android检查与BroadcastReceiver的互联网连接

时间:2014-11-16 14:36:10

标签: android broadcastreceiver android-broadcast internet-connection

我尝试检查与BroadcastReceiver.i的互联网连接写了一些代码巫婆可以检查连接。现在,我想检查连接例如每5分钟 这是我的代码

public class BroadCastSampleActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    Timer timer = new Timer();
    timer.schedule(new TimerTask() {

        @Override
        public void run() {
            getApplicationContext().registerReceiver(
                    mConnReceiver,
                    new IntentFilter(
                            ConnectivityManager.CONNECTIVITY_ACTION));

        }
    }, 2000);
}

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        boolean noConnectivity = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
        String reason = intent
                .getStringExtra(ConnectivityManager.EXTRA_REASON);
        boolean isFailover = intent.getBooleanExtra(
                ConnectivityManager.EXTRA_IS_FAILOVER, false);

        NetworkInfo currentNetworkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
        NetworkInfo otherNetworkInfo = (NetworkInfo) intent
                .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

        if (currentNetworkInfo.isConnected()
                || otherNetworkInfo.isConnected()) {
            Toast.makeText(getApplicationContext(), "Connected",
                    Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Not Connected",
                    Toast.LENGTH_LONG).show();
        }
    }
};

}

我怎么写才能每次检查连接,(每5分钟一次) 如果有人知道解决方案,请帮帮我。谢谢

2 个答案:

答案 0 :(得分:0)

您应该使用AlarmManager检查互联网连接。检查official example并查看此tut。 我希望它能做到这一点

答案 1 :(得分:0)

您可以使用Timer以固定间隔重复任务。

Timer timer = new Timer();
t.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        boolean internetConnected = checkInternetConnection();
    }

}, 0, 300000);  //for repeating every 5 minutes

public boolean checkInternetConnection (){
    //your code
}

希望它有所帮助。