[英]Android - Launching an activity from service after force stop / crash
我正在開發一個倒數計時器應用程序,並希望在時間完成后啟動活動以開始一切正常,但是在我強制停止該應用程序后,它顯示NullPointerException
。 我不知道為什么它顯示了這一點。 這是我的java代碼
public int onStartCommand(Intent intent, int flags, int startId) {
handler = new Handler();
x=1;
//final TimerService timerService=this;
r = new Runnable() {
@Override
public void run() {
try {
if ((minutes >= 0) && (seconds >= 0) && (minutes <= 59) && (seconds <= 59)) {
if (seconds == 0 && minutes > 0) {
minutes--;
seconds = 59;
} else if (seconds == 0 && minutes == 0) {
try {
mins.setEnabled(true);
secs.setEnabled(true);
Intent ring = new Intent(getApplicationContext(), TimerComplete.class);
ring.setAction(Intent.ACTION_VIEW);
ring.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ring.setComponent(new ComponentName(getApplicationContext().getPackageName(), TimerComplete.class.getName()));
timerService.startActivity(ring);
stopSelf();
handler.removeCallbacks(this);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
mins.setText(String.format("%02d", minutes));
secs.setText(String.format("%02d", seconds));
if (seconds != 0) {
seconds--;
x++;
handler.postDelayed(this, 1000);
}
} else {
mins.setEnabled(true);
secs.setEnabled(true);
mins.setText("00");
secs.setText("00");
handler.removeCallbacks(this);
Toast.makeText(getApplicationContext(), "Invalid Time", Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
};
handler.post(r);
return START_REDELIVER_INTENT;
}
該函數是靜態嵌套類的,我使用的所有視圖都是外部類的
您可以使用計時器並設置1秒的延遲
int myTimeCounter = 60;
Timer myTimer = new Timer();
private void startRepeatedTask() {
myTimer.scheduleAtFixedRate(new TimerTask() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (myTimeCounter == 0) {
myTimer.cancel();
callActivity();
return;
}
//Log.d(TAG, "timer=" + String.valueOf(myTimeCounter));
myTimeCounter--;
}
});
}
}, 0, 1000);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.