一个计时器,在空闲一段时间后会杀死Android应用程序?

时间:2014-02-26 09:37:27

标签: android android-intent service timeout

我正在研究一项服务,该服务将检查应用程序是否在一段时间内处于空闲状态(在后台),如果超过指定时间则终止应用程序。此外,如果用户已将活动恢复,则会重置计时器

问题是,如果我的应用程序中的活动很少,我该如何实现?我发现了一些类似的代码,但如何调整它以适应我的情况?感谢。

示例代码:

超时类及其服务

public class Timeout {
    private static final int REQUEST_ID = 0;
    private static final long DEFAULT_TIMEOUT = 5 * 60 * 1000;  // 5 minutes

    private static PendingIntent buildIntent(Context ctx) {
        Intent intent = new Intent(Intents.TIMEOUT);
        PendingIntent sender = PendingIntent.getBroadcast(ctx, REQUEST_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        return sender;
    }

    public static void start(Context ctx) {
        ctx.startService(new Intent(ctx, TimeoutService.class));

        long triggerTime = System.currentTimeMillis() + DEFAULT_TIMEOUT;

        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);

        am.set(AlarmManager.RTC, triggerTime, buildIntent(ctx));
    }

    public static void cancel(Context ctx) {
        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);

        am.cancel(buildIntent(ctx));

        ctx.startService(new Intent(ctx, TimeoutService.class));

    }

}



public class TimeoutService extends Service {
    private BroadcastReceiver mIntentReceiver;

    @Override
    public void onCreate() {
        super.onCreate();

        mIntentReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();

                if ( action.equals(Intents.TIMEOUT) ) {
                    timeout(context);
                }
            }
        };

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intents.TIMEOUT);
        registerReceiver(mIntentReceiver, filter);

    }

    private void timeout(Context context) {
        App.setShutdown();

        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.cancelAll();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mIntentReceiver);
    }

    public class TimeoutBinder extends Binder {
        public TimeoutService getService() {
            return TimeoutService.this;
        }
    }

    private final IBinder mBinder = new TimeoutBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

}

杀死app

android.os.Process.killProcess(android.os.Process.myPid());

1 个答案:

答案 0 :(得分:1)

你可以使用handler.postDelayed(runnable,time),当你带回你的活动你可以调用handler.removeCallbacks(runnable);取消postDelayed