How to open url in external browser on Tap on android push notifications?

huangapple go评论76阅读模式
英文:

How to open url in external browser on Tap on android push notifications?

问题

I am trying to open the browser with a URL when the user clicks on the push notification, I searched on Stack Overflow and found this:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);

But it doesn't work for me.

I am searching for a solution for the last 5 days but failed to find one.

Here is my code:

public class MyFirebaseMessagingService extends FirebaseMessagingService {

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
    notificationIntent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.example.android"));
    startActivity(notificationIntent);

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);

    int notificationId = new Random().nextInt(60000);
    Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("image-url"));

    Intent likeIntent = new Intent(Intent.ACTION_VIEW);
    likeIntent.putExtra(NOTIFICATION_ID_EXTRA, notificationId);
    likeIntent.putExtra(IMAGE_URL_EXTRA, remoteMessage.getData().get("image-url"));
    PendingIntent likePendingIntent = PendingIntent.getService(this, notificationId + 1, likeIntent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        setupChannels();
    }

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
            .setLargeIcon(bitmap)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setStyle(new NotificationCompat.BigPictureStyle()
                    .setSummaryText(remoteMessage.getData().get("message"))
                    .bigPicture(bitmap)) /*Notification with Image*/
            .setContentText(remoteMessage.getData().get("message"))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .addAction(R.drawable.ic_favorite_true,
                    getString(R.string.notification_add_to_cart_button), likePendingIntent)
            .setContentIntent(pendingIntent);

    notificationManager.notify(notificationId, notificationBuilder.build());
}

Looking for any help.

英文:

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 Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(browserIntent);

but it doesnt work for me.<br />
I am searching for the solution for last 5 days but failed to find the one.<br />
Here is my code<br />

public class MyFirebaseMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// Intent notificationIntent = new Intent(this, HomeActivity.class);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(&quot;https://play.google.com/store/apps/details?id=com.example.android&quot;));
startActivity(notificationIntent);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get(&quot;image-url&quot;));
Intent likeIntent = new Intent(Intent.ACTION_VIEW);
likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
likeIntent.putExtra(IMAGE_URL_EXTRA,remoteMessage.getData().get(&quot;image-url&quot;));
PendingIntent likePendingIntent = PendingIntent.getService(this,
notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.O) {
setupChannels();
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, ADMIN_CHANNEL_ID)
.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(remoteMessage.getData().get(&quot;title&quot;))
.setStyle(new NotificationCompat.BigPictureStyle()
.setSummaryText(remoteMessage.getData().get(&quot;message&quot;))
.bigPicture(bitmap))/*Notification with Image*/
.setContentText(remoteMessage.getData().get(&quot;message&quot;))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.addAction(R.drawable.ic_favorite_true,
getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}

Looking for any help..

答案1

得分: 2

以下是您提供的代码的翻译部分:

无论您到目前为止尝试了什么都相当正确我在一个示例Android应用程序上尝试了您的代码

package com.example.notificationapp;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;

import java.util.Random;

public class MainActivity extends AppCompatActivity {
    private static final String NOTIFICATION_CHANNEL_ID = "通知渠道名称";
    private static final String NOTIFICATION_CHANNEL_NAME = "通知";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Intent notificationIntent = new Intent(this, HomeActivity.class);

        Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
        notificationIntent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.example.android"));
        startActivity(notificationIntent);

        notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_ONE_SHOT);

        int notificationId = new Random().nextInt(60000);
//        Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get("image-url"));

//        Intent likeIntent = new Intent(Intent.ACTION_VIEW);
//        likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
//        likeIntent.putExtra(IMAGE_URL_EXTRA, remoteMessage.getData().get("image-url"));
//        PendingIntent likePendingIntent = PendingIntent.getService(this,
//                notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            final NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);

            notificationManager.createNotificationChannel(notificationChannel);
        }

        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                        //.setLargeIcon(bitmap)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("一些随机标题")
//                        .setStyle(new NotificationCompat.BigPictureStyle()
//                                .setSummaryText("来自远程消息的消息")
//                                .bigPicture(bitmap))/*带有图片的通知*/
                        .setContentText("在内容文本中添加一些文本")
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
//                        .addAction(R.drawable.ic_favorite_true,
//                                getString(R.string.notification_add_to_cart_button),likePendingIntent)
                        .setContentIntent(pendingIntent);

        notificationManager.notify(notificationId, notificationBuilder.build());
    }
}

