有二种方式:
u 在“AndroidManifest.xml”文件注册,这种方法是全局的,主程序只要启动了这种服务,就算是关闭了注册了的广播服务也会在手机后台一直运行。(有点像一个间谍服务)
AndroidManifest.xml文件中写入
<application android:icon="@drawable/icon"android:label="@string/app_name">
…
<receiverandroid:name=".TestReceiver">
<intent-filter>
<actionandroid:name="android.intent.action.PICK" />
</intent-filter>
</receiver>
</application>
<uses-permissionandroid:name="android.permission.RECEIVE_SMS"></uses-permission>
写一个广播类
public classTestReceiver extends BroadcastReceiver{
public TestReceiver(){ System.out.println("TestReceiver"); }
@Override
public void onReceive(Context context,Intent intent) {
//这可以做收到信息后要做的事情
System.out.println("onReceive");
}
}
调用广播类
class BroadcastListener implementsOnClickListener{
@Override
public void onClick(View v) {
Intent intent = newIntent();
intent.setAction(Intent.ACTION_EDIT);
TestActivity.this.sendBroadcast(intent);
}
}
u 在程序中注册/卸载广播服务
AndroidManifest.xml文件中写入
<application android:icon="@drawable/icon"android:label="@string/app_name">
…
</application>
<uses-permissionandroid:name="android.permission.RECEIVE_SMS"></uses-permission>
写一个广播类
public classSMSReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context,Intent intent) {
//接受Intent对象当中的数据
Bundle bundle =intent.getExtras();
//在Bundle对象当中有一个属性名为pdus,这个属性的值是一个Object数组
Object[]myOBJpdus = (Object[]) bundle.get("pdus");
//创建一个SmsMessage类型的数组
SmsMessage[] messages = newSmsMessage[myOBJpdus.length];
for (int i = 0; i<myOBJpdus.length;i++)
{
//使用Object数组当中的对象创建SmsMessage对象
messages[i] =SmsMessage.createFromPdu((byte[]) myOBJpdus[i]);
//调用SmsMessage对象的getDisppalyMessageBody()方法,就可以得到消息的内容
System.out.println(messages[i].getDisplayMessageBody());
}
}
}
调用广播类
private static final String SMS_ACTION ="android.provider.Telephony.SMS_RECEIVED";
class RegisterReceiverListener implementsOnClickListener{
@Override
public void onClick(View v) {
smsReceiver = newSMSReceiver();//生成一个BroiadcastReceiver对象
IntentFilter filter = newIntentFilter();//生成一个IntentFilter对象
filter.addAction(SMS_ACTION);//为IntentFilter添加一个Action
//将BroadcastReceiver对象注册到系统当中
TestBC2Activity.this.registerReceiver(smsReceiver,filter);
}
}
class UnRegisterReceiverListener implementsOnClickListener{
@Override
public void onClick(View v) {
//解除BroadcastReceiver对象的注册
TestBC2Activity.this.unregisterReceiver(smsReceiver);
}
}