código
código

Reputation: 53

Check Android Network continuously

I want to verify the Android system networks continuously in this way, but i think that in this form is not correct, my service should update if the connection on wifi or other network is available.

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

my function verifyConnection() is:

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() is:

public void updateNotificacionService(String arg){

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

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

Upvotes: 0

Views: 3354

Answers (2)

Zain
Zain

Reputation: 40830

Android 7.0 (API level 24) placed limitations on broadcasts, as described in Background Optimization. Android 8.0 (API level 26) makes these limitations more stringent.

Apps can use Context.registerReceiver() at runtime to register a receiver for any broadcast, whether implicit or explicit.

Documentation reference.

So, here is a utility class that utilizes a context registered BroadcastReceiver , and LifeCycleObserver for achieving 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);
                }
            }
        }
    }

}

Manifest permission

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

Usage:

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

Note: NetworkInfo is deprecated as of API 29, and you can use ConnectivityManager.NetworkCallback with its onAvailable() & onLost() callbacks for the same purpose instead of using a BroadcastReceiver. This answer can guide to target this purpose.

Upvotes: 0

sais
sais

Reputation: 843

Try this code below to listen whether the connection exist, if the connection state changes it notifies the change,

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

Then for manifest,

<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" />

Reference: Internet listener Android example

Upvotes: 4

Related Questions