您的位置:首页 > 其它

intent广播

2016-02-02 20:37 232 查看
1.创建一个intent,调用sendBroadcast()函数,把intent携带的信息广播出去,如果要在intent传递额外数据,可以用intent的putExtra()方法

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

public class FirstActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstactivity_layout);// 设置页面布局
Button button = (Button) findViewById(R.id.button);// 通过ID值获得按钮对象
button.setOnClickListener(new View.OnClickListener() {// 为按钮增加单击事件监听器
public void onClick(View v) {
String str = "this.is.the.first.broadcast";//将此字符串作为识别广播的标识符
Intent intent = new Intent(str);// 创建Intent对象
intent.putExtra("message","this is my first message with broadcast");
sendBroadcast(intent);
}
});
}
}


2.广播消息发送后,利用broadcastReceiver监听广播消息,并且在AndroidManifest.xml文件中注册receiver标签。在broadcastReceiver接收到与之匹配的广播消息后,onReceive()方法会被调用;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class SecondActivity extends BroadcastReceiver {//接收广播要继承BroadcastReceiver

@Override
public void onReceive(Context context, Intent intent) {//重写onReceive方法
// TODO Auto-generated method stub
String msg = intent.getStringExtra("message");//获取key为message里面的字符串的值
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
}


3.在AndroidManifest.xml中进行广播过滤

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

<uses-sdk android:minSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity android:name=".FirstActivity" > <!--发送广播方的类名-->
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name=".SecondActivity"><!--接收广播方的类名 -->
<intent-filter>
<action android:name="this.is.the.first.broadcast"/><!--只接受带该字符串的intent广播-->
<!--这与发送方(最上面的第一段代码)在初始化intent时作为参数的字符串是一致的-->
</intent-filter>
</receiver>

</application>
</manifest>


通过在AndroidManifest.xml中,第21行代码,将第一段代码的发送方和第二段接收方的代码进行连接起来了,它就像一座桥梁。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: