我遇到了一个非常奇怪的问题,广播广播接收器无法在我自己的设备上运行,但在android模拟器上运行。 每当调用onDestroy方法时,我的应用程序通过调用广播接收方来重新启动服务是什么。 我什至尝试查看设备上的开发人员选项,以查看是否激活了一些限制(例如“不保留活动”),但未选中该限制。
Xml文件
<service
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorService"
android:enabled="true">
</service>
<receiver
android:name="oak.shef.ac.uk.testrunningservicesbackgroundrelaunched.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="SensorRestarterBroadcastReceiver" />
</intent-filter>
</receiver>
服务
public class SensorService extends Service {
private Timer timer;
MyThread myThread;
private TimerTask timerTask;
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myThread = new MyThread();
myThread.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
Intent restartService = new Intent("SensorRestarterBroadcastReceiver");
sendBroadcast(restartService);
timer.cancel();
myThread.interrupt();
}
public class MyThread extends Thread{
@Override
public void run() {
// TODO Auto-generated method stub
try {
int delay = 10000; // delay for 10 sec.
int period = 10000; // repeat every 10 sec.
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
}, delay, period);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
广播接收器
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(),
"Restarting Service");
context.startService(new Intent(context, SensorService.class));;
}
}