【问题标题】:Keeping the service running indefinitely保持服务无限期运行
【发布时间】:2016-10-19 21:45:26
【问题描述】:

我正在尝试编写一个将在后台运行直到被用户删除的服务,我使用了以下代码:

    Intent activityIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
            activityIntent, 0);

    Notification notification = new Notification.Builder(this).
            setContentTitle(getText(R.string.app_name)).
            setContentText("Doing stuff").
            setContentInfo("").
            setSmallIcon(R.drawable.icon).
            setDeleteIntent(createOnDismissedIntent(getBaseContext(), notId)).
            setContentIntent(pendingIntent).build();



    notificationManager.notify(notId,notification);

    return START_REDELIVER_INTENT;

该服务应该侦听传入的 SMS,然后在检测到 SMS 后执行某些操作。 现在它可以工作了,但是如果我稍等片刻,然后尝试向自己发送一条短信以查看服务是否仍在运行,该服务不会做任何暗示服务已关闭的事情(我认为),所以我的问题是, 如果我使用“START_REDELIVER_INTENT”,为什么服务会关闭? -我删除了服务中 onDestroy 函数中的通知。因此,虽然服务在一段时间后停止工作,但通知仍然存在,这意味着服务尚未被销毁

【问题讨论】:

  • 一个服务可以随时终止,以便为其他应用腾出空间。系统最终会尝试重新启动它,但您必须处理它不可用的情况。

标签: android android-intent service notifications


【解决方案1】:

重启后需要自动重启服务。

清单:

<service android:exported="false" android:name=".service.YourService" android:enabled="true"></service>
  <receiver android:name=".service.YourBootReceiver">
      <intent-filter>
         <action android:name="android.intent.action.BOOT_COMPLETED"/>
      </intent-filter>

还有权限:

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

定义接收者:

public class YourBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        Intent serviceIntent = new Intent(arg0, YourService.class);
        arg0.startService(serviceIntent);
    }

【讨论】:

  • 感谢您的回答,但我的主要问题是为什么服务会在一段时间后停止?
  • 稍后我会检查你的代码,但我使用的是我的,没问题,我的服务一直在工作。
猜你喜欢
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多