gpt4 book ai didi

android - java.lang.RuntimeException : Unable to start receiver 错误

转载 作者:行者123 更新时间:2023-11-30 00:32:15 24 4
gpt4 key购买 nike

我是 Android 的初学者。我正在尝试在特定日期显示通知。当我尝试运行 showNotification() 方法时,出现以下错误:

java.lang.RuntimeException: Unable to start receiver com.example.azernax.dforget.ScheduleNotification: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

我已尝试修复此错误但未成功。

日程通知:

public class ScheduleNotification extends WakefulBroadcastReceiver {

private AlarmManager alarmManager;

@Override
public void onReceive(Context context, Intent intent) {
ScheduleNotification.completeWakefulIntent(intent);

//create notification to show !!!
Toast.makeText(context, "TEST schedule!!!! ", Toast.LENGTH_LONG).show();
Notification_center notification = new Notification_center();
notification.showNotification(); //######################### CRASH !!!!
}

通知中心:

public class Notification_center extends AppCompatActivity {

public void showNotification()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.icon);
builder.setContentTitle("dF Notification!");
builder.setContentText("description"); //--description event--

Intent intent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(intent);

PendingIntent pendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManager NM = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NM.notify(0,builder.build());
}

最佳答案

Notification_center notification = new Notification_center();

永远不要自己创建 Activity 的实例,因为它永远无法正常工作。

将代码从 showNotification() 移到 onReceive() 中。您可以使用传递给 onReceive()Context 替代 this 和调用 getSystemService().

另外,这里你不需要WakefulBroadcastReceiver。这适用于您需要将工作委托(delegate)给其他东西的情况(例如,IntentService)。如果所有工作都在 onReceive() 结束时完成,则不需要管理单独的 WakeLock,这就是 WakefulBroadcastReceiver 是为了。

关于android - java.lang.RuntimeException : Unable to start receiver 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44086412/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com