应用关闭后服务停止工作 [英] Service stops working when app gets closed

查看:135
本文介绍了应用关闭后服务停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,我已经实现了使用Text-To-Speech读取传入的推送通知消息的功能.我为此创建了一个单独的服务类,该类可以正常工作,并且会在一段时间后出现通知,但会停止读取通知.

Here I have implemented functionality to read messages of incoming push notifications using Text-To-Speech. I created a separate service class for it which works fine and after a while notifications comes but it stops read notifications.

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以以下方式启动该服务:

And I start this service from FirebaseMessagingService as:

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

如果有人可以帮助,那就太好了.预先感谢.

It would be great if anybody can help. Thanks in advance.

推荐答案

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

From the API level 26, android restricted background service access. You can solve this by starting your service as a foreground.

我的一个项目也遇到了同样的问题,并且使用下面的代码修复了该问题.

I had the same issue with my one project and i have fixed it by using below code.

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" />

将此标签添加到标签中.

Add this inside Tag.

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

希望此帮助..:)

这篇关于应用关闭后服务停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