我想將我的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());
}
}
UPDATE
我試圖從呼叫者類,這是在同一個包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「'您的應用程序包名稱? –