android应用开发详解(十七)-----------------------BroadcastReceiver

自己定义Broadcast Receiver来处理广播事件
(1)程序组件里构建intent,用sendBroadcast方法发送出去
(2)定义一个广播接收器,继承自BroadcastReceiver,并且覆盖onReceiver()方法响应事件
(3)注册该广播接收器,可以在代码中注册,也可以在Android Menifest.xml中注册。
系统广播事件的使用
【注意】接收系统发出的广播,我们不需要自己定义发出广播的intent,只需要定义接收器就可以了。

1、工程目录


2、MainActivity.java

package com.example.test_broadcast_receiver1;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	// 定义一个Action常量
	private static final String MY_ACTION = "com.example.test_broadcast_receiver1.action.MY_ACTION";
	// 定义一个Button
	private Button btn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		btn = (Button) findViewById(R.id.button01);
		btn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// 实例化intent
				Intent intent = new Intent();
				// 设置intent的action属性
				intent.setAction(MY_ACTION);
				// intent添加extra信息
				intent.putExtra("msg", "地瓜,地瓜,我是土豆");
				// 发送广播
				sendBroadcast(intent);
			}
		});
	}

	@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;
	}

}

MyReceiver.java

package com.example.test_broadcast_receiver1;

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) {
		// TODO Auto-generated method stub
		//从intent中获得信息
		String msg = intent.getStringExtra("msg");
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

}

3、布局文件main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发出广播" />

</LinearLayout>

4、
 <receiver android:name=".MyReceiver" >
            <intent-filter>
                <action android:name="com.example.test_broadcast_receiver1.action.MY_ACTION" />
            </intent-filter>
        </receiver>

猜你喜欢

转载自blog.csdn.net/hulan_baby/article/details/40153487
今日推荐