簡體   English   中英

將數據從廣播接收器發送到MainActivity

[英]Send data from Broadcast receiver to MainActivity

我需要在屏幕上顯示連接狀態。 看起來很簡單...

這是我下面的接收器代碼:

public class PowerConnectionReceiver extends BroadcastReceiver {

public PowerConnectionReceiver() {
}

@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}
}

我如何在屏幕textView上顯示我的狀態變量。 有人可以幫忙嗎? 謝謝!

您需要注冊一個Callback PowerConnectionReceiver創建一個Interface ,如下所示:

public Interface NetworkStatusCallback {
    public void onStateChange(String state);
}

現在在您的MainActivity實現此Callback ,如下所示:

public class MainActivity extends AppCompatActivity implements PowerConnectionReceiver.NetworkStatusCallback  {...}

PowerConnectionReceiver創建此Callbackreference ,並進行如下聲明:

private NetworkStatusCallback mCallback;
mCallBack = (NetworkStatusCallback)context;

現在在onReceive(Context context, Intent intent)執行以下操作:

@Override
public void onReceive(Context context, Intent intent) {
    String state;
    if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
        state = "Charging";
        mCallback.onStateChange(state);
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();

    } else {
        intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED);
        state = "Not charging";
        mCallback.onStateChange(state);
        Toast.makeText(context, state, Toast.LENGTH_SHORT).show();
    }
}

您將在MainActivity收到狀態

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM