android 广播BroadcastReceiver(activity与service通信)

来源:互联网 发布:流星网络电视2.87破解 编辑:程序博客网 时间:2024/04/28 03:01
activity里注册接收广播    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        initview();        // 开启后台服务,在服务里添加线程,再定时定位,        this.startService(new Intent(MainActivity.this,MyService.class));        System.out.println("启动service");        // 动态注册广播接收器        IntentFilter intentFilter = new IntentFilter();        intentFilter.addAction("com.main.MyService");        intentFilter.setPriority(Integer.MAX_VALUE);        registerReceiver(myReceiver, intentFilter);    }    private BroadcastReceiver myReceiver = new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            if(intent.getAction().equals("com.main.MyService")){             cityName = intent.getStringExtra("cityname");             myLocation = intent.getDoubleArrayExtra("jwd");            }            System.out.println(myLocation);            Toast.makeText(context,cityName+"的经纬度"+"lat:"+myLocation[0]+"lng:"+myLocation[1], Toast.LENGTH_SHORT)                    .show();        }    };//需要发送广播的地方//  sendBroadcast(new Intent(ACTION));//  Toast.makeText(MainActivity.this, "stsat receive", Toast.LENGTH_SHORT)//  .show();

service里发送广播
//发送广播
Intent intent=new Intent();
intent.putExtra(“jwd”, myLocation);
intent.putExtra(“cityname”, getCityName());
intent.setAction(“com.main.MyService”);
sendBroadcast(intent);

0 0