Naham Soft
Naham Soft

Reputation: 91

How to listen to change in internet connection in my Android app?

I already created an android app which uses a web service to send and retrieve JSON data.

When I make a request while the device is online it works fine but when the device goes offline the app is stuck and prints Null Pointer Exception error.

Is there a way to listen to the internet connection?

Upvotes: 1

Views: 1246

Answers (4)

Slobodan Antonijević
Slobodan Antonijević

Reputation: 2643

From your question and comments, looks like you have a problem if the connection is lost during the request/response process. So in order to listen for this change you need to crate a BroadcastReceiver (NetworkStateReceiver) to listen to network state change, something like this: NetworkStateReceiver.java

package your.package.name;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import java.util.ArrayList;
import java.util.List;

public class NetworkStateReceiver extends BroadcastReceiver {
    // Listeners list
    protected List<NetworkStateReceiverListener> listeners;

    // Connection flag
    protected Boolean connected;

    /**
     * Public constructor
     */
    public NetworkStateReceiver() {
        listeners = new ArrayList<NetworkStateReceiverListener>();
        connected = null;
    }

    /**
     *
     * @param context  Context - Application context
     * @param intent  Intent - Manages application actions on network state changes
     */
    public void onReceive(Context context, Intent intent) {
        if(intent == null || intent.getExtras() == null) return;

        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = manager.getActiveNetworkInfo();

        if((ni != null) && ni.isConnected()) {
            connected = true;
        } else {
            connected = false;
        }

        mNotifyStateToAll();
    }

    /**
     * Notify the state to all needed methods
     */
    private void mNotifyStateToAll() {
        for(NetworkStateReceiverListener listener : listeners)
            mNotifyState(listener);
    }

    /**
     * Notify the network state
     * @param listener  NetworkStateReceiverListener - receives network state change
     */
    private void mNotifyState(NetworkStateReceiverListener listener) {
        if(connected == null || listener == null) return;

        if(connected == true) {
            listener.networkAvailable();
        } else {
            listener.networkUnavailable();
        }
    }

    /**
     * Add listener once it is needed
     * @param l  NetworkStateReceiverListener - receives network state change
     */
    public void addListener(NetworkStateReceiverListener l) {
        listeners.add(l);
        mNotifyState(l);
    }

    /**
     * Remove the listener once it is not needed anymore
     * @param l  NetworkStateReceiverListener - receives network state change
     */
    public void removeListener(NetworkStateReceiverListener l) {
        listeners.remove(l);
    }

    /**
     * Set interface to communicate with Main methods
     */
    public interface NetworkStateReceiverListener {
        public void networkAvailable();
        public void networkUnavailable();
    }
}

Your activity needs to implement this:

public class MyActivity extends Activity implements NetworkStateReceiver.NetworkStateReceiverListener {
    // Receiver that detects network state changes
    private NetworkStateReceiver networkStateReceiver;
    private boolean mNetworkAvailable;

    ...
    // What ever the code you want or need
    ...

    /**
     * Call back for NetworkStateReceiver to set the network state to available
     */
    @Override
    public void networkAvailable() {
        Log.d(TAG, "I'm in, baby! Dance, dance revolution!");
        sNetworkAvailable = true;
        // Network available again do things here
    }

    /**
     * Call back for NetworkStateReceiver to set the network state to unavailable
     */
    @Override
    public void networkUnavailable() {
        Log.d(TAG, "I'm dancing with myself, noone can see me.");
        sNetworkAvailable = false;
        // Network broke, warn the user, or do alternative action
    }

    /**
     * Need to register the receiver
     */
    @Override
    public void onResume() {
        super.onResume();

        // Register the network state receiver to listen to network state change
        if (networkStateReceiver == null) {
            networkStateReceiver = new NetworkStateReceiver();
            networkStateReceiver.addListener(this);
            this.registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
        }
    }

    /**
     * Unregister the receiver as you do not need it anymore
     */
    @Override
    public void onDestroy() {
        super.onDestroy();

        // Remove network state receiver and listener as we don't need them at this point
        if (networkStateReceiver != null) {
            networkStateReceiver.removeListener(this);
            this.unregisterReceiver(networkStateReceiver);
            networkStateReceiver = null;
        }
    }

    ...
    // What ever the code you want or need
    ...

}

Upvotes: 2

user5865012
user5865012

Reputation:

before request the web service call this method

private boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo NInfo = cm.getActiveNetworkInfo();

    if (NInfo != null && NInfo.isConnectedOrConnecting())
        return true;
    else
        return false;
}

if(isOnline()){
 // request the service 
 // but make sure that U have surrounded the calling web-service by try and catch
try{
     // here make your request when the connection go offline the app will    catch   the error and ignore the process 
}catch (Exception e) {
}

add this permission

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

Upvotes: 0

MrRobot9
MrRobot9

Reputation: 2684

  • You can check if it is connected to internet through this.

    private boolean isNetworkAvailable() { 
            ConnectivityManager manager = (ConnectivityManager)
                    getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = manager.getActiveNetworkInfo();
            boolean isAvailable = false;
    
            if(networkInfo != null && networkInfo.isConnected()) {
                isAvailable = true;
    
            } 
    
            return isAvailable;
     }
    

Upvotes: 1

Sasi Kumar
Sasi Kumar

Reputation: 13348

In your manifest add permission

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

Java

public boolean networkstatus() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
 }


if(networkstatus())
{
// do your process
}
else
{
//alert message for no internet connection
}

Upvotes: 0

Related Questions