简体   繁体   中英

Get a list of all the implementations of an Interface in Android

I am working on a project in Android and want to know the Inte.net Connection State in every Activity and my App has more than 15 activities so, I don't want to implement and initialize my.networkstatechanged class and interface in every activity. So, I have created it's instance in a class that extends Application in which I create a object of my interface.

My NetworkStateChanged Class:

NetworkConnected.java

package time.real.identify.location.tracker.gps.saksham.com.emptrackerhost;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

interface NetworkListener {
    void isConnected();
    void isDisconnected();
}


public class NetworkConnected {

    private List<NetworkListener> listeners = new ArrayList<NetworkListener>();
    private boolean isConnected = false;
    private boolean wasConnected = false;

    NetworkConnected() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                isConnected = isOnline();
                wasConnected = isConnected;
                notifySomethingHappened();
                while(true){
                    isConnected = isOnline();
                    if(wasConnected != isConnected){
                        wasConnected = isConnected;
                        notifySomethingHappened();
                    }
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
    private boolean isOnline() {
        try {
            int timeoutMs = 3000;
            Socket sock = new Socket();
            SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

            sock.connect(sockaddr, timeoutMs);
            sock.close();

            return true;
        } catch (IOException e) {
            return false;
        }
    }
    void addListener(NetworkListener listener) { listeners.add(listener); }
    private void notifySomethingHappened() {
        for (NetworkListener listener : listeners) {
            if(isConnected){
                listener.isConnected();
            }
            else{
                listener.isDisconnected();
            }
        }

    }

}

ApplicationClass.java

package time.real.identify.location.tracker.gps.saksham.com.emptrackerhost;

import android.app.Application;

public class ApplicationClass extends Application {

    public static boolean isNetworkConnected = false;
    @Override
    public void onCreate() {
        super.onCreate();
        new NetworkConnected().addListener(new time.real.identify.location.tracker.gps.saksham.com.emptrackerhost.NetworkListener() {
            @Override
            public void isConnected() {
                isNetworkConnected = true;
            }

            @Override
            public void isDisconnected() {
                isNetworkConnected = false;
            }
        });
    }

}

After this I would just like to implement a interface in every class which would not need to be added as listener or initialized since one object is already running.

I want something like this:-

public class LoginPageClass extends Activity implements NetworkListener
{
public void isConnected(){
//Make a Snackbar
}
public void isDisconnected(){
//Make a Snackbar
}
}

Note:- I don't want to call object of myNetworkListener Class from ApplicationClass to add listener(this);

I just want to get a list of classes that implement my NetworkConnected Class in order to provide a state change callback to them. Is it possible? If so, how?

Of course on Java you can't extends two classes, so you can create a new class BaseAcivity that extends class Activity and make the job done on the NetworkConnected on this class (BaseActivity), and extend it on your activities instead of class Activity.

You can use BaseActivity As abstract and check the the inte.net as per the.network changes.

  • Require permissions
<!--Manifest.xml-->
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  • NetworkChangeListener.java
/* Interface required to call in each activity with whom you extends BaseActivity.java */
public interface NetworkChangeListener {
    void networkAvailable();

    void networkUnavailable();
}
  • BaseActivity.java

@SuppressLint("Registered")
public abstract class BaseActivity extends AppCompatActivity implements NetworkChangeListener {

    private BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            /* previous way of doing it*/
            NetworkInfo ni = null;
            if (manager != null) {
                ni = manager.getActiveNetworkInfo();
            }
            if (ni != null && ni.isConnected()) {
                networkAvailable();
            } else {
                networkUnavailable();
            }
        }
    };

    /*
     * If you like to check it manually you also cam use the bellow function for it
     * */

    public void checkInternet() {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        /* previous way of doing it*/
        NetworkInfo ni = null;
        if (manager != null) {
            ni = manager.getActiveNetworkInfo();
        }
        if (ni != null && ni.isConnected())
            networkAvailable();
        else
            networkUnavailable();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("NETWORK_STATE", "networkStateReceiver registerReceiver");
        registerReceiver(networkStateReceiver, new IntentFilter(android.net.ConnectivityManager.CONNECTIVITY_ACTION));
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("NETWORK_STATE", "networkStateReceiver unregisterReceiver");
        unregisterReceiver(networkStateReceiver);
    }
}


if you like to check the Inte.net manually you can use


    /*
     * If you like to check it manually you also cam use the bellow function for it
     * */
    public void checkInternet() {
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        /* previous way of doing it*/
        NetworkInfo ni = null;
        if (manager != null) {
            ni = manager.getActiveNetworkInfo();
        }
        if (ni != null && ni.isConnected())
            networkAvailable();
        else
            networkUnavailable();
    }
  • MainActivity.java

public class MainActivity extends BaseActivity {

    /*
     * Check the log for the proper results
     * */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void networkAvailable() {
        Log.e("NETWORK_STATE", "Connected");
    }

    @Override
    public void networkUnavailable() {
        Log.e("NETWORK_STATE", "Not Connected");
    }
}

Also if anything missed please refer Github repo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM