我的应用程序最近遇到了一些崩溃,我想知道是否可能是由于意图上的标记。
当崩溃发生时,应用程序关闭我相信,在休息计时器期间。打开一个片段,然后用户可以单击开始,这将启动一个90秒倒计时器。用户在计时器结束时收到通知,单击该计时器时应将用户带回打开的片段。错误不会经常发生,我不能每次都重新创建它。
这是stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ComponentName.<init>(ComponentName.java:77)
at android.content.Intent.<init>(Intent.java:4913)
at com.bestworkouts.sheikoworkout.Workouts.Week1Mon.showNotification(Week1Mon.java:171)
at com.bestworkouts.sheikoworkout.Workouts.Week1Mon$1.onFinish(Week1Mon.java:147)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:127)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
以下是错误发生的通知(它表示错误发生在Intent intent = new Intent(getActivity(),MyWorkout.class):
public void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext());
builder.setSmallIcon(R.drawable.sheikoicon);
builder.setContentTitle("Sheiko Rest Timer");
builder.setContentText("Rest timer is up, start your set!");
builder.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE);
builder.setAutoCancel(true);
Intent intent = new Intent(getActivity(), MyWorkout.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
stackBuilder.addParentStack(MyWorkout.class);
stackBuilder.addNextIntent(intent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager NM = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
NM.notify(0, builder.build());
}
我开始倒数计时器并调用showNotification:
private void start() {
cancel();
mCountDownTimer = new CountDownTimer(90000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
txtViewRest.setText(millisUntilFinished / 1000 + " Secs");
}
@Override
public void onFinish() {
txtViewRest.setText("Start!");
showNotification();
}
}.start();
}
我想知道它是否与我的FLAG_ACTIVITY_CLEAR_TOP有关?
感谢您的帮助!
答案 0 :(得分:1)
由于您的代码在另一个主题上运行,如果CountDownTimer
完成时Fragment
因任何原因而被关闭,getActivity()
和getContext()
都会返回null
。
您应该将自己的语境保存在Fragment
的{{1}}:
onCreate
然后在private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context= getContext();
// Your code here
}
方法中使用它:
showNotification()