2012-11-06 45 views
1

由於用戶處於非活動狀態,15分鐘後如何在android中使用timer進行自動註銷?由於在android中不活動而導致15分鐘後自動註銷

我使用這個婁代碼在我loginActivity.java

public class BackgroundProcessingService extends Service { 

     @Override 
     public IBinder onBind(Intent intent) { 
      // TODO Auto-generated method stub 
     timer = new CountDownTimer(5 *60 * 1000, 1000) { 

       public void onTick(long millisUntilFinished) { 
        //Some code 
        //inactivity = true; 
        timer.start(); 
        Log.v("Timer::", "Started"); 
       } 

       public void onFinish() { 
        //Logout 
        Intent intent = new Intent(LoginActivity.this,HomePageActivity.class); 
        startActivity(intent); 
        //inactivity = false; 
        timer.cancel(); 
        Log.v("Timer::", "Stoped"); 
       } 
      }; 
      return null; 
     } 

    } 

和的onclick登錄按鈕的我呼籲服務的意圖。

​​

請指點......

此類型的錯誤消息之後15分鐘

所示

This type of error message is shown after 15 mins

+0

我相信你正在尋找不活動,而不是anactivity – Krishnabhadra

+0

@Krishnabhadra是其不活動。 – Rash

+0

啓動一項服務並在其中啓動一個計時器並在那裏處理您的會話。 –

回答

6

使用CountDownTimer

CountDownTimer timer = new CountDownTimer(15 *60 * 1000, 1000) { 

     public void onTick(long millisUntilFinished) { 
      //Some code 
     } 

     public void onFinish() { 
      //Logout 
     } 
    }; 

當用戶有停止任何操作使用timer.start()並且當用戶執行操作時做timer.cancel()

+0

我已經編輯了我的代碼,請指教..... – Rash

+0

@Rash Ibinder用於進程間通信的地方codein'startservice()'服務的方法。這裏是一些服務http://www.vogella.com/articles/AndroidServices/article.html的教程,當計時器結束時,即onFinish()方法調用'stopself()'來停止服務並執行你需要這樣做 –

+0

@Rash以上是如果你需要使用服務,但我不認爲你需要使用我的代碼服務,我建議它在默認情況下在不同的線程中工作。代替'startService(intent1);'你可以使用'timer.start()'啓動計時器 –

1

你可以啓動一個服務並啓動一個定時器。每15分鐘檢查一次標誌,假設inactivity標誌設置爲true。如果是,從應用程序註銷。

每當用戶與您的應用進行交互時,將inactivity標誌設置爲false。

+0

我已編輯我的代碼請諮詢..... – Rash

3

我同意Girish在上面的答案。皮疹爲您的方便,我與你分享代碼。

public class LogoutService extends Service { 
     public static CountDownTimer timer; 
    @Override 
    public void onCreate(){ 
     super.onCreate(); 
      timer = new CountDownTimer(1 *60 * 1000, 1000) { 
       public void onTick(long millisUntilFinished) { 
        //Some code 
        Log.v(Constants.TAG, "Service Started"); 
       } 

       public void onFinish() { 
        Log.v(Constants.TAG, "Call Logout by Service"); 
        // Code for Logout 
        stopSelf(); 
       } 
      }; 
    } 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 
} 

在每個活動中添加以下代碼。

@Override 
protected void onResume() { 
    super.onResume(); 

    LogoutService.timer.start(); 
} 

@Override 
protected void onStop() { 
    super.onStop(); 
    LogoutService.timer.cancel(); 
} 
+0

這是'服務'在Manifest.xml中導出並啓用。 ? – XoXo

+0

我在LogoutService.timer.start()處得到'NullPointerException' – XoXo

相關問題