Android的服务START_STICKY START_NOT_STICKY [英] android service START_STICKY START_NOT_STICKY

查看:1518
本文介绍了Android的服务START_STICKY START_NOT_STICKY的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让我的服务始终在后台运行。而我开始用startService()函数的服务。我不想重新启动服务,无论是应用程序的状态。

I need to keep my service always running in background. And starting my service with "startService()" function. I don't want to restart service whatever is Application's state.

下面是我的看法。

START_STICKY>如果应用程序启动,服务重新启动。和服务正在重新启动自己,当应用程序关闭了。

START_STICKY > if application starts , service is restarting. And service is restarting itself when application closes , too.

START_NOT_STICK>服务无法正常工作的应用程序关闭后。

START_NOT_STICK > service doesn't work after application closed.

我需要它总是运行服务,它会接收广播时,应用程序启动。服务状态musn't依赖,如果应用程序正在运行或不。

I need a service which always running , and it will receive broadcast when application starts. Services status musn't depend if application is running or not.

您能帮我吗?

感谢。

推荐答案

您将要设置其启动的报警服务(这将间歇性地醒来,并确保你的服务是否正在运行)的设备启动时,启动接收器。报警接收器应该唤醒每分钟(左右),看看你的服务还没有被清理搭载Android(这会发生不时)。

you will want to set a BOOT receiver which starts your Service ALARM (which will wake up intermittently and make sure your Service is running) when the device boots. The ALARM receiver should wakes up every minute (or so) to see that your Service hasn't been cleaned up by Android (which will happen from time to time).

您会想要一个BootReceiver开始你的报警,将是这样的:

You'll want a BootReceiver to start your alarm that will look like this:

public class BootReceiver extends BroadcastReceiver {
    @Override
       public void onReceive(Context context, Intent intent) {

          AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
          PendingIntent pendingIntent =
                   PendingIntent.getBroadcast(context, 0, new Intent(context, AlarmReceiver.class), 0);

          alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 2000,  60000, pendingIntent);
       }
    }

和一个alarmReceiver是这样的:

And an alarmReceiver would look like this:

public class AlarmReceiver extends BroadcastReceiver {
    private String TAG = "AlarmReceiver";
   // onReceive must be very quick and not block, so it just fires up a Service
   @Override
   public void onReceive(Context context, Intent intent) {     
      Intent i = new Intent(context, MyLovelyService.class);      
      PendingIntent.getService(context, 0,i, 0).send();    
   }
}

和最后这需要进入你的清单:

and lastly this needs to go into your manifest:

<receiver android:name=".BootReceiver">
  <intent-filter>
     <action android:name="android.intent.action.BOOT_COMPLETED" />
  </intent-filter>
 </receiver>

 <receiver android:name=".AlarmReceiver" />

这篇关于Android的服务START_STICKY START_NOT_STICKY的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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