自定义广播

广播注册有两种:代码注册和清单文件中注册。这里用代码注册的方式:

还有需注意的是要设置IntentFilter的action然后在onReceive()方法中通过intent的action判断是否是我们定制的广播

//注册广播的方法
    public void registerBoradcastReceiver() {
    
        IntentFilter filter = new IntentFilter();
        filter.addAction("custom.broadcast");      
        //注册广播
        registerReceiver(myBroadcastReceiver, filter);
    }


---------------------------------------------整个工程代码-------------------------------------------------------

public class MyBroadcastReceiver1Activity extends Activity implements OnClickListener{

private Button button;
public String msg;
public MyBroadcastReceiver myBroadcastReceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

button = (Button) this.findViewById(R.id.button);
myBroadcastReceiver = new MyBroadcastReceiver();

button.setOnClickListener(this);

//注册广播
registerBoradcastReceiver(); 

}

@Override
public void onClick(View v) {
MyRunnable myRunnable = new MyRunnable();
new Thread(myRunnable).start();
}

public class MyRunnable implements Runnable {

@Override
public void run() {
System.out.println("Thread's id: " + Thread.currentThread().getName());

Intent intent = new Intent();
intent.setAction("custom.broadcast");
intent.putExtra("number", "12345678");
sendBroadcast(intent);
}

}

//接收广播的类
public class MyBroadcastReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Log.e("zhubo", "--- in onReceive() --- ");
if(intent.getAction().equals("custom.broadcast")) {
msg = intent.getStringExtra("number");
}

}

}

//注册广播的方法
public void registerBoradcastReceiver() {

IntentFilter filter = new IntentFilter();
filter.addAction("custom.broadcast");
//注册广播
registerReceiver(myBroadcastReceiver, filter);
}


}

 

 
 
posted @ 2012-07-21 18:08  xxzjjcbx  阅读(235)  评论(0编辑  收藏  举报