请注意,我已经将代码中的引号(")翻译为正常的双引号(")以便更好地理解。如果您需要进一步的翻译或有其他问题,请随时提出。

英文:

Whatever you have tried so far is pretty correct. I've tried your code on a sample android app,

package com.example.notificationapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private static final String NOTIFICATION_CHANNEL_ID = &quot;Notification Channel Name&quot;;
private static final String NOTIFICATION_CHANNEL_NAME = &quot;Notifications&quot;;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Intent notificationIntent = new Intent(this, HomeActivity.class);
Intent notificationIntent = new Intent(Intent.ACTION_VIEW);
notificationIntent.setData(Uri.parse(&quot;https://play.google.com/store/apps/details?id=com.example.android&quot;));
startActivity(notificationIntent);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_ONE_SHOT);
int notificationId = new Random().nextInt(60000);
//        Bitmap bitmap = getBitmapfromUrl(remoteMessage.getData().get(&quot;image-url&quot;));
//        Intent likeIntent = new Intent(Intent.ACTION_VIEW);
//        likeIntent.putExtra(NOTIFICATION_ID_EXTRA,notificationId);
//        likeIntent.putExtra(IMAGE_URL_EXTRA, remoteMessage.getData().get(&quot;image-url&quot;));
//        PendingIntent likePendingIntent = PendingIntent.getService(this,
//                notificationId+1,likeIntent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
final NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID,
NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(notificationChannel);
}
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
//.setLargeIcon(bitmap)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(&quot;some random title&quot;)
//                        .setStyle(new NotificationCompat.BigPictureStyle()
//                                .setSummaryText(&quot;message from remote message&quot;)
//                                .bigPicture(bitmap))/*Notification with Image*/
.setContentText(&quot;Adding some text within content text&quot;)
.setAutoCancel(true)
.setSound(defaultSoundUri)
//                        .addAction(R.drawable.ic_favorite_true,
//                                getString(R.string.notification_add_to_cart_button),likePendingIntent)
.setContentIntent(pendingIntent);
notificationManager.notify(notificationId, notificationBuilder.build());
}
}

This is what I see,

How to open url in external browser on Tap on android push notifications?

So I see the browser is getting opened with the url specified.

I highly suspect your onMessageReceived method within MyFirebaseMessagingService is not invoked. Please add a log message within onMessageReceived and see if you are getting invoked that can possibly be the next thing to do if you haven't tried already.

答案2

得分: 1

I'm using this snippet and It's working well:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    super.onMessageReceived(remoteMessage)
    Log.d("TAG", "From: ${remoteMessage.from}")

    // Check if message contains a data payload.
    if (remoteMessage.data.isNotEmpty()) {
        Log.i("TAG", "Message data payload: ${remoteMessage.data}")
    }

    if (/* Check if data needs to be processed by long-running job */ true) {
        handleNow(remoteMessage)
    }
    // Check if the message contains a notification payload.
    remoteMessage.notification?.let {
        Log.d("TAG", "Message Notification Body: ${it.body}")
    }

    // Also, if you intend to generate your notifications as a result of a received FCM
    // message, here is where that should be initiated. See the sendNotification method below.
}

