我一直在整个网络上搜索,了解为什么我的后台服务无法正常工作。当我关闭应用程序时,服务会被终止,而不会从 Brodcast 接收器中回调。本指南: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()");
}
}