我想将我的活动与Google云消息传递同步。 当GCM消息接收其自己的接收者时,获取消息并创建通知,然后将我的自定义消息广播给活动接收者。
另一方面,我的Activity拥有自己动态注册的BroadcastReceiver,它接收我的信息消息。
现在情况如此:
我试过可能的方式:
所以,如果你遇到问题,最好的解决方法是什么?
这是我的活动接收者:
private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("LOG", "unreciver");
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
// Waking up mobile if it is sleeping
WakeLocker.acquire(getApplicationContext());
/**
* Take appropriate action on this message
* depending upon your app requirement
* For now i am just displaying it on the screen
* */
//Showing received message
//lblMessage.append(newMessage + "\n");
Log.i("LOG", "unreciver messsage:"+newMessage);
//Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show();
loadReciverDialog(newMessage);
// Releasing wake lock
WakeLocker.release();
}
};
这是从GCM接收消息并创建通知的服务部分:
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("price");
Log.i("LOG", "GCM service Message "+message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
private static void generateNotification(Context context, String message) {
Log.i("LOG", "genetaret notify");
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, MainActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
// Play default notification sound
notification.defaults |= Notification.DEFAULT_SOUND;
//notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "your_sound_file_name.mp3");
// Vibrate if vibrate is enabled
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(0, notification);
}
}
并且此部分显示消息:
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Log.i("LOG", "commonutils msg="+message);
context.sendBroadcast(intent);
}
答案 0 :(得分:0)
我终于以这种方式解决了这个问题:
所以我的应用程序以两种方式获取消息:
但我想知道是否有更好的方法可以使用一个接收器。