2017-05-20 88 views
1

我是Android的初學者。我正試圖在特定日期顯示通知。當我嘗試運行showNotification()我得到以下錯誤的方法:java.lang.RuntimeException:無法啓動接收器

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

我已經嘗試了這個錯誤沒有成功。

ScheduleNotification:

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 !!!! 
} 

Notification_center:

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()); 
} 

回答

1
Notification_center notification = new Notification_center(); 

NEVER創建活動自己的實例,因爲它從來沒有正常工作。

將代碼從showNotification()移到onReceive()。您可以使用傳入onReceive()Context作爲this的替代以及撥打getSystemService()

另外,這裏不需要WakefulBroadcastReceiver。這適用於需要將工作委派給其他人的情況(例如,IntentService)。如果所有工作在onReceive()結束時完成,則不需要管理單獨的WakeLock,這是WakefulBroadcastReceiver的用途。

相關問題