【发布时间】:2015-03-23 23:18:13
【问题描述】:
我正在尝试“恢复”单个任务活动,以便在用户单击我的通知时显示在前台。 (与用户从应用程序菜单中点击应用程序图标的行为相同。)
我的通知创建了一个 PendingIntent,它广播了我的广播接收器接收到的操作。如果应用程序不在前台,我会尝试恢复应用程序。此外,我试图通过意图将消息传递给我的 onResume 函数。但是,我遇到了一个错误:
Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
尽管出现此错误,但我的应用程序正在恢复...不明白为什么。但是,我的额外内容没有传递给我的 onResume 函数。
首先我创建一个通知。
public static class MyNotificationCreator {
private static final int MY_NOTIFICATION_ID = 987;
public static void createNotification(Context context) {
Intent openAppIntent = new Intent(context, MyReceiver.class);
openAppIntent.setAction("PleaseOpenApp");
PendingIntent pi = PendingIntent.getBroadcast(context, /*requestCode*/0, openAppIntent, /*flags*/0);
Notification notification = ne Notification.Builder(context)
.setContentTitle("")
.setContentText("Open app")
.setSmallIcon(context.getApplicationInfo().icon)
.setContentIntent(pi)
.build();
NotificationManager notificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID, notification); }
}
为 MyReceiver 广播“PleaseOpenApp”。
public class MyReceiver extends BroadcastReceiver {
@Override
public void onRecieve(Context context, Intent intent) {
if (intent.action() == "PleaseOpenApp" && !MyPlugin.isForeground) {
PackageManager pm = context.getPackageManager();
//Perhaps I'm not supposed to use a "launch" intent?
Intent launchIntent = pm.getLaunchIntentForPackage(context.getPackageName());
//I'm adding the FLAG_ACTIVITY_NEW_TASK, but I'm still hitting an error saying my intent does not have the FLAG_ACTIVITY_NEW_TASK...
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchIntent.putExtra("foo", "bar");
context.startActivity(launchActivity);
} else {
//do other stuff
}
}
}
我的插件会跟踪我们是否在前台。此外,它会在我的接收器尝试启动应用程序后尝试获取“食物”。
public class MyPlugin extends CordovaPlugin {
public static boolean isForeground = false;
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webview) {
super.initialize(cordova, webview);
isForeground = true;
}
@Override
public void onResume(boolean multitasking) {
isForeground = true;
String foo = activity.getIntent().getStringExtra("foo");
Log.d("MyPlugin", foo); //foo is null after clicking the notification!
}
@Override
public void onPause(boolean multitasking) {
isForeground = false;
}
@Override
public void onDestroy() {
isForeground = false;
}
}
注意:因为我使用的是 cordova,所以我的活动有一个 singleTask 启动模式。
此外,我是 Android 开发的新手,因此对于恢复不在前台的活动与恢复已被破坏的活动以及有关我不理解的一般概念/最佳实践的信息的任何帮助,我们将不胜感激!
【问题讨论】:
标签: android cordova android-intent notifications