Android 监听网络是否连接可用

   两种方式:Retrofit的NetworkUtils,blankj的NetworkUtils。

 

  1.在使用Retrofit2.0发http协议的时候,在发之前判断一下就行了

  /**
         * 先判断网络连接状态和网络是否可用,放在回调那里好呢,还是放这里每次请求都去判断下网络是否可用好呢?
         * 如果放在请求前面太耗时了,如果放回掉提示的速度慢,要10秒钟请求超时后才提示。
         * 最后采取的方法是判断网络是否连接放在外面,网络是否可用放在回掉。
         */
        if (!NetworkUtils.isConnected()) {
            ToastUtils.showShortToast("网络连接已断开");
            if (target != null) {
                target.setState(AppConstants.STATE_ERROR);
            }
            return;
        }

2.  blankj,它是一个三方开发工具包有很多常用的开发方法,如果需要实时性,比如界面上有网络是否连接的UI图标,时刻显示当前的网络连接状态,但是时间不用特别精确

一.导入blankj:

 implementation 'com.blankj:utilcode:1.3.6'

二.使用blankj提供的NetworkUtils,在比如主活动中开启一个线程,线程死循环间隔若干秒监听判断就行了

    private class StateThread extends Thread {
        @Override
        public void run() {
            super.run();

            while (true) {
                try {
                    Thread.sleep(6000);
                 if (NetworkUtils.isConnected()) {
                        //XX逻辑
                   }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }

 

     但是如果时间要求更精确,那么就要使用一个Service,让它在后台通过ConnectivityManager监听网络的状态,为了保证这个Service不被杀死能一直监听,还需要使用Service的保活,保证Service即使被杀死也能立刻再重新调用起来。

 

public class MessageService extends Service {

    public final static ConnectReceiver conncetReceiver = new ConnectReceiver();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
        startGuardService();
        DeviceEngine.getInst().init( this.getApplicationContext() );


        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        filter.addAction("android.intent.action.USER_PRESENT");
        registerReceiver( conncetReceiver , filter);

        Notification notification = new Notification();
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        this.startForeground(1, notification);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "ServiceDemo onStartCommand");
        flags = START_STICKY;
        return super.onStartCommand(intent, flags, startId);

    }

    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
        Intent intent = new Intent( ACTION );
        sendBroadcast(intent);
        unregisterReceiver( conncetReceiver );
        Log.d(TAG, "sendBroadcast[" + ACTION + "]");
    }


    public void startGuardService()
    {
        Intent intent = new Intent();
        intent.setClass(this, GuardService.class);
        startService(intent);
    }



    private final static String TAG = "MessageService";
    public final static String ACTION = "com.luobeitech.automgr.guard.CONNECT_SERVICE";
}

 

public class ConnectReceiver extends BroadcastReceiver {

    private static Receiver receiver = null;
    public static void setReceiver( Receiver _receiver )
    {
        receiver = _receiver;
    }
    private final static String TAG = "ConnectReceiver";


    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = null;
        String action = intent.getAction();
        if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            Log.d("mylog", "网络状态已经改变");
            info = connectivityManager.getActiveNetworkInfo();
            if(info != null && info.isAvailable()) {
                String name = info.getTypeName();
                Log.d("mylog", "当前网络名称:" + name);

//                if( receiver != null) {
////                    receiver.onConnect( context.getApplicationContext() , name );
//                }
            } else {
                Log.d("mylog", "没有可用网络");
//                if( receiver != null) {
//                    receiver.onDisconnect();
//                }
                EventBus.getDefault().post(new OnlineStateEvent(-1));
            }
        } else if (Intent.ACTION_SCREEN_ON.equals(action)) {
            // 开屏

            KeyguardManager mKeyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
            boolean flag = mKeyguardManager.inKeyguardRestrictedInputMode();
            if (flag) {
                BusinessUtil.getInst().lockScreenState = true;
            } else {
                BusinessUtil.getInst().lockScreenState = false;
            }
            Log.d("mylog", "开屏" + flag);
        } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
            // 锁屏
            BusinessUtil.getInst().lockScreenState = true;
            Log.d("mylog", "锁屏");
        } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
            // 解锁
            BusinessUtil.getInst().lockScreenState = false;
            Log.d("mylog", "解锁");
        }

    }

    public interface Receiver {
        void onDisconnect();
        void onConnect(Context context, String name);
    }


}

 

关于线程保活的技术,会再写一个进行记录

 

https://blog.csdn.net/Crystal_xing/article/details/84233622

 

你可能感兴趣的:(android)