BroadcastReceiver register 广播的动态注册方式

1.动态注册方式特点:在代码中进行注册后,当应用程序关闭后,就不再进行监听。

下面是具体的例子:

BroadcastTest.java

package com.czz.test;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class BroadcastTest extends Activity {

	private static final String ACTION = "com.czz.test.SENDBROADCAST";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.broadcast_test);
		Button btnSendBroadcast = (Button) this.findViewById(R.id.send);
		final Button btnRegisteBroadcast = (Button) this.findViewById(R.id.registe);
		final Button btnUnregisteBroadcast = (Button) this.findViewById(R.id.unregiste);
		btnRegisteBroadcast.setEnabled(true);
		btnUnregisteBroadcast.setEnabled(false);
		btnSendBroadcast.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sendBroadcast(new Intent(ACTION));
			}
		});
		
		btnRegisteBroadcast.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				IntentFilter filter = new IntentFilter();
				filter.addAction(ACTION);
				registerReceiver(myReceiver, filter);
				btnRegisteBroadcast.setEnabled(false);
				btnUnregisteBroadcast.setEnabled(true);
			}
		});
		
		btnUnregisteBroadcast.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				unregisterReceiver(myReceiver);
				btnRegisteBroadcast.setEnabled(true);
				btnUnregisteBroadcast.setEnabled(false);
			}
		});
	}

	private BroadcastReceiver myReceiver = new BroadcastReceiver(){

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			Toast.makeText(context, "myReceiver receive", Toast.LENGTH_SHORT).show();
		}
		
	};
}

broadcast_test.xml



	
	
		
		

------------------------------------------------------------------------------------

2.静态注册方式是在AndroidManifest.xml的application里面定义receiver并设置要接收的action。静态注册方式的特点:不管改应用程序是否处于活动状态,都会进行监听,比如某个程序时监听内存 的使用情况的,当在手机上安装好后,不管改应用程序是处于什么状态,都会执行改监听方法中的内容。

下面是具体的例子:

MyReceiver.java


public class MyReceiver extends BroadcastReceiver{  
        //定义日志标签  
	private static final String TAG = "Test";  
	@Override 
	public void onReceive(Context context, Intent intent){  
	    //输出日志信息  
	    Log.i(TAG, "MyReceiver onReceive--->");  
	}  
}  

AndroidManifest.xml 
com.android.broadcast.RECEIVER_ACTION
activity中的ACTION

 
 

	 
	 
	     
		 
		     
		     
		 
	     
	     
		 
		     
		 
	     
	 
 

你可能感兴趣的:(Android)