Service 广播 到Fragment

时间:2022-03-09 17:51:19
    //Fragment

     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

              System.out.println("oncreate");

         //代码 注册 广播接收器
          Receiver=new myReceiver();
          IntentFilter filter=new IntentFilter();
          filter.addAction("zcd.voicerobot");
          getActivity().registerReceiver(Receiver,filter); 

    }  //http://www.cnblogs.com/xiaobo-Linux/  赵存档 QQ463431476

    //内部类  广播接收

 public class myReceiver extends BroadcastReceiver {

    public void onReceive(Context context, Intent intent) {

        String msg = intent.getStringExtra("message");
         Toast.makeText(context, "广播已经接收", Toast.LENGTH_SHORT).show();
        text.setText("我说:"+msg);

    }
}

//service

    public  void UpdateGUI()
     {

         //broadcast
          // service 通过广播来更新GUI
            Intent intent=new Intent();
            intent.putExtra("message",text);
            intent.setAction("zcd.voicerobot");
            sendBroadcast(intent);
     }