欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android广播 demo

程序员文章站 2022-05-16 13:34:03
...
package com.royal.broadcast;

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;

/**
 * 广播示例
 * 
 * @author Royal
 * 
 */
public class BroadcastDemoActivity extends Activity {

	private Button btn_broadcast = null;
	private final String ACTION_NAME = "发送广播";

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// 注册广播
		registerBoradcastReceiver();

		btn_broadcast = (Button) findViewById(R.id.btn_broadcast);
		btn_broadcast.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				Intent mIntent = new Intent(ACTION_NAME);
				mIntent.putExtra("royal", "发送广播,相当于在这里传送数据");

				// 发送广播
				sendBroadcast(mIntent);
			}
		});
	}
	
	/**
	 * 注册广播      
	 */
	public void registerBoradcastReceiver(){ 
        IntentFilter myIntentFilter = new IntentFilter(); 
        myIntentFilter.addAction(ACTION_NAME); 
        //注册广播       
        registerReceiver(mBroadcastReceiver, myIntentFilter); 
        System.out.println("广播注册");
    } 
	
	/**
	 * 广播接收处理
	 */
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){ 
        @Override 
        public void onReceive(Context context, Intent intent) { 
            String action = intent.getAction(); 
            String str = intent.getStringExtra("royal");
            if(action.equals(ACTION_NAME)){ 
            	System.out.println("广播处理参数:" + str);
                Toast.makeText(BroadcastDemoActivity.this, "处理action名字相对应的广播", 200).show(); 
            } 
        } 
    };

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		//取消广播注册
		this.unregisterReceiver(mBroadcastReceiver);
		System.out.println("取消广播注册");
		super.onDestroy();
	} 
    
}
相关标签: android 广播