android - 应用程序关闭时服务停止工作

标签 android push-notification text-to-speech background-service

在这里,我实现了使用文本转语音读取传入推送通知消息的功能。我为它创建了一个单独的服务类,它工作正常,一段时间后,通知出现,但它停止读取通知。

public class TTSService extends Service implements TextToSpeech.OnInitListener {

private static final String TAG = "TTSService";
private String mSpeechMessage;
private TextToSpeech mTts;

@Override

public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {

    mTts = new TextToSpeech(this,
            this  // OnInitListener
    );
    mTts.setSpeechRate(1f);
    super.onCreate();
}


@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    if (mTts != null) {
        mTts.stop();
        mTts.shutdown();
    }
    super.onDestroy();
}

@Override
public void onStart(Intent intent, int startId) {
    if (intent != null && intent.hasExtra(AppConstant.FEEDBACK_MSG)) {
        mSpeechMessage = intent.getStringExtra(AppConstant.FEEDBACK_MSG);
    }

    speakMessage(mSpeechMessage);

    super.onStart(intent, startId);
}

@Override
public void onInit(int status) {
    Log.v(TAG, "oninit");
    if (status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.US);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
                result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.v(TAG, "Language is not available.");
        } else {

            if (mSpeechMessage != null) {
                speakMessage(mSpeechMessage);
            }
        }
    } else {
        Log.v(TAG, "Could not initialize TextToSpeech.");
    }
}

private void speakMessage(String str) {
    if (str != null) {
        mTts.speak(str,
                TextToSpeech.QUEUE_FLUSH,
                null);
    }

    //Stop Service
    // stopSelf();
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}
}

我从 FirebaseMessagingService 启动此服务:

  private void startTTSService(String message) {
    Intent intent = new Intent(getApplicationContext(), TTSService.class);
    intent.putExtra(AppConstant.FEEDBACK_MSG, message);
    startService(intent);
  }

如果有人能提供帮助,那就太好了。提前致谢。

最佳答案

从API级别26开始,android限制后台服务访问。您可以通过将服务启动为前台来解决此问题。

我的一个项目遇到了同样的问题,我已使用以下代码修复了该问题。

YourService.class

private static final String NOTIFICATION_CHANNEL_ID_DEFAULT = "my_flow_notification_channel_default";

@Override
    public void onCreate() {
        super.onCreate();

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_DEFAULT)
                .setOngoing(false).setSmallIcon(R.drawable.ic_notification).setPriority(Notification.PRIORITY_MIN);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID_DEFAULT,
                    NOTIFICATION_CHANNEL_ID_DEFAULT, NotificationManager.IMPORTANCE_LOW);
            notificationChannel.setDescription(NOTIFICATION_CHANNEL_ID_DEFAULT);
            notificationChannel.setSound(null, null);
            notificationManager.createNotificationChannel(notificationChannel);
            startForeground(1, builder.build());
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO: 
     return START_STICKY;
    }

启动服务

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
     ContextCompat.startForegroundService(context, new Intent(context, YourService.class));
else
     context.startService(new Intent(context, YourService.class));

停止服务

stopService(new Intent(getActivity(), YourService.class));

在 AndroidManifest.xml 中

添加此权限

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

将此添加到标签内。

<service
   android:name=".service.YourService"
   android:enabled="true"
   android:exported="true" />

希望这有帮助..:)

关于android - 应用程序关闭时服务停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55571182/

相关文章:

ios - 如何在推送通知中使用 iPhone 默认铃声和长达 30 秒的持续振动,

java - 加速度计数据中的峰值检测

Android webview 无法正确呈现

android - 如何使用点击监听器和后台 worker 更改 android View 的外观?

android - 不使用第三方 jar 的 2.3 中的 Actionbar 实现

java - android: TextToSpeech 泄漏服务连接

iOS 推送通知不适用于带有 Test Flight 的临时分发

ios - APNS修改通知为静默通知

delphi - 将 SAPI 文本转语音本地化为西类牙语

c++ - 在 SAPI 中说出进度事件