----Activity-----------
package com.broadcast;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.*;
import android.view.View.OnClickListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
public class BroadcastActivity extends Activity implements OnClickListener{
Button start;
Button stop;
IntentFilter _intentfilter;
myBroadcast _mybroadcast;
static final String Action="myaction";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Init();
}
public void Init(){
start=(Button)findViewById(R.id.btn_start);
stop=(Button)findViewById(R.id.btn_stop);
_mybroadcast=new myBroadcast();
_intentfilter=new IntentFilter(Action);
start.setOnClickListener(this);
stop.setOnClickListener(this);
registerReceiver(_mybroadcast,_intentfilter);//动态方法 ,进行绑定
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==start){
Intent intent=new Intent(Action);
intent.putExtra("message", "哈喽啊 activity");
sendBroadcast(intent);
}
if(v==stop){
//
Toast t=Toast.makeText(this, "结束", Toast.LENGTH_LONG);
t.show();
this.unregisterReceiver(_mybroadcast);
}
}
}
-----------------BroadCast-------------------
package com.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class myBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String message=intent.getStringExtra("message");
System.out.println("get resever");
Toast t=Toast.makeText(context, "这是接收到的消息: "+message, Toast.LENGTH_LONG);
t.show();
}
}