我有服务,在一段时间后做某事。从我的应用程序退出后它必须继续工作,并在rebotting设备后重新启动。 我试着写一些像:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
但服务无法启动。
这是我的服务示例:
public class GetTextService extends IntentService {
public static final String TAG = "testing_intent_service";
private static final int LONG_INTERVAL = 1000 * 10; //10 seconds
private static Context mContext;
private static int debug_i = 0;
public GetTextService() {
super(GetTextService.class.getSimpleName());
}
@Override
protected void onHandleIntent(Intent intent) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isNetworkAvailable = cm.getActiveNetworkInfo() != null;
Log.d(TAG, debug_i + "");
debug_i++;
if (!isNetworkAvailable) return;
//TODO check changes on the site
}
public static void setServiceAlarm(Context context, boolean isOn) {
mContext = context;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, GetTextService.class);
i.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
PendingIntent pi = PendingIntent.getService(context, 1, i, 0);
if (isOn) {
alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), LONG_INTERVAL, pi);
} else {
alarmManager.cancel(pi);
pi.cancel();
}
}
}
所以我在这里运行服务:
@Override
public void onCreate(Bundle savedInstanceState) {
...
if (PrefsManager.isFirstLaunch()) {//my custom helper class
GetTextService.setServiceAlarm(this, true);
}
}
UPD:我使用了BroadcastReceiver,每次启动后都会启动服务。正如我所见,它运作清晰。