Network listener Android - java

I want to check when the network of phone in Android goes off. Can I capture that event?
I am not getting the proper API or any example which would explain the same. If anyone had done or any example links would be really helpful.

New java class:
public class ConnectionChangeReceiver extends BroadcastReceiver
{
#Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " + activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " + mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
New xml in your AndroidManifest.xml under the "manifest" element:
<!-- Needed to check when the network connection changes -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
New xml in your AndroidManifest.xml under the "application" element:
<receiver android:name="com.blackboard.androidtest.receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>

I have been using a small setup to check the bandwidth for determining how to scale things, such as images.
Under the activity, in AndroidManifest:
<intent-filter>
...
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
In the activity where the checks are being performed:
boolean network;
int bandwidth;
#Override
public void onCreate(Bundle savedInstanceState) {
...
network = isDataConnected();
bandwidth = isHighBandwidth();
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
network = isDataConnected();
bandwidth = isHighBandwidth();
}
}, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
...
}
...
private boolean isDataConnected() {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
return false;
}
}
private int isHighBandwidth() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
return wm.getConnectionInfo().getLinkSpeed();
} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
return tm.getNetworkType();
}
return 0;
}
An example usage would then be:
if (network) {
if (bandwidth > 16) {
// Code for large items
} else if (bandwidth <= 16 && bandwidth > 8) {
// Code for medium items
} else {
//Code for small items
}
} else {
//Code for disconnected
}
It's not the prettiest, but it allows enough flexibility that I can change the bandwidth cutoff for items depending on what they are and my requirements for them.

If using Android Annotations is an option for you try this in your activities - that's all, the rest is generated:
#Receiver(actions = ConnectivityManager.CONNECTIVITY_ACTION,
registerAt = Receiver.RegisterAt.OnResumeOnPause)
void onConnectivityChange() {
//react
}
Use this only if you already use AndroidAnnotations - putting this dependency inside your project only for this piece of code would be overkill.

The above answer only works if mobile packet data is enabled. Otherwise, ConnectivityManager would be null and you can no longer retrieve NetworkInfo. The way around it is to use a PhoneStateListener or TelephonyManager instead.

Related

Display an alert when Internet connection is off

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/

Android Redmi 6A issues - Failed to connect to the server trigger by Event BOOT_COMPLETED

I have problem with specific device REDMI 6A (with OS MIUI Android Oreo 8.1), according to my project. it's simple application, only connect to the server trigger by BOOT_COMPLETED event. i try to check the internet connection is connected or not. it is really weird the Redmi 6A can't connect,but when i test with MI A1 (OS Android Oreo 8.1 - Android One) the device can connect as well. I really don't understand why this can be happen. I really appreciate if some one can advice me.
This Below the code.
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.NETWORK" />
....................
<service
android:name=".services.SocketJobIntentService"
android:exported="false"
android:permission="android.permission.BIND_JOB_SERVICE" android:label="#string/socket_job" />
<receiver
android:name=".broadcast.MainBroadCastReceiver"
android:enabled="true"
android:label="#string/receiver_name">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".services.SocketSvc"></service>
SocketJobIntentService.java
public class SocketJobIntentService extends JobIntentService {
static Context context;
static final int JOB_ID = 1000;
public static void enqueueWork(Context _context, Intent work) {
context = _context;
enqueueWork(_context, SocketJobIntentService.class, JOB_ID, work);
}
public boolean isOnline(Context context) {
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());
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
if(context==null){context = this;}
boolean isInternetConnected = isOnline(context);
if(isInternetConnected) {
Log.d("DT_JobIntentService","Executed!! and try to Calling Another Service 'SocketSvc' !!!");
Intent service = new Intent(this,SocketSvc.class);
startService(service);
}else{
Log.e("DT_WeGetEcon","isInternetConnected=false !!!!!! LOL!");
}
}}
MainBroadCastReceiver.java
public class MainBroadCastReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
try {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
Log.d("DT_MainBroadCastRceiver", action+" Called !!!");
SocketJobIntentService.enqueueWork(context, new Intent());
Log.d("DT_JobIntent","Try to call JobIntent");
}
}
catch (Exception exc){
Log.e("DT_ERR_ACTBOOT_COMPLTED",exc.getMessage());
}
}}
LogCat
LogCat MI A1
LogCat RedMI 6A
I really appreciate if anyone can advice me.
Thanks
Finally, I found my own solution.
Just put two line code inside onReceive MainBroadCastReceiver.java
public void onReceive(final Context context, Intent intent) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
ref to : Error StrictMode$AndroidBlockGuardPolicy.onNetwork

How to choose the internet connection mode Android

I made an Android application that is used to exchange files with a pc.
The computer and the device are connected to the same network and everything worked very well.
But since I put a 4g sim card, the transfer is no longer done, does anyone know how to solve this problem?
There must be a way to force my application to use only ethernet connection?
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
How I check connection:
public static Boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
boolean isEthernet = false;
if (activeNetwork != null) {
isEthernet = activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET;
}
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting() && isEthernet;
}
Main function:
public void sendFilesInFolder(Boolean bool) {
if (isConnected(MainActivity.this)) {
ProgressBar progressBar;
if (bool) progressBar = mProgressBarD;
else progressBar = mProgressBarM;
fileSender = new FileSender(prefs.getString("ip_adress", null),
Integer.valueOf(prefs.getString("port_dest", null)),
bool, colisageBase, progressBar);
fileSender.execute();
} else {
Toast.makeText(MainActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}

How to detect when user connects to wifi or mobile internet in android

I want to check for particular update when user each time connects to internet.I tried the following codes :
unfortunately app is getting stopped while checking for network
Broadcast receiver for checking internet connection in android app
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Java
public class UpdateReceiver extends BroadcastReceiver {
#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();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
My problem is these codes only receive only once , If the user disconnect wifi and reconnects the BroadcastReceiver unable to notify.Any help is appreciated .
Once I had implemented a check in my app, to see if there is any internet connection or not. You can have a look at this --
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context cont){
this.context = cont;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
You can initialize an object of this class in your OnCreate method.
And finally call this class' method just before you upload files.
Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
//perform your job here.
}
EDITED::
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
Hope this helps.

How to check programmatically if "use wireless networks" is enabled on Android?

I don't want to check if there is any connectivity over WIFI or 3G!
I just want to verify (and not change!) if the "Use wireless networks"-CheckBox is enabled (the one you can set in Settings > Location and security > My location > HERE)
Thanx
Code from RajaReddy will check if Wifi is enabled for network. If you want to know if Wifi is enabled for positioning then this should do (replace "context" with something useful)
ContentResolver cr = context.getContentResolver();
boolean wifiEnabled = Settings.Secure.isLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER);
example code for API Level < 8
private static boolean isWifiLocationEnabled (Context context) {
ContentResolver cr = context.getContentResolver();
String enabledProviders = Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!TextUtils.isEmpty(enabledProviders)) {
// not the fastest way to do that :)
String[] providersList = TextUtils.split(enabledProviders, ",");
for (String provider : providersList) {
if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
return true;
}
}
}
return false;
}
use this code
public Boolean isNetAvailable(Context con) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiInfo.isConnected()) {
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
and following permissions are required for this
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Categories