好的,这是我的问题。我有一个接收推送通知的服务
。现在,根据推送通知的内容,如果单击它,它应该启动相应的应用程序。
我在接收推送通知或使用该服务时没有任何问题,我唯一无法工作的是它打开正确的应用程序的部分。
我需要做什么才能从服务
打开应用程序?这必须是动态的,因为将有多个应用程序使用此服务。
如果有人能指出我正确的方向,那就太好了。
PS。我正在使用 GCM 服务,我将其放入库中,因此我可以在我的多个应用程序中使用它。这是GCMItentService.onMessage()
函数,我需要在其中检查 url 的内容,然后为通知设置正确的 Intent :
@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);
}
最佳答案
可以使用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);
关于java - 从服务启动应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12971611/