1. 程式人生 > >android訊息廣播Intent傳遞資料

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>