我该如何使用AlarmManager调用Activity的特定方法,就我而言,我需要在知道两个小时后通过调用Activity的KillMyServer方法来停止服务。
我不能使用Timer或postDelayed,因为如果应用程序进入后台,Android可能会在一段时间后将其关闭,但AlarmManager会幸免。

最佳答案

为什么在这里使用闹钟?您可以通过在Service上调用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);
    }
}

10-08 06:14