2017-07-24 44 views
1

我想在Android模擬器上添加一個簡單的通知。我在android開發者網站上取得了Notifications的代碼。我已經使用代碼在仿真器上運行,但沒有通知。我是否缺少任何許可或某種設置,任何人都可以請幫助我。模擬器上的通知不起作用

public class SampleNotificationActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_sample_notification); 
} 


@Override 
protected void onResume() { 
    super.onResume(); 
    sendNotification(); 
} 

private void sendNotification() { 
    NotificationCompat.Builder notificationBuilder 
      = new NotificationCompat.Builder(SampleNotificationActivity.this) 
      .setSmallIcon(R.mipmap.ic_launcher) 
      .setContentTitle("Notification cool") 
      .setContentText("My Very first Notification"); 
    Intent resultIntent = new Intent(this, NotificationActivity.class); 


    TaskStackBuilder stackBuilder = TaskStackBuilder.create(SampleNotificationActivity.this); 
    stackBuilder.addParentStack(NotificationActivity.class); 
    stackBuilder.addNextIntent(resultIntent); 

    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
    notificationBuilder.setContentIntent(resultPendingIntent); 

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.notify(100, notificationBuilder.build()); 
} 

}

+1

可以添加完整的代碼,看看滿級? –

+0

@BrunoFerreira,我添加了活動類 – MaheshGupta

+0

如果將sendnotification添加到oncreate,會發生什麼情況。 –

回答

0

我不知道,如果是這樣的問題,但可能是你忘記了創建掛起的意圖正確

你有

PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); 
    notificationBuilder.setContentIntent(resultPendingIntent); 

嘗試變化到:

PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(this,0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT); 
    notificationBuilder.setContentIntent(resultPendingIntent); 
+0

啊......代碼正在使用API​​ 24的Device和Emulator上工作。問題出在模擬器上,我有API 26.感謝您的幫助@Bruno – MaheshGupta