2016-12-27 129 views
0

我看幾個例子,但我想不出什麼我做錯了。自動註銷用戶在Android的

Auto logout after 15 minutes due to inactivity in android

看着這個例子後,我創建了延伸服務LogoutService類。另外,我還是得有一個叫我的登錄活動的意圖是什麼?事情是這樣的:

Intent intent = new Intent(getBaseContext(), LoginActivity.class); 
startActivity(intent); 

我LogoutService類

public class LogoutService extends Service { 
public static CountDownTimer timer; 
private final String TAG="Service"; 
    @Override 
    public void onCreate() { 
     // TODO Auto-generated method stub 
     super.onCreate(); 
     timer = new CountDownTimer(1 * 60 * 1000, 1000) { 
      public void onTick(long millisUntilFinished) { 
       //Some code 
       Log.v(TAG, "Service Started"); 
      } 

      public void onFinish() { 
       Log.v(TAG, "Call Logout by Service"); 
       // TODO should I create an Intent 
       // my Login method here? 
       stopSelf(); 
      } 
     }; 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
} 

,並把這個在我的所有其他類:

@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 
    try { 
     LogoutService.timer.start(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

@Override 
protected void onStop() { 
    // TODO Auto-generated method stub 
    super.onStop(); 
    LogoutService.timer.cancel(); 
} 

,但我一直得到一個空指針異常,由於 LogoutService。 timer.cancel();

我與檢查,如果它是空的,但再沒有任何反應,不知道我應該做的if語句包圍它。

回答

0

得到一個零指示字例外由於LogoutService.timer.cancel();

由於LogoutService延伸Service類,但使用startService方法,以便onCreate方法不調用不啓動它和timernull

執行以下操作:

  1. 使用startServicestopService方法

  2. 在服務onDestory()刪除計時器啓動/停止服務。

  3. 添加LogoutService類作爲服務AndroidManifest.xml

+0

應該在哪裏開始/停止方法去?在LogoutService類中? 此外,爲什麼不是的onDestroy中的onStop? – Spider

+0

@Spider:代替'LogoutService.timer.start();'和'LogoutService.timer.cancel();' –

+0

不知道該怎麼做。那麼只需創建一個像這樣的新方法並調用它? public void startService(){ Logout.timer.start(); } – Spider