Android廣播接收器和Activity間傳遞數據

思路

Activity向廣播接收器傳遞數據很簡單,只需要在發送廣播前將數據put進Intent中就行了。

廣播接收器怎麼向Activity傳送數據?這裏要用到接口,通過在廣播接收器裏定義一個接口,然後讓接收廣播接收器數據的Activity實現這個接口。先看下面的栗子,Activity發送一個廣播,然後廣播接收器返回一個字符串。

具體案例

Activity 佈局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context="com.nangch.broadcastreceivertest.MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="hello" />

    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="發送廣播"/>
</LinearLayout>

Activity代碼

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements MyReceiver.Message{

    TextView tv;
    MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //註冊廣播接收器
        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.nangch.broadcasereceiver.MYRECEIVER");
        registerReceiver(myReceiver, intentFilter);

        //因爲這裏需要注入Message,所以不能在AndroidManifest文件中靜態註冊廣播接收器
        myReceiver.setMessage(this);

        tv = (TextView) findViewById(R.id.tv);
        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.nangch.broadcasereceiver.MYRECEIVER");
                intent.putExtra("hello", tv.getText());         //向廣播接收器傳遞數據
                sendBroadcast(intent);      //發送廣播
            }
        });
    }

    @Override
    public void getMsg(String str) {
        //通過實現MyReceiver.Message接口可以在這裏對MyReceiver中的數據進行處理
        tv.append(str);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myReceiver);     //註銷廣播接收器
    }
}

廣播接收器代碼

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {
    private Message message;

    @Override
    public void onReceive(Context context, Intent intent) {
        //接收MainActivity傳過來的數據
        Toast.makeText(context, intent.getStringExtra("hello"), Toast.LENGTH_SHORT).show();

        //調用Message接口的方法
        message.getMsg(" world");
    }

    interface Message {
        public void getMsg(String str);
    }

    public void setMessage(Message message) {
        this.message = message;
    }
}

在 MyReceiver 中定義一個 Message 接口,並聲明一個 Message 類型的成員變量 message。然後讓 MainActivity實現這個接口,並調用 setMessage 方法將 MainActivity 注入,這樣 MainActivity 實例就成了 Myreceiver 的成員變量 message,這樣就能處理 MyReceiver 中的數據了。這種思想和我們學習 Android 時設置按鈕監聽器的思想差不多,仔細想一下還是很好理解的。

引用

本文轉載自 https://www.cnblogs.com/nangch/p/5353563.html ,感謝原作者的整理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章