简体   繁体   中英

android check internet connection with BroadcastReceiver

i try to check internet connection with BroadcastReceiver.i wrote some code witch can to check connection.and now,i want to check connection for example every 5 min this is a my code

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();
        }
    }
};

}

how i can write to can check connection everytime,(every 5 min) if anyone knows solution please help me.thanks

You should use AlarmManager to check the Internet-connection.Check the official example and check out this tut . I hope it should do the trick

You can use Timer for repeating a task at fixed interval.

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
}

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM