当用户点击推送通知时,我试图用网址打开浏览器,我在stackoverflow中搜索,我发现这个
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
但它对我不起作用,当我把通知没有出现时,我调试它并且它只抛出类文件编辑器没有错误或任何东西。
这是代码
public void mostrarNotificacion(Context context, String body,String title, String icon, String url,String superior)
{
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notManager = (NotificationManager) context.getSystemService(ns);
int icono = R.drawable.mydrawable;
CharSequence textoEstado = superior;
long hora = System.currentTimeMillis();
Notification notif = new Notification(icono, textoEstado, hora);
Context contexto = context.getApplicationContext();
CharSequence titulo = title;
CharSequence descripcion = body;
PendingIntent contIntent;
if(url.equalsIgnoreCase("NULL"))
{
Intent notIntent = new Intent(contexto,MainActivity.class);
contIntent = PendingIntent.getActivity(
contexto, 0, notIntent, 0);
}
else
{
// Intent i = new Intent(Intent.ACTION_VIEW);
//i.setData(Uri.parse(url));
// contIntent = PendingIntent.getActivity(contexto, 0, i, 0);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);
}
// notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent);
//AutoCancel:
notif.flags |= Notification.FLAG_AUTO_CANCEL;
//send notif
notManager.notify(1, notif);
}
答案 0 :(得分:23)
您需要做的是设置待定意图 - 这将在用户单击通知时调用。 (上面你刚开始一项活动......)
以下是示例代码:
private void createNotification(String text, String link){
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setSmallIcon(R.drawable.app_icon)
.setContentTitle(text);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// pending implicit intent to view url
Intent resultIntent = new Intent(Intent.ACTION_VIEW);
resultIntent.setData(Uri.parse(link));
PendingIntent pending = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pending);
// using the same tag and Id causes the new notification to replace an existing one
mNotificationManager.notify(String.valueOf(System.currentTimeMillis()), PUSH, notificationBuilder.build());
}
编辑1:
为了示例目的,我更改了使用PendingIntent.FLAG_UPDATE_CURRENT
的答案。感谢Aviv Ben Shabat的评论。
编辑2:
根据Alex Zezekalo的评论,请注意从锁定屏幕打开通知,假设使用了Chrome,将失败,如公开问题中所述:https://code.google.com/p/chromium/issues/detail?id=455126 -
Chrome会忽略意图,你应该能够在你的logcat中找到 -
E / cr_document.CLActivity:忽略意图:意图{act = android.intent.action.VIEW dat = http://google.com/ ... flg = 0x1000c000 cmp = com.android.chrome / com.google.android.apps.chrome .Main(有额外的)}