本文主要是介绍Android 广播接收器BroadcastReceiver,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
新建一个MyReceiver
public class MyReceiver extends BroadcastReceiver {public MyReceiver() {}@Overridepublic void onReceive(Context context, Intent intent) {System.out.print("接受消息"+intent.getStringExtra("data"));}
}
public class MainActivity extends Activity implements View.OnClickListener {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.sendMessage).setOnClickListener(this);}@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.sendMessage://intent传递数据Intent i = new Intent(new Intent(this,MyReceiver.class));i.putExtra("data","jikedfa");sendBroadcast(i);break;}}
}
- 动态注册和注销
MyReceiver
public class MyReceiver extends BroadcastReceiver {
//添加ACTIONpublic static final String ACTION = "sw.cins.com.service.intent.action.MyReceiver";public MyReceiver() {}@Overridepublic void onReceive(Context context, Intent intent) {System.out.print("接受消息"+intent.getStringExtra("data"));}
}
MainActivity
public class MainActivity extends Activity implements View.OnClickListener {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);findViewById(R.id.sendMessage).setOnClickListener(this);findViewById(R.id.btnreg).setOnClickListener(this);findViewById(R.id.btnunreg).setOnClickListener(this);}private MyReceiver receiver = null;@Overridepublic void onClick(View v) {switch (v.getId()){case R.id.sendMessage:Intent i = new Intent(MyReceiver.ACTION);i.putExtra("data","jikedfa");sendBroadcast(i);break;case R.id.btnreg:if(receiver == null){//注册receiver = new MyReceiver();registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION));}break;case R.id.btnunreg:if(receiver != null){//注销unregisterReceiver(receiver);receiver = null;}break;}}}
- 优先级控制
<receiver
android:name=".MyReceiver"android:enabled="true"android:exported="true">//通过priority控制优先级,数值越大,优先级越高<intent-filter android:priority="10"></intent-filter></receiver>
这篇关于Android 广播接收器BroadcastReceiver的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!