我有一个有效的服务器/客户端解决方案,可以向我的设备发送推送通知。我的项目的下一步是在C2DMReceiver
类中调用onReceive事件时在活动窗口上显示一个对话框。
由于我是Android的新手,我不知道如何做到这一点,所以如果有人能向我解释,我会很高兴。
基本上我重用了chrometophone Application for c2dm中的类。调用onReceive事件,因为我为logcat创建了一个日志条目。由于C2DMReceiver
是一项服务,如果有新消息,如何通知我的活动?
我google了很多但找不到合适的解决方案......我试图使用registerReceiver()
,但我很确定我做错了。有人有例子吗?
好的,所以这是我到目前为止所得到的:
活动
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "Test");
}
};
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.w(Consts.LOG_TAG_SERVICE, "started");
}
// Called when the activity is restarted
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addCategory("com.mydomain.myapp.CONTEXT");
registerReceiver(mReceiver, filter);
}
// Called when the activity is closed
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
C2DMReceiver 公共类C2DMReceiver扩展了C2DMBaseReceiver {
public C2DMReceiver() {
super("my_test@gmail.com");
// TODO Load dynamic Gmail address
}
@Override
public void onRegistrered(Context context, String registrationId) {
Log.i(Consts.LOG_TAG_SERVICE, registrationId);
// Store the registration id in the preferences
SharedPreferences settings = Prefs.get(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString("deviceRegistrationID", registrationId);
editor.commit();
// TODO: Send ID to server
}
@Override
public void onUnregistered(Context context) {
Log.w(Consts.LOG_TAG_SERVICE, "got here!");
}
@Override
public void onError(Context context, String errorId) {
Log.w(Consts.LOG_TAG_SERVICE, errorId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "C2DMReceiver: " + intent.getStringExtra("payload"));
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.mydomain.myapp.NEWMESSAGE");
broadcastIntent.putExtra("reading", intent.getStringExtra("payload"));
broadcastIntent.addCategory("com.mydomain.myapp.CONTEXT");
context.sendBroadcast(broadcastIntent);
}
}
这就是我所得到的,但我从未接收过自己的广播..有没有人有一些投入?
答案 0 :(得分:3)
这应该这样做。
@Override
protected void onMessage(Context context, Intent intent) {
Log.w(Consts.LOG_TAG_SERVICE, "C2DMReceiver: " + intent.getStringExtra("payload"));
Intent i = new Intent(context, YourMainActivity.class);
i.putExtra("reading", intent.getStringExtra("payload"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
然后,您可以在主要活动中处理onStart中的意图。如果您的活动已在运行,它将由现有实例处理,否则将启动新实例。