我已经阅读了关于这个主题的每个Stackoverflow答案,但它们都没有奏效.
问题:每当我的设备处于睡眠模式一小时或更长时间时,服务就会被终止
返回START_STICKY
从onStartCommand()
使用startForeground()
public int onStartCommand(Intent intent, int flags, int startId) {
notification = makeStickyNotification(); //I've simplified the irrelevant code, obviously this would be a real notification I build
startForeground(1234, notification);
return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)这样工作正常,它甚至可以在设备内存不足时重新启动我的服务,但这还不足以解决我的设备暂停一段时间后出现的问题.
在onCreate()
我的Activity和onStartCommand()
我的服务中使用Alarm Manager 来调用调用我的服务的广播接收器
Intent ll24 = new Intent(this, AlarmReceiver.class);
PendingIntent recurringLl24 = PendingIntent.getBroadcast(this, 0, ll24, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000*60, recurringLl24); // Every minute
Run Code Online (Sandbox Code Playgroud)这有助于保持我的服务活跃,但同样,不能解决我的问题
使用Schedule Task Executor使其保持活动状态
if (scheduleTaskExecutor …
Run Code Online (Sandbox Code Playgroud)我有一个Android Service类,其代码如下:
public class LoginService extends Service {
BroadcastReceiver wifiStateChangeReciever;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("AndroidLearning", "Service onStartCommand Started.");
return Service.START_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.i("AndroidLearning", "Service Started.");
final IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
wifiStateChangeReciever = new WifiStateChangeReciever();
this.registerReceiver(wifiStateChangeReciever, intentFilter, null, null);
Log.i("AndroidLearning", "Reciever Registered.");
}
@Override
public void onDestroy() {
Log.i("AndroidLearning", "Service Destroyed.");
this.unregisterReceiver(wifiStateChangeReciever);
}
@Override
public void onTaskRemoved(Intent …
Run Code Online (Sandbox Code Playgroud)