I have a Main Activity, which holds 1 fragment. The fragment is responsible for drawing the UI, running an Async task, etc. All of this requires an internet connection. Now when I first launch my app I check whether there is an internet connection or not through a method:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());
}
If there is no network connection, the activity starts the fragment, but I've made it so that without an internet connection nothing shows (since there is nothing to show because I am downloading content from an online database).
I want to implement a broadcast receiver, which would restart the fragment somehow, when there is an internet connection available. So far I have a broadcast receiver as an Inner class in my Main activity:
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Toast.makeText(context, "internet ++", Toast.LENGTH_LONG).show();
//this is where the fragment needs to be somehow reinstantiated
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "internet --", Toast.LENGTH_LONG).show();
}
}
}
};
I've tried to make the broadcast receiver an outer class, but then I cannot do anything to the fragment.. When it is an Inner class, nothing happens with the code from the broadcast receiver. I've reviewed a lot of similar questions, but nothing seems to work from me.
So the question at hand would be: How do I refresh a fragment inside an activity, when the internet connection becomes available while the app is running?
Your implementation is just wrong. You should start your fragment and request through the network, and meanwhile show ProgressBar or something else to the user. If Internet is not available, in any way, you get the error then show user the problem. On the other hand, if you get the response successfully, just set your data to your view. BTW, your method for finding availability of network is not guaranteed that "Internet" is available.
Related
I have an app and in that, I want to check the real-time network of the mobile phone.
This is my java code:
This is only some of the full java file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
if (checkNetwork() == false) {
Toast noNetwork = Toast.makeText(getApplicationContext(), "Sync is paused, due to no
internet...", Toast.LENGTH_LONG);
noNetwork.show();
} else if (checkNetwork() == true) {
Toast yesNetwork = Toast.makeText(getApplicationContext(), "Sync is turned on...",
Toast.LENGTH_LONG);
yesNetwork.show();
}
// This code we will add later - bottomNavigation.getMenu().removeItem(R.id.navigation_notes);
}
private boolean checkNetwork() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
If I open my app and navigate to this page, it shows the internet is there toast, but at the same time when I turn off mobile data, the other toast which shows internet is not there is not shown. I think the above code is not real-time or there is a problem with the toast, I don't know.
I want to know if there are ways in which I could make the above code real-time. Thanks in advance.
Register a NetworkCallback using registerNetworkCallback() method. Example code is given here.
I have connected my android phone with LAN connection. I would like to display a toast or an alert when I disable LAN connection. I am trying the following code but its of no use. What am I missing ?
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isNetworkAvailable(MainActivity.this);
}
// to check connection state
public static boolean isNetworkAvailable(Context context){
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
Network network = connectivityManager.getActiveNetwork();
NetworkCapabilities networkCapabilities = connectivityManager.getNetworkCapabilities(network);
if(networkCapabilities == null){
Toast.makeText(context, "No Internet connection!", Toast.LENGTH_LONG).show();
}
return true;
}
}
I couldn't Use NetworkInfo since its been deprecated. Thanks in advance
UPDATE:
I solved my problem using the example from the link below.
Very well explained. Have a look :)
Detect internet Connection
First of all the code you showed will be triggered only when activity is created and only once. What you need is Monitor for changes in connectivity
As mentioned:
Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver in their manifest
Meaning that you will have to create a custom broadcast receiver (I use kotlin for android development, you should be able to translate that to java):
class NetworkStatusReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
// check intent action for the connection status
}
}
To use the receiver, you need to register it in your activity (a better choice would be to use a service if you need it across multiple activities):
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
filter.addAction("mypackage.CONNECTIVITY_CHANGE")
val permissionReceiver = NetworkStatusReceiver()
registerReceiver(permissionReceiver, filter)
To avoid memory leaks or multiple bindings it is recommended to unbind the receiver once the lifecycle of you component ends, you can do that by:
unregisterReceiver(permissionReceiver)
Also don't forget to add to your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Try this
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(isNetworkConnected){
}else{
Toast.makeText(context, "No Internet
connection!",Toast.LENGTH_LONG).show();
}
}
public boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnected();
}
}
First added network permissions in you manifest.xml file:
ex:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then create and register a broadcast receiver class which will be notified whenever there is a change in network/internet connection.
Here is a good example
link: https://www.androidhive.info/2012/07/android-detect-internet-connection-status/
This question already has an answer here:
Notification every time wifi disconnects
(1 answer)
Closed 9 years ago.
I need my application to give a notification whenever WiFi goes offline.
I got it to give a notification every time the WiFi connection changes. But I need it to only give a notification when it goes offline.
Also it gives a notification on start-up (of the application).
My question is, how do I alter the code to only give a notification when WiFi goes offline? Now it gives a notification when it goes offline, online and on start-up.
The code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_main);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
}
else{showNotification();}
}
};
use this line in onReceive() of BroadCastReceiver
if(!isNetworkConnectionAvailable(ctx)){
Toast.makeText(ctx, "Network Connection Available ", Toast.LENGTH_LONG).show();
}
the code for isNetworkConnectionAvailable() is
public static boolean isNetworkConnectionAvailable(Context context)
{
boolean isNetworkConnectionAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null)
{
isNetworkConnectionAvailable = activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED;
}
return isNetworkConnectionAvailable;
}
comment me about result
Use this to check connectivity InetAddress.isReachable, the method returns true if you have connectivity else false
I am working on android project which communicate with a webservice in order to receive datas and store them into the database.
Before the sending operation, I verify the connection state (see the code below)
if (XXX.getInstance(Context).isOnline(Context))
{
//TODO Sending operation
}
But during this operation if the device is offline I lose datas though the HTTP status code is 200 or 201.
I manage before the operation but not during.
Is there a way to figure this out?
Use a broadcast receiver to constantly check the status of the connection.
First register the receiver in your onCreate() method:
registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
Then write what you want to do when your desired signal has been discovered:
private BroadcastReceiver mReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
//You are still connected
}
else
{
//You have lost connection
}
}
};
Make sure you unregister the receiver once you leave the activity (in the onDestroy()) method:
if (mReceiver != null)
{
unregisterReceiver(mReceiver);
}
This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How can I monitor the network connection status in Android?
I need to continuously check whether the internet is connected or not and update the text area accordingly with appropriate message . Now if i create an asynctask it will execute once and stop which is not what I want . I want to check at every moment continuously and obviously this should not be on the main thread .So Service wont be a good choice either . Can anyone help me What is the best and efficient approach to handle this . Thanks
do it with a receiver. you can be notified about network state change. for example,
private BroadcastReceiver networkReceiver = new BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
// we're connected
}
}
// we're not connected
}
}
register this in your onResume(), and unregister on onPause().
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkReceiver);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkReceiver, filter);
}
additionally, to obtain the initial state before your receiver has been registered, call this in your onResume() method,
public boolean isNetworkConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
make sure your app requests this permission,
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
You don't need to constantly ask the OS if there is a network connection. Simply check whether a connection exists in onResume() and then use a BroadcastReceiver to listen for the CONNECTIVITY_ACTION Intent from the ConnectivityManager when the connection is changed and check EXTRA_NO_CONNECTIVITY.