Android控件BroadcastReceiver详解

来源:互联网 发布:皮书包知乎 编辑:程序博客网 时间:2024/06/15 01:47

1.BroadcastReceiver控件详解


2.代码实现


a.接收广播代码实现

package com.example.broadcast;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast;public class MyBroadCastReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {Toast.makeText(context,"接收到的Intent的Action为: "+intent.getAction()+"\n消息内容是: "+intent.getStringExtra("msg"),Toast.LENGTH_LONG).show();System.out.println("onCreate  CurrentThread = " + Thread.currentThread().getName());}}

b.发送广播的控件Activity的代码实现

package com.example.broadcastreceivertest;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity {Button send;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//获取程序界面中的按钮send=(Button) findViewById(R.id.send);//事件绑定send.setOnClickListener(new OnClickListener(){@Overridepublic void onClick(View v) {//启动BroadcastReceiver事件的intent,intent信息的解析Intent intent=new Intent();intent.setAction("com.example.broadcastreceivertest.START_BroadcastReceiver");intent.putExtra("msg","你大爷的!!!!!");//发送广播sendBroadcast(intent);}});}}

c.AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastreceivertest"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />


    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <receiver android:name="com.example.broadcast.MyBroadCastReceiver"
            android:exported="false">
            <intent-filter>
                <action android:name="com.example.broadcastreceivertest.START_BroadcastReceiver"/>
            </intent-filter>
        </receiver>
        <activity
            android:name="com.example.broadcastreceivertest.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>


    </application>


</manifest>



0 0