Android中 广播发送 和 接受 的简单示例

来源:互联网 发布:腾讯游戏2017数据分析 编辑:程序博客网 时间:2024/05/17 06:34

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.broadcast"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="18" />    <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <activity            android:name="com.example.broadcast.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.example.BROADCAST"/>            </intent-filter>        </receiver>    </application></manifest>


activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity" >    <Button         android:id="@+id/sendbroad"        android:layout_width="match_parent"        android:layout_height="90dp"        android:text="发送广播"/></RelativeLayout>


MainActivity

package com.example.broadcast;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 {    private Button sendbt;        @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        sendbt = (Button) findViewById(R.id.sendbroad);                sendbt.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent();                intent.setAction("com.example.BROADCAST");                intent.putExtra("msg", "这是广播发送的消息");                sendBroadcast(intent);            }        });            }}

MyReceiver

package com.example.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) {        Toast.makeText(context, "接收到的Intent的Action位:"+intent.getAction()+"\n消息内容是:"+intent.getStringExtra("msg"),Toast.LENGTH_LONG).show();    }}

效果如图




0 2
原创粉丝点击