Opening Browser on push notification

前端 未结 1 1878
太阳男子
太阳男子 2020-12-17 21:27

I am trying to open the browser with a url when the user click on the push notification, i search in stackoverflow and i find this

Intent browserIntent = new         


        
相关标签:
1条回答
  • 2020-12-17 21:50

    What you need to do is set a pending intent - which will be invoked when the user clicks the notification. (Above you just started an activity...)

    Here's a sample code :

    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());
    }
    

    Edit 1 : I changed the answer to use PendingIntent.FLAG_UPDATE_CURRENT for the sample purpose. Thanks Aviv Ben Shabat for the comment.

    Edit 2 : Following Alex Zezekalo's comment, note that opening the notification from the lock screen, assuming chrome is used, will fail as explained in the open issue : https://code.google.com/p/chromium/issues/detail?id=455126 -
    Chrome will ignore the intent, and you should be able to find in your logcat - E/cr_document.CLActivity﹕ Ignoring intent: Intent { act=android.intent.action.VIEW dat=http://google.com/... flg=0x1000c000 cmp=com.android.chrome/com.google.android.apps.chrome.Main (has extras) }

    0 讨论(0)
提交回复
热议问题