1,
package com.example.myreceiver;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.content.IntentFilter;import android.view.Menu;import android.view.View;public class MainActivity extends Activity {private MyBroadcastReceiver receiver = new MyBroadcastReceiver();private IntentFilter filter = new IntentFilter("com.feng.intent");@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}public void start(View view){Intent intent = new Intent("com.feng.intent");intent.putExtra("name", "wang");sendBroadcast(intent);}@Overrideprotected void onPause() {super.onPause();unregisterReceiver(receiver);}@Overrideprotected void onResume() {super.onResume();registerReceiver(receiver, filter);}}
package com.example.myreceiver;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.util.Log;public class MyBroadcastReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context arg0, Intent arg1) {System.out.println("good!i've recevied u!");Log.e("MyBroadcastReceiver", "good!i've recevied u!");}}The advantage of this method is that it is flexible and controllable.
Another method is to register in mainfest. xml. This advantage is that once the application is installed, it will remain in the listening state.