安卓广播代码 Broadcast

package com.example.braodcast;

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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	String action="com.xh";
	private MyBroadcastReceiver mBroadcastReceiver;
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		final Activity activity=this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button button=(Button) findViewById(R.id.button);
		
		
		
		button.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent intent=new Intent();
				intent.setAction(action);
				 activity.sendBroadcast(intent);
			}
		});
		mBroadcastReceiver=new MyBroadcastReceiver();
		IntentFilter filter=new IntentFilter();
		
				filter.addAction(action);
				this.registerReceiver(mBroadcastReceiver, filter);
	}
	
	public void onDestroy(){
		super.onDestroy();
		this.unregisterReceiver(mBroadcastReceiver);
	}
		
	
	private class MyBroadcastReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.d("广播测试","测试成功");
		}
		
	}

	
	
		
	
}

你可能感兴趣的:(安卓广播代码 Broadcast)