广播学习Demo

广播简单学习Demo

package com.amaker.broadcast;

import android.app.Activity;
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;
/**
 * 1,点击按钮发送一个广播
 * 2,注册广播时有两种注册:一,在配置文件中静态注册 二、在代码中动态注册
 * 注意:注册方法写在:onResume里面,注销方法写在:onPause里面
 *
 */
public class MainActivity extends Activity {
    private Button btn_send;
    public static final String MY_ACTION = "com.amaker.broadcast.MY_ACTION";
    MyReceiver r = new MyReceiver();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        btn_send = (Button) findViewById(R.id.button1);
        
        btn_send.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				send();
			}
		});
    }
    //发送一个广播
    void send(){
    	Intent intent = new Intent(MY_ACTION);
    	String msg = "我给你发了一个广播,是否收到?";
    	intent.putExtra("msg", msg);
    	sendBroadcast(intent);
    }
    //动态注册广播
    @Override
    protected void onResume() {
    	super.onResume();
    	IntentFilter filter = new IntentFilter();
    	filter.addAction(MY_ACTION);
    	registerReceiver(r, filter);
    }
    //注销广播
    @Override
    protected void onPause() {
    	super.onPause();
    	unregisterReceiver(r);
    }
}


package com.amaker.broadcast;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver{

	@Override
	public void onReceive(Context context, Intent intent) {
		String msg = intent.getStringExtra("msg");
		//收到广播,简单Toast显示一下
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

}


AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.amaker.broadcast"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".MainActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
	<!-- 先把这个静态的注册注释掉 -->
	<!--<receiver android:name="MyReceiver">
		<intent-filter>
			<action android:name="com.amaker.broadcast.MY_ACTION"/>
		</intent-filter>
	</receiver> -->


   </application>
</manifest>



你可能感兴趣的:(Broadcast)