动态BroadcastReceiver检查在线连接

时间:2017-02-18 13:06:48

标签: android android-intent intentfilter

我想动态设置BroadcastReceiver以检查我的应用程序在前台运行时是否在线。在我的主类中,我创建了一个Intent Filter,一个嵌套的BroadcastReceiver类,最后分别在onResume和onPause方法中注册/取消注册接收器。

我的问题是,是否有一个意图行动,我可以添加到我的意图过滤器,检查在线连接?

如果没有,我该如何创建此动态广播接收器才能在我的应用程序运行时执行?

这是我班级的样子......

public class MainActivity extends AppCompatActivity {
private IntentFilter onlineIntentFilter;
private CheckOnlineReceiver checkOnlineReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    onlineIntentFilter = new IntentFilter();
    checkOnlineReceiver = new CheckOnlineReceiver();
    //*****WHAT INTENT ACTION CAN I PASS TO CHECK NETWORK CONNECTIVITY******
    onlineIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);

    }

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(checkOnlineReceiver, onlineIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(checkOnlineReceiver);
}


private class CheckOnlineReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Toast.makeText(getApplicationContext(),"IN METHOD, ACTION = " + action, Toast.LENGTH_LONG).show();
    }
}}

4 个答案:

答案 0 :(得分:1)

这是执行此操作的标准方法。

创建一个接口,该接口将有两个方法onNetworkConnected()和onNetworkDisconnected()

public interface NetworkConnectivityListener {
     public void onNetworkConnected();
     public void onNetworkDisconnected();
}

任何想要收听网络更改的类都将实现此接口并覆盖它的两种方法。

创建一个将扩展BroadcastReceiver的类,此接收者的onReceive()将捕获连接更改。在这个类中创建一个注册监听器的函数

public class NetworkBroadcastReceiver extends BroadcastReceiver {

private NetworkConnectivityListener listener;

public NetworkBroadcastReceiver(NetworkConnectivityListener listener) {
    this.listener = listener;
}

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();

    if (listener != null) {
        if (isConnectedToInternet()) {
            listener.onNetworkConnected();
        } else {
            listener.onNetworkDisconnected();
        }
    } 
}

PS您可以轻松检查您的设备是否已连接到互联网。只是谷歌。

现在假设您希望MainActivity监听netwrork更改,您只需在主活动调用中实现NetworkConnectivityListener并创建一个传递MainActivity上下文的NetworkBroadcastReceiver实例,它将开始获取网络更新。

答案 1 :(得分:1)

添加连接操作 onlineIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)

并且不要忘记添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

广播接收器的onReceive()将在连接更改时被调用,这意味着连接和断开连接。因此,无论何时收到braodcast,您都要检查连接情况,如下所示

public boolean isNetworkAvailable() {
  ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo networkInfo = cm.getActiveNetworkInfo();
  if (networkInfo != null && networkInfo.isConnected()) {
      return true;
  }
  return false;
}

答案 2 :(得分:0)

添加intentfilter CONNECTIVITY_ACTION

答案 3 :(得分:0)

您需要在后台执行长时间运行的任务时创建服务。

需要在<application>标记内的清单中注册服务。

<service android:name=".WifiService"
         android:stopWithTask="true"
         android:enabled="true"/>

stopWithTask导致在销毁所有活动时销毁服务(默认值为true)。

您需要在服务类中注册和取消注册BroadcastReceiver到CONNECTIVITY_CHANGE操作。

public class WifiService extends Service {

    private BroadcastReceiver mReceiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");

        // Your BroadcastReceiver class
        mReceiver = new WifiReceiver();
        registerReceiver(mReceiver, filter);
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        unregisterReceiver(mReceiver);
        return super.onUnbind(intent);
    }
}

然后在BroadcastReceiver中你必须侦听CONNECTIVITY_CHANGE。

public class WifiReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

        boolean isConnected = networkInfo != null &&
                              networkInfo.isConnectedOrConnecting();

        if (isConnected) {
            switch (networkInfo.getType()) {
                case ConnectivityManager.TYPE_WIFI:
                    // Connected via wifi
                    break;

                case ConnectivityManager.TYPE_ETHERNET:
                    // Connected via ethernet
                    break;

                case ConnectivityManager.TYPE_MOBILE:
                    // Connected via mobile data
                    break;
            }
        }
    }
}

通过此设置,您将能够在连接更改时通知应用程序的组件。