Android(安卓)BroadCast类讲解
注册广播类以拱调用 .
<!-- 定义 Broadcast Receiver 指定监听的 Action 这里我们的接收器,接收了 2 个 Action ,
一个系统的一个我们自定义的 -->
< receiver android:name = " .myBroadCast " >
< intent-filter >
< action android:name = "android.intent.action.BOOT_COMPLETED" />
</ intent-filter >
< intent-filter >
< action android:name = "com.broadcast.app.Hello" >
</ action >
</ intent-filter >
</ receiver >
注意:其中 android.intent.action.BOOT_COMPLETED 是系统自带的。没有实现类。而 com.broadcast.app.Hello 要有实现类。它的超类是 BroadcastReceiver ,它有一个 public void onReceive(Context
context, Intent intent) 方法。
红色高显 .myBroadCast 这个接受器对象
要实现这个类
// 如果接收的事件发生
@Override
public void onReceive(Context context, Intent intent) {
// 对比 Action 决定输出什么信息
if (intent.getAction().equals( "android.intent.action.BOOT_COMPLETED " )){
Log.e ( "HelloBroadReciever" , "BOOT_COMPLETED
!!!!!!!!!!!!!!!!!!!!!!!!!" );
// 设定程序自动运行
Intent
sayHelloIntent= new Intent(context,BroadCastActivity. class );
sayHelloIntent.addFlags(Intent. FLAG_ACTIVITY_NEW_TASK ); // 开始一个新类
context.startActivity(sayHelloIntent);
}
if (intent.getAction().equals( "com.broadcast.app.Hello " )){
Log.e ( "HelloBroadReciever" , "Say Hello
toWAHAHA !!!!!!!!!!!!!!!!!!!!!!!!!" );
Log.e ( "HelloBroadReciever" ,intent.getStringExtra( "yaoyao" ));
MediaPlayer.create (context, R.raw. tada ).start();
}
然后通过在 Activity 子类中进行调用
// 定义一个 intent, 并传递值 出去
Intent intent = new Intent().setAction(
"com.broadcast.app.Hello" ).putExtra( "yaoyao" ,
"wahaha is
189 days old ,27 weeks -- 2010-08-10" );
// 广播出去
sendBroadcast(intent);
要说明的是:
android.intent.action.BOOT_COMPLETED 注册的是开机自动运行。所有系统会动调用这个广播,而 com.broadcast.app.Hello 是自定义的,所以要程序员手动进行配置进行开启。
在程序中有一个 Intent 传值。
Intent intent=new Intent();
intent.putExtra(“yaoyao”,” yaoyao is 189
days old ,27 weeks -- 2010-08-10”);
可以将值传递出去。无论是 BroadReceiver ,还是 Activity 子类都可以收到。
如:
intent.getStringExtra( "yaoyao" )
Activtiy 之间的切换 :
Intent intent=new Intent();
intent.setClass(****Activity.this,***Activity.class);
StartActivity(intent);
****Activity.this.finish();
更多相关文章
- Android调用系统各个功能控件 方法
- Android用类继承Application的全局变量使用注意
- BaseColumns以及自定义Column
- Android(安卓)使用 URL 和 AsyncTask 加载网络数据
- Android(安卓)Intent应用,打开网页,安装程序,打电话,打开地图等功能
- Android(安卓)自定义AlertDialog 去黑边终极解决方案(亲测有效!)
- Android消息机制——时钟显示和异步处理工具类(AsyncTask)
- Android(安卓)Gradle
- httpget请求在android4.4系统出现java.net.ProtocolException: U