【发布时间】:2017-04-14 06:08:55
【问题描述】:
我想将意图设置为我的 MainActivity.class,它与我的 Notification.class 位于不同的包中。我尝试使用 ComponentName 但仍然给我 addParentStack(componentName) 和 NotificationManager 行的 NULL 指针异常。 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference
package com.workdemos.preference;
public class Notification extends AppCompatActivity {
public void pushNotification() {
ComponentName componentName = new ComponentName("com.workdemos.user", "MainActivity");
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("New News")
.setContentText("new news found in your preferred city");
Intent resultIntent = new Intent();
resultIntent.setComponent(componentName);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(componentName);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
}
更新
我尝试从 MainActivity.class 的同一个包中的调用者类发送上下文。
public void pushNotification(Context context) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("New News")
.setContentText("new news found in your preferred city");
Intent resultIntent = new Intent();
resultIntent.setComponent(new ComponentName(context, MainActivity.class));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getBaseContext());
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
这样它通过了之前给我错误的行。但它没有通过 addParentStack(MainActivity.class)。它仍然在该行给我同样的错误。
【问题讨论】:
-
尝试像
ComponentName("com.workdemos.user", "com.workdemos.user.MainActivity");一样更改。在 MainActivity 之前添加您的完整路径。 -
我做到了。还是一样。
-
"com.workdemos.user"是你的应用包名吗? -
应用程序包是 com.workdemos 然后我有多个包(用户、首选项、模型、新闻)。用户中的 MainActivity 和首选项中的 Notification
标签: android push-notification android-notifications