Dynamic BroadcastReceiver to Check Online Connectivity - android

I want to dynamically set up a BroadcastReceiver to check whether or not I am online ONLY when my app is running in the foreground. Within my main class, I created an an Intent Filter, a nested BroadcastReceiver Class and finally register/unregister the receiver within the onResume and onPause methods respectively.
My question is, is there an an intent ACTION that I can add to my intent filter that checks for online connectivity?
If not, how can I create this Dynamic Broadcast Receiver to perform only when my app is running?
Here is what my Class looks like....
public class MainActivity extends AppCompatActivity {
private IntentFilter onlineIntentFilter;
private CheckOnlineReceiver checkOnlineReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onlineIntentFilter = new IntentFilter();
checkOnlineReceiver = new CheckOnlineReceiver();
//*****WHAT INTENT ACTION CAN I PASS TO CHECK NETWORK CONNECTIVITY******
onlineIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(checkOnlineReceiver, onlineIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(checkOnlineReceiver);
}
private class CheckOnlineReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(getApplicationContext(),"IN METHOD, ACTION = " + action, Toast.LENGTH_LONG).show();
}
}}

Add connectivity action
onlineIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
and don't forget to add the permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The broadcast receiver's onReceive() will be called on connectivity change which means on both connected and disconnected. so whenever you receive the braodcast you have check for connectivity as below
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
return false;
}

Here is the standard way to do this.
Create a interface which will have two methods onNetworkConnected() and onNetworkDisconnected()
public interface NetworkConnectivityListener {
public void onNetworkConnected();
public void onNetworkDisconnected();
}
Any class that wants to listen to network changes will implement this interface and override it's two methods.
Create a class which will extend the BroadcastReceiver and this receiver's onReceive() will catch the connectivity changes. In this class create a function to register the listeners
public class NetworkBroadcastReceiver extends BroadcastReceiver {
private NetworkConnectivityListener listener;
public NetworkBroadcastReceiver(NetworkConnectivityListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (listener != null) {
if (isConnectedToInternet()) {
listener.onNetworkConnected();
} else {
listener.onNetworkDisconnected();
}
}
}
PS you can easily check if your device is connected to internet or not. Just google.
Now let's say you want your MainActivity to listen to netwrork changes, all you have to do is implement the NetworkConnectivityListener in your main activity call and create an instance of the NetworkBroadcastReceiver passing the context of MainActivity and it will start to get the network updates.

add intentfilter CONNECTIVITY_ACTION

You will need to create a service as you are looking to perform a long-running task in the background.
A service will need to be registered in the manifest, within the <application> tags.
<service android:name=".WifiService"
android:stopWithTask="true"
android:enabled="true"/>
stopWithTask causes the service to be destroyed when all of your activities are destroyed (the default value is true).
You will need to register and unregister a BroadcastReceiver to the CONNECTIVITY_CHANGE action in the service class.
public class WifiService extends Service {
private BroadcastReceiver mReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
// Your BroadcastReceiver class
mReceiver = new WifiReceiver();
registerReceiver(mReceiver, filter);
return null;
}
#Override
public boolean onUnbind(Intent intent) {
unregisterReceiver(mReceiver);
return super.onUnbind(intent);
}
}
And then in the BroadcastReceiver you must listen for CONNECTIVITY_CHANGE.
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null &&
networkInfo.isConnectedOrConnecting();
if (isConnected) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_WIFI:
// Connected via wifi
break;
case ConnectivityManager.TYPE_ETHERNET:
// Connected via ethernet
break;
case ConnectivityManager.TYPE_MOBILE:
// Connected via mobile data
break;
}
}
}
}
With this setup you will be able to notify components of your application on connectivity change.

Related

Should I check connectivity in every activity in Android?

So I just implemented a checking connectivity method, but should I do this for every activity? Is there a simpler way to continually check for connectivity?
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
return isConnected;
}
First create a ConnectivityChangeReceiver like the following:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
private OnConnectivityChangedListener listener;
public ConnectivityChangeReceiver(OnConnectivityChangedListener listener) {
this.listener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
listener.onConnectivityChanged(isConnected);
}
public interface OnConnectivityChangedListener {
void onConnectivityChanged(boolean isConnected);
}
}
Then create a BaseActivity which extends all of your activites:
public class BaseActivity extends Activity implements OnConnectivityChangedListener {
private ConnectivityChangeReceiver connectivityChangeReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
connectivityChangeReceiver = new ConnectivityChangeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(connectivityChangeReceiver, filter);
}
#Override
public void onConnectivityChanged(boolean isConnected) {
// TODO handle connectivity change
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(connectivityChangeReceiver);
}
}
(If you don't want a BaseActivity, you can implement OnConnectivityChangedListener in all of your activities. But in that case you have to register the receiver in all of your Activity.)
You can check this out: This is service that will continuously check the connection. This will be the proper way to do it
`private void installListener() {
if (broadcastReceiver == null) {
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
NetworkInfo info = (NetworkInfo) extras
.getParcelable("networkInfo");
State state = info.getState();
Log.d("InternalBroadcastReceiver", info.toString() + " "
+ state.toString());
if (state == State.CONNECTED) {
onNetworkUp();
} else {
onNetworkDown();
}
}
};
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
}
}`
Look on this link: Android service to check internet connectivity?
Create some sort of util class, for example ConnectionUtils.
Add a public static method to that class and add a Context object to the parameters. For example:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Then in your Activity just call ConnectionUtils.isNetworkAvailable(this) to know if you're connected.
It would even be better to create some sort of base Activity that you extend with this method in it.
public abstract class BaseActivity extends Activity {
protected boolean isConnected() {
return ConnectionUtils.isNetworkAvailable(this);
}
}
And then let all your Activities extend BaseActivity instead of Activity
You should check before every request to the internet! The user can terminate the connection at any given time... even while your Activity is running.
I suggest you make an Utils class and put this method inside and make it public static so you can access it from everywhere within the Application.
I say it is better to check before every request. It might happen that the connection got broken in between. So its not wise to rely on a check sometime earlier

Using broadcastreceiver only on certain activity

I have two activities on is Register() and the other is ReadNews(). I am using broadcast receiver to detect internet connection automatically to execute some code.
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
if(MyApplication.isActivityVisible() == true) {
Log.d("WifiReceiver", "Have Wifi Connection");
Toast.makeText(context, "تم الإتصال بالشبكة", Toast.LENGTH_LONG).show();
if (context instanceof RegisterActivity){
Intent i = new Intent(context,
ReadNews.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
else {
}
}
}
How can I start the ReadNews() activity only when the internet connection goes on while the user still using the RegisterActivity() only?
I tried to use the context like if (context instanceof RegisterActivity) but that doesn't seem right.
As I said in a comment, you don't need an inner class, you can just create a stand-alone class, like this:
public class MyWifiReceiver extends BroadcastReceiver {
private Activity activityToFinish;
MyWifiReceiver(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
#Override
public void onReceive(Context context, Intent intent) {
// do what ever you want here
...
// finish the activity
activityToFinish.finish();
}
}
and in RegisterActivity, declare a private member variable like this:
private MyWifiReceiver wifiReceiver;
in RegisterActivity.onCreate() create an instance of the receiver passing the Activity in the constructor, like this:
wifiReceiver = new MyWifiReceiver(this);
then register and unregister the wifiReceiver as you've shown in your own answer.
Thanks to #Squonk comment, I have followed that short comment instructions to accomplish what I want to do and now I want to share summary of my code to show how this thing works:
Broadcast receiver inner class
private BroadcastReceiver wifiReceiver =
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//do what ever you want here
};
registering Broadcast receiver in onResume()
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); //or any intent filter you want
registerReceiver(wifiReceiver, filter);
}
unregistering Broadcast receiver in onPause
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(wifiReceiver);
}
Important
Don't use an <intent-filter> in the manifest.
registering the broadcast receiver must be dynamic (onResume,onPause)

Registering BroadcastReceivers from singleton

