持续检查Android网络

时间:2013-11-14 05:50:59

标签: android networking

我想以这种方式持续验证Android系统网络,但我认为这种形式不正确,如果wifi或其他网络上的连接可用,我的服务应该更新。

public class ObjService extends Service{

    private final static int NOTIFICATION=1;
    public static boolean process;
    private NotificationManager state;
    private NotificationCompat.Builder objBuilder;

    public void onCreate(){
     process=true;
    state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);    
    objBuilder = new NotificationCompat.Builder(this)
            .setContentTitle("Title")
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
            .setSmallIcon(R.drawable.notification_img);



  Thread checker=new Thread(){//1
    public void run(){//2
    while (process){//3
    if (verifyConnection()){//4
      updateNotificationService("Service is available");
    }else{
     updateNotificationService("Service is not available");
    }//4
     try{
       Thread.sleep(6000);
     }catch(InterruptedException e){
      //..printLog..
     }
    }//3
   };//2

};//1
checker.start();
.
.
.

我的函数verifyConnection()是:

public boolean verifyConnection() {

        boolean flag = true;

      ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

       NetworkInfo[] net = connec.getAllNetworkInfo();

       if (!net[0].isAvailable() && !net[1].isAvailable())
       {
           flag = false;

       }
       return flag;  

    }

updateNotificationService()是:

public void updateNotificacionService(String arg){

objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());

state.notify(NOTIFICATION, objBuilder.build());
}

2 个答案:

答案 0 :(得分:4)

请尝试以下代码来监听连接是否存在,如果连接状态发生变化则通知更改,

public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
 super.onReceive(context, intent);
 Log.d("app","Network connectivity change");
 if(intent.getExtras()!=null) {
    NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
    if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
        Log.i("app","Network "+ni.getTypeName()+" connected");
    }
 }
 if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
        Log.d("app","There's no network connectivity");
 }
}
}

然后是清单,

<receiver android:name=".NetworkStateReceiver">
   <intent-filter>
      <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
   </intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

参考:Internet listener Android example

答案 1 :(得分:0)

Android 7.0(API级别24)对广播设置了限制,因为 Background Optimization中描述。 Android 8.0(API级别26)使 这些限制更加严格。

应用可以在运行时使用Context.registerReceiver()来注册 广播,无论是隐式还是显式。

文档reference

因此,这是一个实用程序类,它利用注册BroadcastReceiverLifeCycleObserver的上下文来实现Single-responsibility principle

class ConnectionUtil implements LifecycleObserver {

    private ConnectivityManager mConnectivityMgr;
    private Context mContext;
    private NetworkStateReceiver mNetworkStateReceiver;

    interface ConnectionStateListener {
        void onAvailable(boolean isAvailable);
    }

    ConnectionUtil(Context context) {
        mContext = context;
        mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        ((AppCompatActivity) mContext).getLifecycle().addObserver(this);
    }


    void onInternetStateListener(ConnectionStateListener listener) {
        mNetworkStateReceiver = new NetworkStateReceiver(listener);
        IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        // Registering the Context Registered Receiver
        mContext.registerReceiver(mNetworkStateReceiver, intentFilter);
    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {

        // Removing lifecycler owner observer
        ((AppCompatActivity) mContext).getLifecycle().removeObserver(this);

        // Unregistering the Context Registered Receiver
        if (mNetworkStateReceiver != null)
            mContext.unregisterReceiver(mNetworkStateReceiver);

    }


    public class NetworkStateReceiver extends BroadcastReceiver {

        ConnectionStateListener mListener;

        public NetworkStateReceiver(ConnectionStateListener listener) {
            mListener = listener;
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getExtras() != null) {
                NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo();

                if (activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
                    // Connected to the internet
                    mListener.onAvailable(true);

                } else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
                    // Not connected to the internet
                    mListener.onAvailable(false);
                }
            }
        }
    }

}

清单权限

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

用法:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConnectionUtil mConnectionMonitor = new ConnectionUtil(this);
        mConnectionMonitor.onInternetStateListener(new ConnectionUtil.ConnectionStateListener() {
            @Override
            public void onAvailable(boolean isAvailable) {
                if(isAvailable)
                    Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

注意:NetworkInfo自API 29起已过时,您可以将ConnectivityManager.NetworkCallback及其onAvailable()onLost()回调用于同一目的,而不必使用{{ 1}}。 This answer可以指导实现此目的。