android - 如何在通知点击时转到特定活动?
问题描述
有几个通知,点击通知我想去特定的活动。假设出现一个奖励通知,然后单击将转到 RewardActivity 并添加了新朋友,然后单击 newFriend 通知将转到friendlistActivity,无论应用程序是在前台还是后台。
但在我的情况下,如果出现任何通知,它将转到相同的活动而不是不同的活动。
private void handleDataMessage(String noti_title,String noti_message,String noti_click_action) {
try {
Intent intent = new Intent(this, RewardActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("title", noti_title);
ByteArrayOutputStream _bs = new ByteArrayOutputStream();
//image.compress(Bitmap.CompressFormat.PNG, 50, _bs);
//intent.putExtra("img", image);
intent.putExtra("msg", noti_message);
intent.putExtra("click_action", noti_click_action);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new
NotificationCompat.Builder(this, "Default")
//.setLargeIcon(R.mipmap.ic_launcher)/*Notification icon image*/
.setSmallIcon(R.mipmap.ic_launcher)
//.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setPriority(Notification.PRIORITY_HIGH)
.setChannelId("Default")
.setVibrate(new long[]{1000, 1000})
.setContentIntent(pendingIntent);
notificationBuilder.setContentTitle(noti_title);
notificationBuilder.setContentText(noti_message);
notificationBuilder.setAutoCancel(true);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
}
解决方案
FCM 代表客户端应用程序自动向最终用户设备显示消息。当用户单击通知时,会创建两个条件
当您的应用程序处于后台时发送的通知。在这种情况下,通知将传送到设备的系统托盘。默认情况下,用户点击通知会打开应用启动器。
带有通知和数据有效负载的消息,包括 background 和foreground。在这种情况下,通知被传递到设备的系统托盘,数据负载在启动器 Activity 的意图的附加部分中传递。
如果您想在应用程序处于后台并且通知仅包含通知且没有数据播放负载时打开所需的活动,那么这是不可能的。
但是,如果您想在应用程序处于后台并且通知包含数据播放负载时打开所需的活动,那么您可以将用户导航到所需的活动。
请参阅下面的示例,了解当消息具有数据有效负载时打开所需的活动,包括后台和前台条件。
在我的 AndroidManifest 启动器 Activity 是 SplashActivity
<activity android:name=".activities.SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
您可以通过 Google FCM 测试器在 pushtry.com 上测试通知。这是通过 pushtry.com 发送时播放负载数据的格式
{
"to":"your_device_token",
"data": {
"title": "hello",
"message": "test message",
},
"priority":"high"
}
MyFirebaseMessagingService 类:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
private static int count = 0;
@Override
public void onNewToken(String s) {
super.onNewToken(s);
KeyManager.setSharedPreferenceString(getApplicationContext(), "fcm_token", s);
Log.e(TAG, "onNewToken: " + s);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//Here notification is recieved from server
try {
sendNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("message"));
} catch (Exception e) {
e.printStackTrace();
}
}
private void sendNotification(String title, String messageBody) {
Intent intent = new Intent(getApplicationContext(), SplashActivity.class);
//you can use your launcher Activity insted of SplashActivity, But if the Activity you used here is not launcher Activty than its not work when App is in background.
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//Add Any key-value to pass extras to intent
intent.putExtra("pushnotification", "yes");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationManager mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//For Android Version Orio and greater than orio.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_LOW;
NotificationChannel mChannel = new NotificationChannel("Sesame", "Sesame", importance);
mChannel.setDescription(messageBody);
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
mNotifyManager.createNotificationChannel(mChannel);
}
//For Android Version lower than orio.
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, "Seasame");
mBuilder.setContentTitle(title)
.setContentText(messageBody)
.setSmallIcon(R.mipmap.ic_launcher_sesame)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher_sesame))
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setColor(Color.parseColor("#FFD600"))
.setContentIntent(pendingIntent)
.setChannelId("Sesame")
.setPriority(NotificationCompat.PRIORITY_LOW);
mNotifyManager.notify(count, mBuilder.build());
count++;
}
}
现在,当您在后台收到推送通知并单击通知时,通知会发送到设备的系统托盘,而 Extras 会传递到您的启动器活动。检查启动器 Activity 是否带有附加功能或为空,然后将用户导航到所需的 Activity。
如果您只想向仅登录用户显示您的活动,则 SplashActivity 如下所示:
public class SplashActivity extends AppCompatActivity {
@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
try {
if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
if (getIntent().hasExtra("pushnotification")) {
Intent intent = new Intent(this, YourDesiredActivity.class);
startActivity(intent);
finish();
} else {
CheckLogin();
}
} else {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
} catch (Exception e) {
CheckLogin();
e.printStackTrace();
}
}
private void CheckLogin() {
if (KeyManager.getSharedPreferenceBoolean(SplashActivity.this, "isLoggedIn", false)) {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
} else {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 2500);
}
}
}
SplashActivty 中的逻辑,用于根据条件在不同的 Activity 中导航用户。
当用户在正常流程中打开应用程序而不单击 pushnotification 时,getIntent().hasExtra(“pushnotification”) 为空,因此命令转到 catch 块并检查 CheckLogin() 方法是否已登录。但是用户通过单击 pushnotification 进入,然后 getIntent().hasExtra(“pushnotification”) 不为空,他将转到所需的 Activity。
推荐阅读
- python - 为什么/有一个错误的答案,但//在python中有一个正确的答案?
- file - 如何在包含批处理文件的文件夹中循环
- c# - 从 Core 控制台应用程序连接到 Core MVC 应用程序数据上下文
- python - 根据pandas列中的数据,在1和0为真时附加一个空列表?
- sql - MS Access 查询太慢
- string - 如何在 Go 中有效地将字符串转换为字节切片,包括最后的 0?
- python - 如何在我的python代码中使用while循环
- php - PHP条件语句?
- react-native - 组件卸载后,TextInput 光标指针仍保留在屏幕上
- unit-testing - Bazel 的测试:CppCompileAction.java 是否有任何测试?