2014-02-26 2 views
0

저는 특정 시간 동안 앱이 유휴 상태인지 (백그라운드에서) 있는지 확인하고 주어진 시간을 초과하면 앱을 종료하는 서비스를 개발 중입니다. 또한 사용자가 활동을 다시 가져온 경우 타이머가 재설정됩니다.일정 시간 동안 유휴 상태에서 android app를 죽일 타이머?

내 앱에 활동이 거의 없다면 문제가 발생할 수 있습니다. 어떻게해야합니까? 비슷한 코드를 발견했지만 내 경우에 맞게 조정하는 방법은 무엇입니까? 감사.

샘플 코드 :

시간 제한 클래스와 그 서비스

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

궁금한 점 : 왜 앱의 배경 상태를 관리해야한다고 생각하십니까? 안드로이드는 그걸 자동으로 처리합니다 ... – 2Dee

+0

유휴 상태이면 앱이 죽지 않을 것 같습니다 – user782104

+0

그러면 시스템에 메모리가 필요하지 않을 것입니다 ... 왜 시스템의 능력을 활용하지 않고 앱을 죽이고 싶습니까? 사용자가 다시 전환 할 때 앱의 상태를 복구하려면 어떻게해야합니까? – 2Dee

답변

1
당신은 다시 가져올 때

당신은 handler.postDelayed (실행 가능한, 시간) 등을 사용할 수 귀하 activity handler.removeCallbacks (runnable)를 호출 할 수 있습니다. postDelayed를 취소 하시겠습니까?

관련 문제