[英]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.