我一直在搜索整个网络,以了解为什么我的后台服务无法正常工作。当我关闭应用程序时,该服务将被杀死,而不会从Brodcast Receiver中被调回。本指南:https://www.quora.com/How-do-I-keep-an-app-running-in-the-background-in-MIUI显示了三种不同的方法,但没有一种对我有用。我确信该应用程序可以正常运行,因为它可以与仿真器(相同的API 24)正常工作,并且还可以与华为(同样的API)一起工作。
XML
<service
android:name="com.arvi.neverendingbackgroundservice.SensorService"
android:enabled="true"
android:exported="true"
android:stopWithTask="false">
</service>
<receiver
android:name="com.arvi.neverendingbackgroundservice.SensorRestartBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
</intent-filter>
</receiver>
服务
public class SensorService extends Service {
private Context ctx;
TimerCounter tc;
private int counter = 0;
private static final String TAG = SensorService.class.getSimpleName();
public SensorService() {
}
public SensorService(Context applicationContext) {
super();
ctx = applicationContext;
Log.i(TAG, "SensorService class");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "onCreate()");
tc = new TimerCounter();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.i(TAG, "onStartCommand()");
tc.startTimer(counter);
return START_STICKY;
}
@Override
public void onDestroy() {
Log.i(TAG, "serviceOnDestroy()");
super.onDestroy();
Intent broadcastIntent = new Intent(getApplicationContext(),SensorRestartBroadcastReceiver.class);
sendBroadcast(broadcastIntent);
tc.stopTimerTask();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
Log.i(TAG, "serviceonTaskRemoved()");
// workaround for kitkat: set an alarm service to trigger service again
Intent intent = new Intent(getApplicationContext(), SensorService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 1, intent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 5000, pendingIntent);
super.onTaskRemoved(rootIntent);
}
@Override
public void onLowMemory() {
super.onLowMemory();
Log.i(TAG, "onLowMemory()");
}
}