首页 > 代码库 > android使用两种方式注册receiver

android使用两种方式注册receiver

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");
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	public 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);
	}

	@Override
	protected void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
	}

	@Override
	protected 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{

	@Override
	public void onReceive(Context arg0, Intent arg1) {
		System.out.println("good!i've recevied u!");
		Log.e("MyBroadcastReceiver", "good!i've recevied u!");
	}
	
}
这种方式的好处是,使用灵活,可控性高。

另外一种是在mainfest.xml中注册。这种好处是只要应用程序安装后,就会一直处于监听状态。

      <receiver android:name="com.example.myreceiver.MyBroadcastReceiver">
            <intent-filter >
                <action android:name="com.feng.intent"/>
            </intent-filter>
        </receiver>