好的,这是我的问题。我有Service
接收推送通知。现在,根据推送通知的内容,它应该启动相应的应用程序,如果点击它。
接收推送通知或使用服务没有问题,我唯一无法工作的是打开正确应用程序的部分。
从Service
打开应用程序需要做什么?这必须是动态的,因为将有多个应用程序使用此服务。
如果有人能指出我正确的方向,那将是很棒的。
PS。我正在使用GCM服务,我将其放入库中,因此我可以在我的多个应用程序中使用它。这是GCMIntentService.onMessage()
函数,我需要在其中检查网址的内容,然后为通知设置正确的意图:
@Override
protected void onMessage(Context arg0, Intent arg1)
{
Log.i(TAG, "new message = " + arg1.getExtras());
//Get a reference to the NotificationManager
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
//Instantiate the Notification
int icon = getResourseIdByName(arg0.getApplicationContext().getPackageName(), "drawable", "notification_icon");
CharSequence tickerText = arg1.getExtras().getString("tickertext");
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
//Define the notification's message and PendingIntent
Context context = getApplicationContext();
CharSequence contentTitle = arg1.getExtras().getString("contentTitle");
CharSequence contentText = arg1.getExtras().getString("contentText");
Intent notificationIntent = null;
if(arg1.getExtras().getString("url").isEmpty())
{
notificationIntent = new Intent(this, arg1.getExtras().getString("packageName").getClass());
}
else
{
notificationIntent = new Intent(this, MyWebView.class);
}
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
//Pass the Notification to the NotificationManager
int notificationId = Integer.parseInt(arg1.getExtras().getString("notificationId"));
mNotificationManager.notify(notificationId, notification);
}
答案 0 :(得分:2)
可以使用Intent
启动应用程序。您需要构造正确的PendingIntent
对象,如下所示:
Intent targetIntent = new Intent(Intent.ACTION_MAIN, null);
targetIntent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName("target_app_package_name", "target_activity_class_name");
targetIntent.setComponent(cn);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
如果您不了解目标包或目标Activity
,则可以使用以下代码:
Intent startingIntent = context.getPackageManager().getLaunchIntentForPackage("target_app_package_name");
context.startActivity(startingIntent);
答案 1 :(得分:1)
然后您可以按包名启动应用程序,类似这样的
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.your.packageName.in.String");
startActivity(LaunchIntent);
编辑:
为此,AFAIK,您只能从创建该通知的自己的包中启动活动。您可以从另一个应用程序包启动一个活动,但是您必须知道该包的活动类名称,这通常是您不可能知道的。
Intent clickIntent = new Intent(context,Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,clickIntent,0);
这是创建通知时所需要的。
notification.setlatestEventInfo(context, "title","content",pendingIntent);
urgh!抱歉蹩脚的评论......我似乎无法在评论中加入代码:(