大四实习准备5_android广播机制

时间:2023-03-09 08:19:38
大四实习准备5_android广播机制

2015-5-1

android 广播机制

5.1简介

分为标准广播(Normal broadcasts)(无先后顺序,几乎同时接收,不可截断)和有序广播(Ordered broadcasts)(有先后顺序,可以截断)两种。

5.2接收系统广播

广播接收器对感兴趣的广播进行注册,这样就能监听到对应的广播,并在内部处理相应的逻辑。

注册广播的方式有两种,分别为在代码中注册(动态注册)(缺点:必须在程序启动之后才能接收到广播,因为注册的逻辑是写在onCreat()方法中的)和在AndroidManifest.xml(静态注册)中注册。

创建广播接收器的方法为:新建一个继承自BroadcastReceiver的类,并重写父类的onReceive()方法就行了,监听到广播时对应的处理逻辑就在onReceive()方法中。

5.2.1通过动态注册的方法实现监听网络变化

IntentFilter:组件告诉Android系统自己乐意接收哪些隐式intent(显式的Intent会直接传送到目标组件)

http://blog.****.net/today520/article/details/7000048

 package com.example.broadcasttest;

 import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast; public class MainActivity extends Activity {
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
} @Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
} class NetworkChangeReceiver extends BroadcastReceiver{//非静态内部类 @Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if( networkInfo != null && networkInfo.isAvailable() ){
Toast.makeText(arg0, "network is availbale", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(arg0, "network is unavailbale", Toast.LENGTH_SHORT).show();
}
} }
}

MainActivity.class

需在在AndroidManifest.xml中声明

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

5.2.2通过静态注册监听开机启动广播

//开机启动广播只能用静态注册来监听(?)

 package com.example.broadtest2;

 import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast; public class BootCompleted extends BroadcastReceiver{ @Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Toast.makeText(arg0, "开机啦",Toast.LENGTH_SHORT).show();
}
}

BootCompleted.class 广播接收器

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadtest2"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".BootCompleted" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
</manifest>

AndroidManifest.xml 这里需对开机启动做权限声明&静态注册广播

这里MainActivity.class中不用写跟广播有关系的内容。

5.3发送自定义广播

5.3.1发送标准广播

 Intent intent = new Intent("lalala");//自定义的广播名
intent.putExtra("key", "get lalala BroadCast~");//可以附带些数据
sendBroadcast(intent);

例子:采用静态注册的方法,点击按钮发送一个自定义的广播,MainActivity中就是发送了下广播,没有直接涉及到diy_broadcastReceiver.class。

 package com.example.broadcasttest;

 import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity { Button bt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt = (Button) findViewById(R.id.button1);
bt.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent("lalala");
intent.putExtra("key", "get lalala BroadCast~");
sendBroadcast(intent);
}
});
}
}

MainActivity.class

 package com.example.broadcasttest;

 import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast; public class diy_broadcastReceiver extends BroadcastReceiver{ @Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
String s = arg1.getExtras().getString("key");//或者arg1.getStringExtra("key");
Toast.makeText(arg0, s, Toast.LENGTH_SHORT).show();
} }

diy_broadcastReceiver.class

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="${relativePackage}.${activityClass}" > <TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" /> <Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginTop="19dp"
android:text="Send BroadCast" /> </RelativeLayout>

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.broadcasttest"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="20" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:name=".diy_broadcastReceiver" >
<intent-filter>
<action android:name="lalala" />
</intent-filter>
</receiver>
</application> </manifest>

AndroidManifest.xml

别的应用,如果静态注册了同样的广播,也会进行相应的操作。

问题:

一个广播接收器注册了多个广播,怎样根据广播来源的不同,进行不同的操作?

5.3.2发送有序广播

//..........