public class TestReceiver extends BroadcastReceiver{ //这里面只有生成一次,一旦代码返回后生命就结束了。再此发送广播这个重新接收就会再次生成一个这个对象。
public TestReceiver(){
System.out.println("TestReceiver");
}
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive");
}
}
4、事件产生:
public class TestActivity extends Activity {
/** Called when the activity is first created. */
private Button sendButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testreceiver);
sendButton = (Button)findViewById(R.id.sendButton);
sendButton.setOnClickListener(new BroadcastListener());
}
class BroadcastListener implements OnClickListener{
//import android.view.View.OnClickListener; 这里记得要用这个,否则会有一些乱七八糟的问题。
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_EDIT);
//在xml只有 对应的EDIT 才能反应。recve里面才能进入构造函数,onReceive里面也才有进入。
TestActivity.this.sendBroadcast(intent);
}