Android服务:检测数据连接是否可用Wifi或移动数据

时间:2018-11-08 04:42:01

标签: android android-service android-internet

如何通过Wifi或移动数据连续或按计划检测是否有数据连接?

即使应用程序处于前台,后台或被系统或用户杀死,我也需要对其进行检测。

我已经看过很多相关的问题和示例代码,但是他们说出于安全原因,Android N及更高版本中的情况有所变化。

2 个答案:

答案 0 :(得分:0)

//This is your service class working fine just add network state permission in your manifest and at runtime

    public class MyService extends Service {
        private static final String TAG = "MyService";
        private ServiceHandler serviceHandler;
        private static final int MSG_REQUEST = 1112;
        static Context context1;
        public static void startService(Context context) {
            context1=context;
            Intent myIntent = new Intent(context, MyService.class);
            context.startService(myIntent);
        }

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


        private class ServiceHandler extends Handler {
            ServiceHandler(Looper looper) {
                super(looper);
            }

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case MSG_REQUEST:
                        checkNetwork();
                        break;
                }
            }
        }

        private void checkNetwork() {
        ConnectivityManager cm = (ConnectivityManager)context1.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        String networkType = "";
        if (info.getType() == ConnectivityManager.TYPE_WIFI) {
            Log.d("yahooooooo","WIFI");
        }
        else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

            networkType = "mobile";
            Log.d("yahooooooo","MOBILE");
        }
     if (!serviceHandler.hasMessages(MSG_REQUEST)) {
            serviceHandler.sendEmptyMessageDelayed(MSG_REQUEST, 1000);//every 1 sec
        }

        }

        @Override
        public void onCreate() {
            super.onCreate();
            HandlerThread handlerThread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
            handlerThread.start();
            serviceHandler = new ServiceHandler(handlerThread.getLooper());
        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if (!serviceHandler.hasMessages(MSG_REQUEST)) {
                serviceHandler.sendEmptyMessage(MSG_REQUEST);
            }


            return START_REDELIVER_INTENT;
        }

        @Override
        public void onTaskRemoved(Intent rootIntent) {
            super.onTaskRemoved(rootIntent);

            PendingIntent service = PendingIntent.getService(
                    getApplicationContext(),
                    1001,
                    new Intent(getApplicationContext(), MyService.class),
                    PendingIntent.FLAG_ONE_SHOT);

            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            assert alarmManager != null;
            alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1000, service);
        }

    }

//现在从“活动”中调用服务

    MyService.startService(MainActivity.this);

//在清单中

    <service
    android:name=".MyService"
    tools:ignore="InnerclassSeparator" />

答案 1 :(得分:0)

尝试以下代码。...

    Boolean  bs_netcheck=false;
    bs_netcheck = netCheck();
    if(!bs_netcheck)
    {
        displayAlert();
    }

public void displayAlert()
{

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setMessage("Internet Connection Required...! \nPlease Check Your Internet Connection and Try Again");
    TextView title = new TextView(MainActivity.this);
    title.setText("Network Error");
    title.setBackgroundColor(R.color.colorAccent);
    title.setPadding(20, 20, 20, 20);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.WHITE);
    title.setTextSize(20);
    builder.setCustomTitle(title)
            .setPositiveButton(android.R.string.ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton){
                            finishAffinity();
                        }
                    });
    builder.show();
}

public boolean netCheck()
{
    ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

    assert conMgr != null;
    if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
            || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED ) {
//notify user you are not online
        bs_netcheck =true;

    }
    return bs_netcheck;
}

在AndroidManifest.xml中添加以下权限

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