我在我们的应用程序中使用Background服务:
public class BackgroundService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(r, 5000);
return START_STICKY;
}
Handler handler = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
handler.postDelayed(r, 5000);
Log.d("arpit", "connected");
}
};
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent restartServiceIntent = new Intent(Appclass.getInstance().getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(Appclass.getInstance()
.getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
}
}
它工作正常,如果我关闭或杀死应用程序也可以。
但是在某些设备上,例如oppo A33F
,Lenovo Vibe K5
等推送通知未通过,并且杀死应用程序后服务类也会被销毁。我检查了设备的running application
部分,但我的应用程序没有显示服务类在销毁应用程序后被销毁的方式。即使应用程序被杀,我怎样才能解决这个问题并保持我的服务不断运行。