Skip to content

Instantly share code, notes, and snippets.

@androcool androcool/AndroidManifest.xml Secret
Last active Apr 12, 2020

Embed
What would you like to do?
Application class can be used to track which activity is running currently in your app and it could be used to apply common functionality to your app
<receiver android:name=".MyNetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
public class MyNetworkReceiver extends BroadcastReceiver {
private final String TAG = "MyNetworkReciver";
public static boolean isActive=false;
@Override
public void onReceive(Context context, Intent intent) {
isActive = isOnline(context);
Activity activity = SubApplication.mActivity ; // Getting Current Activity
if (!isActive) {
//if internet connection disconnected, then this block exceutes
//activity is currently running activity
}
}
//returns internet connection
public boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
return (netInfo != null && netInfo.isConnected());
} catch (NullPointerException e) {
e.printStackTrace();
return false;
}
}
}
public class SubApplication extends Application {
static Activity mActivity;
MyNetworkReceiver mNetworkReceiver;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
mNetworkReceiver = new MyNetworkReceiver();
}
@Override
public void onActivityStarted(Activity activity) {
mActivity = activity;
}
@Override
public void onActivityResumed(Activity activity) {
mActivity = activity;
registerNetworkBroadcastForNougat();
}
@Override
public void onActivityPaused(Activity activity) {
mActivity = null;
unregisterReceiver(mNetworkReceiver);
Log.d("MyApplicationTest", "onActivityResumed: un-registered");
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.