我有一个简单的任务 - 通过推送特定 Activity (而不是开始 Activity )来激活应用
想象我在应用程序中有 3 个 Activity :
- A(飞溅)
- B(项目列表)
- C(所选项目的详细信息)
一些先决条件:
- 通过推送,我得到了要选择的项目的 ID。
- 启动时我正在强制进行身份验证。
- 条件之一 - 我无法将身份验证转移到另一个 Activity 或应用程序服务。
现在我可以创建多个语句。当我点击推送激活应用程序时:
- 当推送到达时,PushIntentService 会生成一个通知,在 intent extras 中指定项目 ID 如果应用程序已终止,我应该从 Activity A 启动应用程序(以强制进行身份验证)
- 如果该应用程序是后台运行的(在后台运行),我应该在同一位置重新激活它(以跳过重新验证)
- 应用程序激活后,我将使用从 extras 中获取的项目 ID 导航到 Activity C。
现在我正在使用以下代码生成通知(第 1 项,Xamarin.Android 语法):
var resultIntent = new Intent(Application.Context, typeof(SplashScreen));
resultIntent.AddFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop);
if (extras.ContainsKey("ItemId"))
{
var itemId = extras["ItemId"];
resultIntent.PutExtra("ItemId", itemId);
}
var resultPendingIntent = PendingIntent.GetActivity(Application.Context, 0, resultIntent, 0);
builder.SetContentIntent(resultPendingIntent);
var notification = builder.Build();
此通知在所有情况下都工作得很好,但我在这里看到一个问题。 每次我点击通知时,我都会从头开始重新启动应用程序。 我想要的是当应用程序处于后台时我只需要激活它(就像 iOS 那样)并导航到所需的页面(更快的激活并避免重新验证)。
如何实现并修改上面的代码?
最佳答案
为此创建一个新的 Activity
。通知应启动该 Activity
(没有任何标志)。
在这个新的 Activity
的 onCreate()
中,执行如下操作:
super.onCreate(...);
if (!isTaskRoot() && alreadyAuthenticated) {
// Go directly to details page
Intent redirectIntent = new Intent(this, Details.class)
redirect.putExtra("id", itemId);
startActivity(redirectIntent);
else {
// This means the app was not running, so redirect to Splash
Intent redirectIntent = new Intent(this, Splash.class)
startActivity(redirectIntent);
}
finish();
isTaskRoot()
将返回 true
如果当用户点击 Notification
时应用没有运行。如果应用程序已经在运行,它应该返回 false
。
要测试您是否已经通过身份验证,您可以调用 static
方法或检查 static
变量,或者您可以使用其他方法来执行此操作。如果用户已经在“项目详细信息”或“项目列表” Activity 中,则取决于您希望 Activity
堆栈看起来像什么,您可能需要添加 SINGLE_TOP
和/或重定向到项目详细信息 Activity
时的 CLEAR_TOP
标志。
希望你明白这一点。
关于android - "smart"从推送通知激活 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25175518/