模拟器上的通知无效

时间:2017-07-24 17:00:34

标签: android android-notifications

我正在尝试在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 :(得分: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);