一.最基础自定义广播接收
1、MainActivity 代码
public class MainActivity extends Activity implements
OnClickListener {
private Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1=(Button) this.findViewById(R.id.button1);
button1.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.setAction("aaa.action.MyBroadcast");
sendOrderedBroadcast(intent, null); //定义有序广播
}
}
2、receiver代码
public class MyBroadcastReceiver2 extends BroadcastReceiver {
static final String ACTION = "aaa.action.MyBroadcast";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION)) {
Toast.makeText(context, "登录失败...", Toast.LENGTH_LONG).show();
Log.i("MyBroadcast", "1111MyBroadcast");
}
}
}
public class MyBroadcastReceiver3 extends BroadcastReceiver {
static final String ACTION = "aaa.action.MyBroadcast";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION)) {
//Toast.makeText(context, "登录失败...", Toast.LENGTH_LONG).show();
Log.i("MyBroadcast", "22222MyBroadcast");
}
}
}
3、注册
<receiver android:name=".MyBroadcastReceiver2" >
<intent-filter android:priority="500" >
<action android:name="aaa.action.MyBroadcast" />
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcastReceiver3" >
<intent-filter android:priority="1000" >
<action android:name="aaa.action.MyBroadcast" />
</intent-filter>
</receiver>
二.定义开机启动广播
1、
public class MyBroadcastReceiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.getAction().equals(ACTION)){
Intent intent2=new Intent(context, MainActivity.class);
context.startActivity(intent2);
}
}
}
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver
android:name=".MyBroadcastReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>