0

私はAndroidに比較的慣れていませんが、

ネットワーク接続の変化の検出に関する関連記事を読み、このBroadcastReceiverサブクラスを実装し、AndroidManifest.xml に必要な追加を行い、必要な状態変更ブロードキャストを期待どおりに受け取りました。

public class NetworkStateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

    }
}

Activity質問: これらの通知をサブクラスで受信または転送するにはどうすればよいですか? どうやらNetworkStateReceiver私のActivityサブクラスで のインスタンスを作成し、onReceiveそこをオーバーライドしてもうまくいきません。

ご指摘ありがとうございます...

編集:

私は上IntentからonReceive次のように放送しました:

Intent target = new Intent(CONNECTIVITY_EVENT);
target.putExtra(CONNECTIVITY_STATE, networkInfo.isConnected());
context.sendBroadcast(target);

Activityそして、私のようにそれを受け取る:

@Override
protected String[] notifyStrings() {
     return ArrayUtils.addAll(super.notifyStrings(), new String[] {NetworkStateReceiver.CONNECTIVITY_EVENT});
}

@Override
protected void notifyEvent(Intent intent, String action) {
    super.notifyEvent(intent, action);
    if (action != null) {
        if (action.equalsIgnoreCase(NetworkStateReceiver.CONNECTIVITY_EVENT)) {
            boolean isConnected = intent.getBooleanExtra(NetworkStateReceiver.CONNECTIVITY_STATE, true);
            // Do something...
        }
    }
}
4

1 に答える 1

1

どちらかを使用することをお勧めします 1) インターフェイス アプローチ。したがって、メソッドを持つインターフェイスを宣言し、networkChanged()これを所有するクラスBroadcastReceiverに、ローカルでネットワークの変更を通知したいクラスのリストを保持させますList<InterfaceName>

2) インターフェイスの作成をスキップし、サブスクリプション ユーティリティを使用します。私の 2 つのお気に入りは https://github.com/greenrobot/EventBusです。

https://gist.github.com/bclymer/6708819 (小さく、あまり使われていない、また免責事項: 私はこれを書きました)

これらを使用して、プロパティを持つイベント クラスを作成し、それらのクラスのインスタンスをサブスクライブしてポストします。

あなたの活動で

@Override
public void onCreate() {
    ...
    EventBus.getInstance().subscribe(this, MyType.class);
}

@Override
public void onDestroy() {
    ...
    EventBus.getInstance().unsubscribe(this, MyType.class);
}

@Override
public void newEvent(Object event) {
    if (event instanceOf MyType) {
        // do stuff
    }
}

そして、あなたのBroadcastReceiver

@Override 
public void onReceive(Context context, Intent intent) {
    EventBus.post(new MyType(true));
}

例 MyType

public class MyType {
    public boolean networkEnabled;
    public MyType(boolean networkEnabled) {
        this.networkEnabled = networkEnabled;
    }
}

この例では、2 番目のサブスクリプション ユーティリティ (私のもの) を使用します。

于 2013-10-11T16:15:28.337 に答える