I'm trying to create a singleton class to report connectivity status. The idea being, I can reuse this "service" anywhere in my app e.g:
getApplication().getConnectivityStatus().isConnected()
The singleton has a reference to the ApplicationContext.
I'd like to use a BroadcastReceiver behind the scenes to detect connectivity changes. I'm registering and unregistering it dynamically within the connectivity "service" to implement a higher level listener for connectivity e.g:
getApplication().getConnectivityStatus().onConnectivity(mConnectivityCallback)
I only want the BroadcastReceiver to be registered at my discretion. I see a hole here, though, when the app is killed. Since there are no lifecycle callbacks for Application, there's nothing I can hook onto to unregister the BroadcastReceiver if the app is killed.
So, 1: my app dies but the BroadcastReceiver (with its reference to the ApplicationContext) stays registered and its onReceive method gets called... Do bad things happen?
2: Is there any way to cleanly do what I'm trying to do here or is my pattern just misconceived?
I would simply create BroadcastReceiver registered in the AndroidManifest.xml.
From that receiver you could update your singleton's connection status and you don't have to be worried about unregistering. If you don't want to other classes be able to change status, put receiver and singleton classes in the separate package and make setter method visibility to the package only.
Update
Your idea sound really interesting, having hermetic "service" that handles network changes and inform registered listeners. But, at the end your listeners are Activites which means that there will always be one listener at a time. Moreover, you cannot keep strong references to Activity in long lived objects and you have to use Activite's lifecycle callbacks.
I came to the conclusion that it would be better for you to go with very simple pattern(which I used to implement) of manager class.
Manager class could look like this:
public class NetworkManager {
private boolean connected;
private NetworkCallback callback;
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateStatus(context);
}
};
private void updateStatus(Context context) {
ConnectivityManager conn = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conn.getActiveNetworkInfo();
//TODO do the rest here, e.g. set connected flag
connected = networkInfo.isConnected();
if (callback != null) {
callback.onConnectionChanged(connected);
}
}
public void registerContext(Context context, NetworkCallback callback) {
this.callback = callback;
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(receiver, filter);
updateStatus(context);
}
public void unregisterContext(Context context) {
callback = null;
context.unregisterReceiver(receiver);
}
public interface NetworkCallback {
void onConnectionChanged(boolean connected);
}
}
It doesn't have to be a singleton if it's used by Activity only.
And Activity that use it:
public class NetworkActivity extends Activity implements NetworkManager.NetworkCallback {
private NetworkManager networkManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
networkManager = new NetworkManager();
}
#Override
protected void onResume() {
super.onResume();
networkManager.registerContext(this, this);
}
#Override
protected void onPause() {
networkManager.unregisterContext(this);
super.onPause();
}
#Override
public void onConnectionChanged(boolean connected) {
//TODO do something here
}
}
Hint
Do not force yourself to create code using sophisticated Patterns where it is not needed. Use Patterns only if your application actually benefit from their advantages.
Here am posting sample code who test internet connection through service and let user know is internet present or not through service may it will help you
BroadcastReceiverClass.java
package com.sample;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;
public class BroadcastReceiverClass extends android.content.BroadcastReceiver {
Context _con;
public BroadcastReceiverClass(Context _con) {
this._con = _con;
}
#Override
public void onReceive(Context context, Intent intent) {
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if (currentNetworkInfo.isConnected()) {
Toast.makeText(_con, "Connected", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(_con, "Not Connected", Toast.LENGTH_LONG).show();
}
}
}
/////////////////////////////////////////////////////////////////////////
BroadCastSampleActivity .java
package com.sample;
import android.app.Activity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
public class BroadCastSampleActivity extends Activity {
BroadcastReceiverClass mConnReceiver;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mConnReceiver = new BroadcastReceiverClass(this);
this.registerReceiver(mConnReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// this.unregisterReceiver(mConnReceiver);
}
// private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
// public void onReceive(Context context, Intent intent) {
// intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,
// false);
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
//
// NetworkInfo currentNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
//
// if (currentNetworkInfo.isConnected()) {
// Toast.makeText(getApplicationContext(), "Connected",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(getApplicationContext(), "Not Connected",
// Toast.LENGTH_LONG).show();
// }
// }
// };
}
/////////////////////////////////////////////
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name">
<activity android:name=".BroadCastSampleActivity"
android:label="BroadCast">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

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

How to reboot my current activity,when i connect net?

I am developing an application and I am displaying images from URl using xml parsing.
When internet gets disconnected I pop up alert window.
Now I wan my current activity automatically reboot, when my device connect net.
You need to have a BroadcastReceiver to listen to internet changes.
If you just need this logic in your activity you can do something like this:
private BroadcastReceiver mReceiver;
private IntentFilter mFilter;
#Override
protected void onCreate(Bundle savedInstanceState) {
mFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mReceiver = new ConnectionChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
private class ConnectionChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent i) {
ConnectivityManager connectivityManager = (ConnectivityManager) ActivityActionBar.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() == null) {
onLoseInternet();
}
}
}
onLoseInternet() method you should do something to reset everything.
Possibilities:
Best way I found so far
In the onCreate() method I have two calls: getWidgets() and populateWidgets().
getWidgets() is in charge of doing all the findViewById stuff and populateWidgets() will basically populate them with the correct info.
So when I need to reset the info I just call populateWidgets().
Hacky way
I don't know if this will work but you can try doing:
finish();
startActivity(new Intent(this, this.class));

Categories

Resources