calling a method inside MainActivity from GCM onMessage()

被刻印的时光 ゝ 提交于 2019-12-22 12:39:10

问题


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.


回答1:


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); 


来源:https://stackoverflow.com/questions/14661749/calling-a-method-inside-mainactivity-from-gcm-onmessage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!