一、静态注册#
1.在AndroidManifest.xml的<application>标签里加入
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
</receiver>
(我只注册了两个系统usb挂载和卸载的广播,后面会写自定义广播)
2.创建Recevier类
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("广播接受者:"+action);
}
}
3.拔插USB设备的打印
二、动态注册#
1.在要接收广播的类里创建一个IntentFilter,里面加入要接收的广播内容
private static IntentFilter Filter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.hardware.usb.action.USB_DEVICE_ATTACHED");
intentFilter.addAction("android.hardware.usb.action.USB_DEVICE_DETACHED");
return intentFilter;
}
2.new一个BroadcastReceiver 用于接收广播
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
System.out.println("广播接受者:"+action);
}
};
3.在Activity的生命周期里动态注册和动态取消广播接受者
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//注册
registerReceiver(receiver , Filter());
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//取消
unregisterReceiver(receiver);
}
三、自定义广播发送#
1.在AndroidManifest.xml的<application>标签里加入
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="cn.text"/>
</intent-filter>
</receiver>
2.手动发送广播。
package cn.text.broadcastsender;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button button;
private OnClickListener listener = new OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction("cn.text");
intent.putExtra("name", "text");
MainActivity.this.sendBroadcast(intent);
Toast.makeText(getApplicationContext(), "发送广播成功", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)this.findViewById(R.id.button);
button.setOnClickListener(listener);
}
}
3.接收广播
package cn.text.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Receiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getExtras().getString("name");
System.out.println("接收的内容"+name)
}
}
网友评论