我试图注册两个接收器,一个将通过GCM从我的应用服务器接收消息,另一个将从我的服务器加载消息。
所有这些都在名为 ChatActivity
的活动中private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
d("Broadcast received FROM MMESSAGERECEIVER");
Toast.makeText(context, "mMessageReceiver started", Toast.LENGTH_LONG).show();
if(cust != null && adapter != null){
SharedPreferences sharedPref = ChatActivity.this.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
long userID = sharedPref.getLong(AllSystems.PREFERENCES_KEY_LOGGED_IN_USER_ID, -1);
// Extract data included in the Intent
String message = intent.getStringExtra("message");
String dateCreated = intent.getStringExtra("dateCreated");
Date d = new Date(Long.parseLong(dateCreated));
long senderId = Long.parseLong(intent.getStringExtra("senderId"));
Toast.makeText(context, "mMessageReceiver in the first if", Toast.LENGTH_LONG).show();
if(senderId == userID || senderId == cust.getId()){
Toast.makeText(context, "mMessageReceiver in the second if", Toast.LENGTH_LONG).show();
adapter.add(new ChatMessageData(senderId == cust.getId(), message, new DateTime(d)));
Bundle results = getResultExtras(true);
results.putBoolean(INTERCEPTED, true);
playSound();
}
}
}
};
private BroadcastReceiver mLoadedReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
d("Broadcast received");
d("Conversation loaded broadcast received");
if(task != null && cust != null){
d("Contact and task not null");
long contactId = intent.getLongExtra("contactId", -1);
if(contactId == cust.getId()){
d("Executing conversation loading task");
task.execute();
}
}
}
};
private void playSound(){
try {
Uri notification = Uri.parse("android.resource://com.me.myapp/" + R.raw.notif);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter("com.google.android.c2dm.intent.RECEIVE"));
LocalBroadcastManager.getInstance(this).registerReceiver(mLoadedReceiver, loadedFilter);
}
//Must unregister onPause()
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLoadedReceiver);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chats);
LocalBroadcastManager.getInstance(this).registerReceiver(mLoadedReceiver, loadedFilter);
registerReceiver(mMessageReceiver,new IntentFilter("com.google.android.c2dm.intent.RECEIVE"));
}
问题
广播实例mMessageReceiver
(第1行)尚未注册,因为应该在其onReceive
方法中激活的对话框(Toast)未被激活。这个实例应该接收GCM消息,说明为什么我已经注册了这个`registerReceiver(mMessageReceiver,new IntentFilter(" com.google.android.c2dm.intent.RECEIVE"));
问题
哪里出错了?我试图遵循Try Cloud Messaging for Android 甚至example at gitlab,但都是徒劳的。我以前的问题与此问题的关系是here。