簡體   English   中英

一個在空閑一段時間后會殺死Android應用程序的計時器?

[英]A timer that will kill android app after idle for certain time?

我正在使用一項服務,該服務將檢查應用程序是否在特定時間(在后台)處於空閑狀態,並在超過指定時間后將其終止。 此外,如果用戶恢復了活動,則它將重置計時器

問題是,如果我的應用程序中很少活動,我該如何實現? 我找到了一些類似的代碼,但是如何調整它以適合我的情況? 謝謝。

示例代碼:

超時類及其服務

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;
    }

}

殺死應用

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

您可以使用handler.postDelayed(runnable,time),當您恢復活動時,可以調用handler.removeCallbacks(runnable);。 取消postDelayed

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM