自定义广播
注意声明自定义权力
开启权力
静态注册
package com.example.wkp.broadcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;/** * Created by wkp on 2016/9/21. */public class MyReceiver2 extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.v("hh","get broadcast"); }}
接收器
package com.example.wkp.broadcast;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;/** * Created by wkp on 2016/9/21. */public class SecondActivity extends Activity { private Button btn=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); btn= (Button) findViewById(R.id.send); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent=new Intent(); intent.setAction("com.example.wkp.broadcast.MY_ACTION"); sendBroadcast(intent,"com.example.wkp.broadcast.MY_PEMISSION"); Log.v("hehe","already send"); } }); }}
点击按钮发送广播
有序广播先定义先接收
abortBroadcast();忽略广播
可以通过android:priority制定优先级 不写为0
可以设置是否接收其他app的广播
可以设置是否被其他app接收广播 本地广播LocalBroadcastManager
private LocalBroadcastManager manager= LocalBroadcastManager.getInstance(this);
LocalReceiver receiver=new LocalReceiver();
IntentFilter filter=new IntentFilter();
filter.addAction("com.example.wkp.broadcast.MY_ACTION");
manager.registerReceiver(receiver,filter);