private fun handleNow(remoteMessage: RemoteMessage) {
    try {
        val mBuilder =
            NotificationCompat.Builder(
                applicationContext,
                "notify_001"
            )
        var intent = Intent(Intent.ACTION_VIEW, Uri.parse(
                        "market://details?id=" + applicationContext.packageName))
        intent.action = "Unique_id"
        intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        val pendingIntent = PendingIntent.getActivity(
            applicationContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        val bigText =
            NotificationCompat.BigTextStyle()

        for (item in remoteMessage.data.keys) {
            Log.i("TAG", "Key:" + item + " " + remoteMessage.data[item])
        }
        if (remoteMessage.data["big_text"] != null) {
            bigText.bigText(remoteMessage.data["big_text"])
        }
        if (remoteMessage.data["big_content_title"] != null) {
            bigText.setBigContentTitle(remoteMessage.data["big_content_title"])
        }
        if (remoteMessage.data["summary_text"] != null) {
            bigText.setBigContentTitle(remoteMessage.data["summary_text"])
        }
        mBuilder.setContentIntent(pendingIntent)
        mBuilder.setContentTitle(remoteMessage.notification?.title)
        mBuilder.setContentText(remoteMessage.notification?.body)
        mBuilder.priority = NotificationCompat.PRIORITY_MAX
        mBuilder.setAutoCancel(true)
        mBuilder.setContentIntent(pendingIntent)
        val bitmap =
            BitmapFactory.decodeResource(
                applicationContext.getResources(),
                R.drawable.chandmahame_logo
            )
        mBuilder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(bitmap)
        mBuilder.setStyle(bigText)
        val mNotificationManager: NotificationManager = applicationContext
            .getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channelId = "1234"
            val channel = NotificationChannel(
                channelId, "YOUR_CHANNEL_ID",
                NotificationManager.IMPORTANCE_HIGH
            )
            mNotificationManager.createNotificationChannel(channel)
            mBuilder.setChannelId(channelId)
        }

        mNotificationManager.notify(
            NOTIFICATION_ID,
            mBuilder.build()
        )
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

And for sure, using it as Java code is not a big deal.

英文:

I'm using this snippet and It's working well:

override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d(&quot;TAG&quot;, &quot;From: ${remoteMessage.from}&quot;)
// Check if message contains a data payload.
if (remoteMessage.data.isNotEmpty()) {
Log.i(&quot;TAG&quot;, &quot;Message data payload: ${remoteMessage.data}&quot;)
}
if (/* Check if data needs to be processed by long running job */ true) {
handleNow(remoteMessage)
}
// Check if message contains a notification payload.
remoteMessage.notification?.let {
Log.d(&quot;TAG&quot;, &quot;Message Notification Body: ${it.body}&quot;)
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private fun handleNow(remoteMessage: RemoteMessage) {
try {
val mBuilder =
NotificationCompat.Builder(
applicationContext,
&quot;notify_001&quot;
)
var intent = Intent(Intent.ACTION_VIEW, Uri.parse(
&quot;market://details?id=&quot; + applicationContext.packageName))
intent.action = &quot;Unique_id&quot;
intent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
val pendingIntent = PendingIntent.getActivity(
applicationContext, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
val bigText =
NotificationCompat.BigTextStyle()
for (item in remoteMessage.data.keys) {
Log.i(&quot;TAG&quot;, &quot;Key:&quot; + item + &quot; &quot; + remoteMessage.data[item])
}
if (remoteMessage.data[&quot;big_text&quot;] != null) {
bigText.bigText(remoteMessage.data[&quot;big_text&quot;])
}
if (remoteMessage.data[&quot;big_content_title&quot;] != null) {
bigText.setBigContentTitle(remoteMessage.data[&quot;big_content_title&quot;])
}
if (remoteMessage.data[&quot;summary_text&quot;] != null) {
bigText.setBigContentTitle(remoteMessage.data[&quot;summary_text&quot;])
}a
mBuilder.setContentIntent(pendingIntent)
mBuilder.setContentTitle(remoteMessage.notification?.title)
mBuilder.setContentText(remoteMessage.notification?.body)
mBuilder.priority = NotificationCompat.PRIORITY_MAX
mBuilder.setAutoCancel(true)
mBuilder.setContentIntent(pendingIntent)
val bitmap =
BitmapFactory.decodeResource(
applicationContext.getResources(),
R.drawable.chandmahame_logo
)
mBuilder.setSmallIcon(R.mipmap.ic_launcher).setLargeIcon(bitmap)
mBuilder.setStyle(bigText)
val mNotificationManager: NotificationManager = applicationContext
.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.O) {
val channelId = &quot;1234&quot;
val channel = NotificationChannel(
channelId, &quot;YOUR_CHANNEL_ID&quot;,
NotificationManager.IMPORTANCE_HIGH
)
mNotificationManager.createNotificationChannel(channel)
mBuilder.setChannelId(channelId)
}
mNotificationManager.notify(
NOTIFICATION_ID,
mBuilder.build()
)
} catch (e: Exception) {
e.printStackTrace()
}
}

and for sure, using it as Java code is not a big deal.

答案3

得分: 0

我在tutorialpoint.com上搜索,出现了这个带有按钮的内容,也许可以帮助。
英文:

I search in tutorialpoint.com and appear this with a button, maybe can help.

Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

huangapple
  • 本文由 发表于 2020年8月6日 06:20:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/63274316.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定