我知道这不是一个新的问题,我认为它与其他人稍有不同,在这里尝试从pendingIntent中取消当前警报,但在我的情况下,应用程序崩溃了。
在此应用中,我试图停止单击按钮时的警报。但是出现以下错误。
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at android.content.ContextWrapper.getPackageName(ContextWrapper.java:132)
at android.content.ComponentName.<init>(ComponentName.java:128)
at android.content.Intent.<init>(Intent.java:4900)
at com.aviz.www.reminder.Activity_Classes.AlarmActivity.stopAlarm(AlarmActivity.java:132)
at com.aviz.www.reminder.Activity_Classes.WakeUpScreen$1.onClick(WakeUpScreen.java:44)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
AlarmActivity.java
public void stopAlarm() {
Intent intent = new Intent(AlarmActivity.this, AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(AlarmActivity.this, mAlarmId, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(this.ALARM_SERVICE);
alarmManager.cancel(alarmIntent);
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context,WakeUpScreen.class);
context.startActivity(intent1);
Uri alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
if (alarmUri == null) {
alarmUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
}
Ringtone ringtone = RingtoneManager.getRingtone(context, alarmUri);
ringtone.play();
}
}
WakeUpScreen.java
mStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alarmActivity.stopAlarm();
}
});
我尝试了一些与错误有关的解决方案,但我无法解决,有人可以帮助我解决此问题。
答案 0 :(得分:0)
执行此操作以取消警报
public static void cancelReminder(Context context,Class<?> cls)
{
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE_2, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}