我希望当手机收到来自AC2M的推送通知时,必须在通知栏中显示通知,如果用户按下通知,我的应用必须启动并显示描述该通知的特定活动,并且不是我的应用程序的正常拳头活动。
有可能实现这一目标吗?谁能解释我怎么样?
我的应用必须开始收听接收器吗?或者我的应用程序可以不启动?
感谢
答案 0 :(得分:1)
从C2DM,是的,这是可能的。
在C2DMReceiver.java类中使用以下代码:
@Override
protected void onMessage(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.icon; // icon from resources
CharSequence tickerText = "MyApp Notification"; // ticker-text
long when = System.currentTimeMillis(); // notification time
Context context21 = getApplicationContext(); // application Context
CharSequence contentTitle = "MyApp Notification Title"; // expanded message title
CharSequence contentText = (CharSequence) extras.get("message"); // expanded message text
Intent notificationIntent = new Intent(this, YourActivityName.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(context21, contentTitle, contentText, contentIntent);
mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
}
}
要让您的应用程序开始收听,请确保您已在项目的AndroidManifest.xml文件中声明了以下内容(以及其他必要的必需权限):
<service android:name=".C2DMReceiver" />
<!-- Only C2DM servers can send messages for the app. If permission is not set - any other app can generate it
<receiver android:name=".C2DMReceiver" android:permission="com.google.android.c2dm.permission.SEND"> -->
<receiver android:name="com.google.android.c2dm.C2DMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND">
<!-- Receive the actual message -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.your.packagename" />
</intent-filter>
<!-- Receive the registration id -->
<intent-filter>
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.your.packagename" />
</intent-filter>
</receiver>