android– 当应用关闭时,服务停止工作

android– 当应用关闭时,服务停止工作,第1张

概述在这里,我实现了使用Text-To-Speech读取传入推送通知消息的功能.我为它创建了一个单独的服务类,它工作正常,一段时间后会收到通知,但它会停止读取通知.publicclassTTSServiceextendsServiceimplementsTextToSpeech.OnInitListener{privatestaticfinalStringTAG="T

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

public class TTSService extends Service implements TextToSpeech.OnInitListener {private static final String TAG = "TTSService";private String mSpeechMessage;private TextToSpeech mTts;@OverrIDepublic IBinder onBind(Intent arg0) {    return null;}@OverrIDepublic voID onCreate() {    mTts = new TextToSpeech(this,            this  // OnInitListener    );    mTts.setSpeechRate(1f);    super.onCreate();}@OverrIDepublic voID onDestroy() {    // Todo auto-generated method stub    if (mTts != null) {        mTts.stop();        mTts.shutdown();    }    super.onDestroy();}@OverrIDepublic 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);}@OverrIDepublic 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();}@OverrIDepublic 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" />

在Tag中添加此内容.

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

希望这有帮助.. 总结

以上是内存溢出为你收集整理的android – 当应用关闭时,服务停止工作全部内容,希望文章能够帮你解决android – 当应用关闭时,服务停止工作所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1101689.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存