保持服务无限期运行

时间:2016-10-19 21:45:26

标签: android android-intent service notifications

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

    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;

该服务应该监听传入的短信,然后在检测到短信后再做一些事情。 现在它可以工作,但是如果我等了一会儿然后尝试发送自己的短信来看看服务是否还在运行,服务没有做任何暗示服务失效的事情(我想),所以我的问题是,如果我使用'START_REDELIVER_INTENT',为什么服务会停止? -I删除服务中onDestroy函数的通知。因此,虽然服务在一段时间后停止工作,但通知仍然存在意味着该服务尚未销毁

1 个答案:

答案 0 :(得分: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);
    }