android broadcastreceiver 範例

看了下面這幾篇,就完全通了,完全可以在activity & service 之間互傳資料。


完整程式碼

你可以到 GitHub 上面觀看或下載完整程式碼

程式碼說明

首先定義一個 Button
它是用來送出一個廣播訊息
當接收廣播的程式收到以後,就會跳出一個視窗顯示我收到了

public class MainActivity extends AppCompatActivity {
    private final static String MY_MESSAGE = "com.givemepass.sendmessage";
    private Button send_broadcast;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        send_broadcast = (Button)findViewById(R.id.send_broadcast);
        send_broadcast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                registerReceiver(mBroadcast, new IntentFilter(MY_MESSAGE));
                Intent intent = new Intent();
                intent.setAction(MY_MESSAGE);
                sendBroadcast(intent);
            }
        });
    }
    private BroadcastReceiver mBroadcast =  new BroadcastReceiver() {
        private final static String MY_MESSAGE = "com.givemepass.sendmessage";
        @Override
        public void onReceive(Context mContext, Intent mIntent) {

            if(MY_MESSAGE.equals(mIntent.getAction())){
                new AlertDialog.Builder(MainActivity.this)
                    .setMessage("收到訊息!")
                    .setPositiveButton("確定", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            unregisterReceiver(mBroadcast);
                        }
                    })
                    .show();
            }
        }
    };
}

簡單的幾行程式碼, 當我們按下 Button 的時候
就對系統註冊我們下面所寫的廣播類別

registerReceiver(mBroadcast, new IntentFilter(MY_MESSAGE));

這個廣播類別是專門接收傳送出來的各類訊息
而我們篩選出MY_MESSAGE裡面的字串

if(MY_MESSAGE.equals(mIntent.getAction())){
    //...
}

當我們截取到這樣的字串, 就會跳出一個視窗顯示我們收到了!
接著就將廣播的物件解除註冊。

new AlertDialog.Builder(BroadcastReceiverDemoActivity.this)
    .setMessage("收到訊息!")
    .setPositiveButton("確定", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which) {
         // TODO Auto-generated method stub
         unregisterReceiver(mBroadcast);
     }
    })
    .show();

xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

    <Button android:text="send broadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/send_broadcast"/>
</RelativeLayout>

相關文章

寫留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *