检测用户何时启用数据连接

时间:2015-04-16 17:56:14

标签: android

我想知道如何检测用户何时启用数据连接,但仅在我的应用程序将用户发送到网络数据设置屏幕时。然后执行剩下的操作...... 不是在那之前。

我之前看过一些与相同主题相关的例子,但找不到明确且有效的答案。

请高度赞赏任何形式的帮助......

2 个答案:

答案 0 :(得分:0)

我认为你应该在SharedPreferences中使用Flag,所以当用户进入数据设置时,你保存flag=true,然后检查连续性的变化,如this thread < / p>

答案 1 :(得分:0)

在你提到的帖子中你应该听一个标志,然后注册你的接收器听取数据连接,然后在onDestroy中取消注册,可以这样做:

NetworkStateReceiver:

public class NetworkStateReceiver extends BroadcastReceiver {

protected List<NetworkStateReceiverListener> listeners;
protected Boolean connected;

public NetworkStateReceiver() {
    listeners = new ArrayList<NetworkStateReceiverListener>();
    connected = null;
}

public void onReceive(Context context, Intent intent) {
    if(intent == null || intent.getExtras() == null)
        return;

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo ni = manager.getActiveNetworkInfo();

    if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
        connected = true;
    } else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        connected = false;
    }

    notifyStateToAll();
}

private void notifyStateToAll() {
    for(NetworkStateReceiverListener listener : listeners)
        notifyState(listener);
}

private void notifyState(NetworkStateReceiverListener listener) {
    if(connected == null || listener == null)
        return;

    if(connected == true)
        listener.networkAvailable();
    else
        listener.networkUnavailable();
}

public void addListener(NetworkStateReceiverListener l) {
    listeners.add(l);
    notifyState(l);
}

public void removeListener(NetworkStateReceiverListener l) {
    listeners.remove(l);
}

public interface NetworkStateReceiverListener {
    public void networkAvailable();
    public void networkUnavailable();
}

}

首先发送到networksettings屏幕时:

Intent i = new Intent(this,NetworkSettingsActivity.class);
i.putExtra("ACTIVATE_RECEIVER", true);
startActivity(i);

然后在NetworkSettingsActivity中接收时:

public class NetworkSettingsActivity extends Activity{
    NetworkStateReceiver receiver;

    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
    protected void onCreate(Bundle savedInstanceState){
        if (getIntent().getBooleanExtra("ACTIVATE_RECEIVER", false)){
         receiver = new NetworkStateReceiver();
         receiver.addListener(new NetworkStateReceiver.NetworkStateReceiverListener() {
             @Override
             public void networkAvailable() {
                 //do something
             }

             @Override
             public void networkUnavailable() {
                //do something else
             }
         });
         registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
     }
    }
}

希望我能得到任何帮助,祝你好运:) ...