9

当用户单击推送通知时,我正在尝试使用 url 打开浏览器,我在 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);
}
4

1 回答 1

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:忽略意图:Intent { act=android.intent.action.VIEW dat= http://google.com / ... flg=0x1000c000 cmp=com.android.chrome/com.google.android.apps.chrome.Main(有附加功能)}

于 2013-05-13T16:16:31.447 回答