这是我的通知构建器:
public void CustomNotification() {
// Using RemoteViews to bind custom layouts into Notification
RemoteViews remoteViews = new RemoteViews(getPackageName(),
R.layout.customnotification);
// Set Notification Title
String strtitle = getString(R.string.customnotificationtitle);
// Set Notification Text
String strtext = getString(R.string.customnotificationtext);
Intent intent = new Intent(this, Main2Activity.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
// Set Icon
.setSmallIcon(R.mipmap.ic_launcher)
// Set Ticker Message
.setTicker(getString(R.string.customnotificationticker))
// Dismiss Notification
.setOngoing(true)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Set RemoteViews into Notification
.setContent(remoteViews);
// Locate and set the Images
remoteViews.setImageViewResource(R.id.imagenotileft, R.mipmap.ic_launcher);
remoteViews.setImageViewResource(R.id.imagenotiright, R.mipmap.ic_launcher);
remoteViews.setTextViewText(R.id.title, getString(R.string.customnotificationtitle));
remoteViews.setTextViewText(R.id.text, getString(R.string.customnotificationtext));
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
现在的问题是:
点击通知时是否可以启动主屏幕( device home
)(或点击通知时用户被带回主屏幕)?如果是,那么如何?
答案 0 :(得分:0)
嘿,请使用此代码来解决您的问题,在pendingIntent中提及您的活动。
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse(
"android.resource://"
+ context.getPackageName()
+ "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}