一、什么是广播
广播是Android四大组件之一,全称BroadcastReceiver。
二、静态注册无序广播示例
1.新建类继承BroadcastReceiver,实现onReceive方法
public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"收到",Toast.LENGTH_SHORT).show(); }
2.在AndroidManifest.xml文件中注册广播
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
3.在Activity(或服务)中发送广播
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //发送广播 Intent intent=new Intent("zhifubao"); sendBroadcast(intent); } });
三、动态注册无序广播示例
package com.example.ll.broadcast2application;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private Receive receive;
private Receive2 receive2;
@Override
//接收者
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receive=new Receive();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("hahahaha");
//动态注册广播接收器
registerReceiver(receive,intentFilter);
}
}
四、静态注册有序广播示例
<receiver android:name=".Receive">
<intent-filter android:priority="-1000">
<action android:name="hahahaha"></action>
</intent-filter>
</receiver>
五、动态注册有序广播示例
<receiver android:name=".Receive">
<intent-filter android:priority="-1000">
<action android:name="hahahaha"></action>
</intent-filter>
</receiver>