问题描述: 在Android应用中,使用GcmListenerService来接收来自Google Cloud Messaging的消息。但是发现onMessageReceived()方法未被调用,导致无法处理收到的消息。
解决方法:
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
// 在这里处理接收到的消息
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 注册GcmListenerService
Intent intent = new Intent(this, MyGcmListenerService.class);
startService(intent);
}
}
public class MyGcmListenerService extends GcmListenerService {
private static final String TAG = "MyGcmListenerService";
@Override
public void onMessageReceived(String from, Bundle data) {
String message = data.getString("message");
Log.d(TAG, "From: " + from);
Log.d(TAG, "Message: " + message);
// 获取设备的标识符(Registration ID)
String registrationId = InstanceID.getInstance(this).getToken();
Log.d(TAG, "Registration ID: " + registrationId);
// 在这里处理接收到的消息
}
}
以上是解决“Android GcmListenerService onMessageReceived() 方法未被调用”问题的一般步骤和代码示例。请根据自己的应用场景进行相应的修改和适配。