Могу ли я сделать фоновый сервис, который всегда запускает распознавание речи - PullRequest
1 голос
/ 03 ноября 2019

Я хочу создать приложение, которое я мог бы запускать через голос, как siri или google assistant, поэтому, чтобы сделать это, я должен внедрить код в фоновый или основной сервис, который будет запускать распознаватель речи, поэтому это возможно,из-за ограниченности рабочих служб на Android Oreo и выше, это делает меня застрявшим в глуши, и я не настолько профессионален, поэтому я мог сам в этом разобраться

я пытался сделать службу переднего планас IntentService, чтобы он мог работать в фоновом режиме, не останавливая пользовательский интерфейс и распознаватель речи не работал

package com.example.intentservice;

import android.app.IntentService;
import android.app.Notification;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.SystemClock;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;

import java.util.List;
import java.util.Locale;


import static com.example.intentservice.App.CHANNEL_ID;

public class ExampleService extends IntentService {
    public static final String TAG = "ExampleService";
    private PowerManager.WakeLock wakeLock;
    private TextToSpeech textToSpeech;
    private SpeechRecognizer recognizer;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate");


        initRec();
        startListening();

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ExampleService:wakelock");
        wakeLock.acquire();
        Log.e(TAG, "wakelock acquired");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification notification = new Notification.Builder(this, CHANNEL_ID)
                    .setContentTitle("noti")
                    .setContentText("running")
                    .build();
            startForeground(1, notification);
        }
    }

    private void startListening() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,1);
        recognizer.startListening(intent);
    }

    private void initRec() {
        if (SpeechRecognizer.isRecognitionAvailable(this)) {
            recognizer = SpeechRecognizer.createSpeechRecognizer(this);
            recognizer.setRecognitionListener(new RecognitionListener() {
                @Override
                public void onReadyForSpeech(Bundle bundle) {

                }

                @Override
                public void onBeginningOfSpeech() {

                }

                @Override
                public void onRmsChanged(float v) {

                }

                @Override
                public void onBufferReceived(byte[] bytes) {

                }

                @Override
                public void onEndOfSpeech() {

                }

                @Override
                public void onError(int i) {

                }

                @Override
                public void onResults(Bundle bundle) {
                    List<String> res = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
                    Toast.makeText(ExampleService.this, res.get(0), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onPartialResults(Bundle bundle) {

                }

                @Override
                public void onEvent(int i, Bundle bundle) {

                }
            });
        }
    }





    public ExampleService() {
        super("ExampleService");
//        to create service again
        setIntentRedelivery(true);
    }


// this just to test the code
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.e(TAG, "onHandleIntent");
        String string = intent.getStringExtra("key");
        for (int i = 0; i < 10; i++) {
            Log.e(TAG, string + "-" + i);
//            Toast.makeText(this, "i", Toast.LENGTH_SHORT).show();
            SystemClock.sleep(1000);

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.e(TAG, "onDestroy");
        wakeLock.release();
        Log.e(TAG, "wakelock realised");
    }
}
...