问题描述
当 GCMIntentService.java 中的 onMessage()接收到新消息时, onMessage()调用一个名为 MainActivity.java 中的> blinkLED(),以便 blinkLED()方法可以使用 onMessage()接收的数据。我怎么能实现呢?一个示例代码将会很有帮助。
使用BroadcastReceiver。这个向您展示了如何从一个类发送广播意图,并由另一个类来处理它。 / p>
简短的例子,在你的GCMIntentService :: onMessage()中,你可能会有这样的:
Intent intent = new Intent();
intent.setAction(com.my.app.blinkled);
sendBroadcast(intent);
然后在MainActivity中,实现一个BroadcastReceiver:
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override $ b $ public void onReceive(Context context,Intent intent){
blinkLED();
并在MainActivity的onResume()中注册它:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(com.my.app.blinkled);
receiver = new MyBroadcastReceiver();
registerReceiver(receiver,intentFilter);
i want when a new message received by onMessage() inside GCMIntentService.java , the onMessage() call a method called blinkLED() inside the MainActivity.java so the blinkLED() method can use the data received by onMessage() , how can i implement that ? a sample code will be helpful.
解决方案 Use BroadcastReceiver. This tutorial shows you how to send a broadcast intent from a class, and have another class handles it.
Short example, in your GCMIntentService::onMessage(), you may have this:
Intent intent = new Intent();
intent.setAction("com.my.app.blinkled");
sendBroadcast(intent);
Then in your MainActivity, you implements a BroadcastReceiver :
private class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
blinkLED();
}
}
and register for it in onResume() of MainActivity:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.my.app.blinkled");
receiver = new MyBroadcastReceiver();
registerReceiver(receiver, intentFilter);
这篇关于从GCM onMessage()调用MainActivity中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!