Android -- 簡單廣播接收與發送(1)

來源:互聯網
上載者:User

標籤:android   blog   io   ar   os   sp   java   on   檔案   

1.

 

2. 實現代碼 

 layout.xml

 

 <Button        android:id="@+id/testBtn"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="@string/hello_world" />

 

  MainActivity.java

public static final String MY_ACTION = "iflab.test.MY_ACTION"; // 自訂ACTIONprivate Button testBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);testBtn = (Button) findViewById(R.id.testBtn);testBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubIntent intent = new Intent();intent.setAction(MY_ACTION);intent.putExtra("message", "來自於廣播的訊息!"); // 設定廣播的訊息sendBroadcast(intent);}});}

 testBroadcastReceiver.java

public class testBroadcastReceiver extends BroadcastReceiver {// context 內容物件 intent 接收的意圖對象@Overridepublic void onReceive(Context context, Intent intent) {// TODO Auto-generated method stubString str;str = "接收到的廣播訊息為:" + intent.getStringExtra("message"); // 接收訊息Toast.makeText(context, str, Toast.LENGTH_SHORT).show();}}

 設定檔中需要填寫的資訊

 <receiver android:name="testBroadcastReceiver" >            <intent-filter>                <action android:name="iflab.test.MY_ACTION" />            </intent-filter>        </receiver>

 

3. 說明

 <action android:name="iflab.test.MY_ACTION" />  為你在 MainActivity 中定義的常量
<receiver android:name="testBroadcastReceiver" >   name 的值為 你要接收廣播的時候所啟動的類  testBroadcastReceiver

 

Android -- 簡單廣播接收與發送(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.