Android 消息广播Intent传递数据
1.创建布局文件activity_broadcast.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" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".BroadcastActivity" > <Button android:id="@+id/sendBroadcastIntent" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Broadcast Intent" /> </RelativeLayout>
2.创建Activity
public class BroadcastActivity extends Activity { //设定为com.china.ui.NEW_LIFEFORM,显示内容前,多一条信息"收到广播信息"; //public static final String MY_NEW_LIFEFORM="com.china.ui.NEW_LIFEFORM"; public static final String MY_NEW_LIFEFORM="NEW_LIFEFORM"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_broadcast); //传递数据 final Intent intent=new Intent(MY_NEW_LIFEFORM); intent.putExtra("msgContent", "测试内容"); //初始化按钮 Button button=(Button) findViewById(R.id.sendBroadcastIntent); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { sendBroadcast(intent); } }); } }
3.创建BroadcastReceiver
public class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String content=intent.getStringExtra("msgContent"); CharSequence string="收到信息:"+content; Toast.makeText(context, string, Toast.LENGTH_LONG).show(); } }
4.配置AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.dh.broadcast" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.dh.broadcast.BroadcastActivity" 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="com.dh.broadcast.Receiver" android:enabled="true"> <intent-filter > <!-- <action android:name="com.china.ui.NEW_LIFEFORM"/> --> <action android:name="NEW_LIFEFORM"/> </intent-filter> </receiver> </application> </manifest>