关闭

Android控件BroadcastReceiver详解

174人阅读 评论(0) 收藏 举报
分类:

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{

	@Override
	public 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;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//获取程序界面中的按钮
		send=(Button) findViewById(R.id.send);
		//事件绑定
		send.setOnClickListener(new OnClickListener(){

			@Override
			public 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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:6790次
    • 积分:289
    • 等级:
    • 排名:千里之外
    • 原创:23篇
    • 转载:0篇
    • 译文:0篇
    • 评论:1条
    最新评论