2014-02-26 113 views
0

我正在研究一項服務,該服務將檢查應用程序是否在特定時間內處於閒置狀態(在後臺),如果應用程序超過了指定時間,則會終止該應用程序。此外,如果用戶已恢復活動,則會重置計時器計時器會在閒置一段時間後殺死android應用程序嗎?

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

示例代碼:

超時類及其服務

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()); 
+0

只是好奇:爲什麼你認爲你需要管理你的應用程序的背景狀態? Android會自動... – 2Dee

+0

似乎應用程序永遠不會被殺死,如果它處於空閒狀態 – user782104

+0

然後系統可能不需要內存...爲什麼你想殺死應用程序,而不是利用系統的能力當用戶切換到它時恢復您的應用程序的狀態? – 2Dee

回答

1

當你帶回你可以使用handler.postDelayed(可運行,時間)和您活動你可以調用handler.removeCallbacks(runnable);取消postDelayed

相關問題