如何使用 AlarmManager 来调用Activity的特定方法,在我的情况下,我需要通过调用我的Activity 的 KillMyServer 方法来停止服务2小时以后知道。 我无法使用计时器或 postDelayed ,因为如果应用程序转到后台,Android可能会在一段时间后将其关闭,但AlarmManager将继续存在。
答案 0 :(得分:1)
为什么在这里使用闹钟?你可以通过在服务上调用stopself()方法来停止服务。
public class MyService extends Service {
public static final String ACTION_START_TIMER = "com.sample.myapp.action.ACTION_START_TIMER";
private TimerReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
receiver = new TimerReceiver();
IntentFilter filter = new IntentFilter(ACTION_START_TIMER);
registerReceiver(receiver, filter);
}
public void runKillTimer() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
stopSelf();
}
}, 2 * 60 * 60 * 1000);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
private class TimerReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
runKillTimer();
}
}
}
public class MyActivity extends Activity {
@Override
protected void onStop() {
super.onStop();
Intent intent = new Intent(MyService.ACTION_START_TIMER);
sendBroadcast(intent);
}
}