将数据从brodcastreciever传递到UI

时间:2015-05-25 11:11:43

标签: android

我已经实施了brodcast接收器来列出来自谷歌消息服务的消息,我正在尝试将数据从Brodcastreciever传递到mainactivity我正在使用处理程序传递数据当我从服务器向手机发送消息时导致强制关闭我是也无法得到日志。

public class GcmBroadcastReceiver extends BroadcastReceiver {
   String mes;
   String action;
   Handler handler;
@Override
public void onReceive(final Context context, Intent intent) {
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(context));
    Log.d("regid", "notification recieved" );
    Bundle extras = intent.getExtras();
    action = intent.getAction();
    mes = extras.getString("message");
    Log.d("regid", "" + mes);
    Toast.makeText(context,mes,Toast.LENGTH_LONG).show();
    Bundle b = new Bundle();
    Message messobj = handler.obtainMessage();
    b.putString("message",mes);
    messobj.setData(b);
   handler.sendMessage(messobj);

}}

并在主要活动中

  handler = new Handler(){
        @Override
        public  void handleMessage( Message msg){
            String msg1 = msg.getData().getString("message");
            if(msg1 != null){
                text.setText(msg1);
            }
            else {
                text.setText("message not recieved");
            }
        }
    };

当我从服务器发送消息时,应用程序强制关闭 请帮忙解决问题

1 个答案:

答案 0 :(得分:2)

您在广播接收器处启动处理程序字段,因此您遇到NullPointerException。 有很多方法可以做到这一点:

  • EventBus - 如果您对此库不熟悉,那么您应该使用link

  • 创建一个接口(例如:onMessageShow)并让MainActivity实现它并将其传递给构造函数中的接收器,然后在您希望进行工作调用的位置接口监听器,它将完成工作。

  

注意: UI线程上正在调用 onReceive

祝你好运。