I have a manifest registered BroadcastReceiver that I am using to monitor WiFi disconnects. I receive a disconnect broadcast every time the device scans for WiFi. I need some way to determine if the broadcast was a result of scanning for WiFi or the device actually disconnected from a network.
public class WifiReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
if(!intent.getAction().equals("android.net.wifi.STATE_CHANGE"))
return;
NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (networkInfo != null) {
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if(networkInfo.getDetailedState() == CONNECTED || networkInfo.getDetailedState() == DISCONNECTED)
PresenceData.loadData(context);
if(networkInfo.getDetailedState() == CONNECTED) {
System.out.println("Wifi connected");
PresenceData.sendNotification("Wifi Connected", "You are now connected to " + PresenceData.getCurrentWifiSSID(context), context);
PresenceData.submitChanges(context);
} else if(networkInfo.getDetailedState() == DISCONNECTED) {
System.out.println("Wifi Disconnected");
PresenceData.sendNotification("Wifi Disconnected", "Your wifi has disconnected", context);
UpdaterService.scheduleUpdate(context);
}
}
}
}
}
You could try using NetworkInfo.State to get the current state of the network. There are enumerations for all kinds of possible states, such as failures, successes, scanning, etc. Below is a sample on how to retrieve the info:
public class MainActivity extends AppCompatActivity {
private ConnectivityManager connectivityManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.connectivityManager = (ConnectivityManager)
this.getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
System.out.println("Network Status " + info.getDetailedState().name());
}
}
Related
I build the dialogue box for my android app. Its working well, but i encountered some issues related to the dialogue box.
(1) I want when internet connection or WiFi get connected. automatically dialogue box get disappeared.
(2) In middle of the app is running if internet connection get lost. dialogue box again appears automatically.
if (!isConnected(Dashboard.this)) buildDialog(Dashboard.this).show();
else {
setContentView(R.layout.activity_dashboard);
}
public boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netinfo = cm.getActiveNetworkInfo();
if (netinfo != null && netinfo.isConnectedOrConnecting()) {
android.net.NetworkInfo wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((mobile != null && mobile.isConnectedOrConnecting()) || (wifi != null && wifi.isConnectedOrConnecting()))
return true;
else return false;
} else
return false;
}
public AlertDialog.Builder buildDialog(Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("No Internet Connection");
builder.setMessage("You need to have Mobile Data or WiFi to access this. Press OK to Exit");
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Dashboard.super.onBackPressed();
}
});
return builder;
}
Use properties builder.setCancelable(false); in your aleart dailog
Put this line out of the alert dialog code
alertDialog.setCancelable(false);
To automatically get internet connectivity events try setting up a network change listener. Here is a sample:
/**
* Broadcast receiver that detects receives notification when change in internet connection to alert when there is no Internet.
*/
public class NetworkChangeReceiver extends BroadcastReceiver {
private NetworkChangeListener mListener;
public NetworkChangeReceiver(NetworkChangeListener listener) {
mListener = listener;
}
#Override
public void onReceive(final Context context, #NonNull final Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
boolean connected = activeNetwork != null && activeNetwork.isConnected();
mListener.onNetworkConnectedStateChanged(connected);
}
}
public interface NetworkChangeListener {
void onNetworkConnectedStateChanged(boolean connected);
}
}
You then register the listener in your Activity or Fragment
#Override
public void onStart() {
super.onStart();
if (mNetworkChangeReceiver == null) {
mNetworkChangeReceiver = new NetworkChangeReceiver(this);
getContext().registerReceiver(mNetworkChangeReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
Then show / dismiss your dialog on network connected state changed
#Override
public void onNetworkConnectedStateChanged(boolean connected) {
if (connected) {
//dismiss dialog
} else {
//show dialog
}
}
You have to setCancelable == false for stop tounching outside of dialog.
In Your case You have to put like this in your AlertDialog.Builder after setMessage
builder.setCancelable(false);
and Use this functionality for User that on Backpress button You have to setCancelable == true
for that You have to write code in onBackPressed like this :-
builder.setCancelable(true);
You need add Broadcast receiver to get connectivity status.
Then you need to keep builder global.
private AlertDialog.Builder builder;
Just create a BroadcastReceiver to track your internet connectivity
first, create a NetworkChangeReceiver class like this
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try {
if (isOnline(context)) {
//show dialog when internet on
dialogHome(true);
Log.e("pradeep", "Online Connect Internet ");
} else {
//hide dialog when internet off
dialogHome(false);
Log.e("pradeep", "Connectivity Failure !!");
}
} catch (NullPointerException e) {
e.printStackTrace();
Log.i(getClass().getName(), "exceptional " + e.toString());
}
}
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;
}
}
}
after that just add below code in application tag which is located in AndroidMenifest.xml
<receiver android:name=".utils.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Final step
just create your BroadcastReceiver instance in your activity where you check the internet activity
private BroadcastReceiver mNetworkReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//init broadcast receiver
mNetworkReceiver = new NetworkChangeReceiver();
}
#Override
protected void onResume() {
super.onResume();
if (((NetworkChangeReceiver) mNetworkReceiver).isOnline(mContext)) {
} else {
registerNetworkBroadcastForNougat();
}
}
private void registerNetworkBroadcastForNougat() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdf" + e.toString());
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
} catch (Exception e) {
Log.i(getClass().getName(), "easdfdfdd" + e.toString());
}
}
}
protected void unregisterNetworkChanges() {
try {
unregisterReceiver(mNetworkReceiver);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterNetworkChanges();
}
whenever internet connection changes BroadcastReceiver call onReceive Method.
Hope helpful for you...
Mission is to check if the mobile is connected on internet or not. I have problem.
It shows "Connected" even when wifi is off. Here is my class.
public class InterneProvjera {
Context context;
#SuppressLint("MissingPermission")
public InterneProvjera(Context context){
this.context = context;
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (NetworkInfo i: info) {
if (i.getState() == NetworkInfo.State.CONNECTED)
return true;
}
}
}
return false;
}
}
And here is in the main activity :
InterneProvjera interneProvjera = new InterneProvjera(this);
String tKonekcija = (interneProvjera.isNetworkAvailable()) ? "Connected" : "No connection";
txtIspis.setText(tKonekcija);
Sorry if its trivial question im new in android programming.
Ps: is there any Connection listener and how to check internet signal strength (3G, 4G, wifi)?
You should use BroadcastReceiver to check the network status using ConnectivityManager
Below is the code to check in your activity if network is connected or not. If connected, it will show you name of network in Toast:
ConnectivityStatusReceiver.java
public class ConnectivityStatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) {
Toast.makeText(context, activeNetworkInfo.getTypeName() + " connected", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Internet or Network connection available", Toast.LENGTH_LONG).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ConnectivityStatusReceiver connectivityStatusReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectivityStatusReceiver = new ConnectivityStatusReceiver();
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectivityStatusReceiver, intentFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (connectivityStatusReceiver != null) {
// unregister receiver
unregisterReceiver(connectivityStatusReceiver);
}
}
}
in my app there is a modul with a weather activity. When the user click and activate the weather function there is a check for network connectivity. The Problem is, direct on start, there comes my toast message "No network connectivity" with the Android Dialog to enable.
When the user click "enable" there is nothing to activate in the options (Everything is on).
When the user click "cancel" the Dialog disappears and the app is working.
Here is my code from the activity:
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
#Override
public void onStart() {
super.onStart();
EasyTracker.getInstance(this).activityStart(this);
// Connect the client.
mLocationClient.connect();
// Registers BroadcastReceiver to track network connection changes.
mNetworkReceiver = new NetworkReceiver() {
private MyAlertDialog enableNetworkDialog = null;
#Override
public void onNoConnectivity() {
Toast.makeText(MainActivity.this,
getString(R.string.network_disabled), Toast.LENGTH_LONG)
.show();
// If the dialog already prompted, do nothing
if (enableNetworkDialog != null
&& enableNetworkDialog.isShowing())
return;
// Prompt a dialog for user to open the network settings screen
enableNetworkDialog = new MyAlertDialog(MainActivity.this,
null, getString(R.string.network_disabled), false);
enableNetworkDialog.setPositiveButton("Enable",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
toggleNetworkSourceSetting();
}
});
enableNetworkDialog.setNegativeButton("Cancel",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
enableNetworkDialog.show();
}
#Override
public void onConnect() {
if (enableNetworkDialog != null
&& enableNetworkDialog.isShowing())
enableNetworkDialog.dismiss();
}
#Override
public void onNetworkChange() {
}
#Override
public void onReconnect() {
}
};
}
UPDATE: This is my manifest:
<!-- Grant the network access permission -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
This are cutouts from my logcat:
[ 07-19 10:43:17.876 18037:18037 D/ ]
Current Network Info : NetworkInfo: type: mobile_supl[HSPA+, type_ext: mobile_supl], state: DISCONNECTED/DISCONNECTED, reason: dataDisabled, extra: internet.telekom, roaming: false, failover: false, isAvailable: true, isConnectedToProvisioningNetwork: false, isIpv4Connected: false, isIpv6Connected: false
[ 07-19 10:43:17.876 18037:18037 D/ ]
No network is available
07-19 10:43:19.778 18037-18037/bakteriusdeveloper.master D/Network Connection: mobile is available
Update super method:
/**
* The subclass of the BroadcastReeiver is used to detect the change of
* connectivity.
*
*/
public class NetworkReceiver extends BroadcastReceiver {
public NetworkReceiver() {
super();
}
public void onNoConnectivity() {
};
public void onNetworkChange() {
};
public void onConnect() {
};
public void onReconnect() {
};
public void toggleNetworkSourceSetting() {
startActivity(new Intent(
android.provider.Settings.ACTION_WIRELESS_SETTINGS));
}
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conn = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activNetworkInfo = conn.getActiveNetworkInfo();
String failMessage = intent
.getStringExtra(ConnectivityManager.EXTRA_REASON);
Logger.printMessage(getClass().getSimpleName(), failMessage,
Logger.DEBUG);
Boolean isNoConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
Boolean isFailOver = intent.getBooleanExtra(
ConnectivityManager.EXTRA_IS_FAILOVER, false);
Logger.printMessage(getClass().getSimpleName(), "is Failover: "
+ isFailOver, Logger.DEBUG);
Boolean isNetworkChanged = false;
NetworkInfo otherNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
Logger.printMessage(getClass().getSimpleName(),
"Current Network Info : " + networkInfo, Logger.DEBUG);
Logger.printMessage(getClass().getSimpleName(),
"Other Network Info : " + otherNetworkInfo, Logger.DEBUG);
if (networkInfo != null && networkInfo.isConnected()) {
if (isFailOver) {
Logger.printMessage(getClass().getSimpleName(),
"Network is re-connected and available now",
Logger.DEBUG);
onReconnect();
return;
} else {
Logger.printMessage(getClass().getSimpleName(),
"Network is available", Logger.DEBUG);
onConnect();
return;
}
} else if (networkInfo != null
&& !networkInfo.isConnectedOrConnecting()) {
// do application-specific task(s) based on the current network
// state, such
// as enabling queuing of HTTP requests when currentNetworkInfo
// is connected etc.
if (otherNetworkInfo != null
&& otherNetworkInfo.isConnectedOrConnecting()) {
isNetworkChanged = true;
} else {
Logger.printMessage(getClass().getSimpleName(),
"No network is available", Logger.DEBUG);
onNoConnectivity();
return;
}
}
// No network is active OR no network is available
if (activNetworkInfo == null || isNoConnectivity) {
if (isNetworkChanged) {
Logger.printMessage(getClass().getSimpleName(),
"Change network connectivity", Logger.DEBUG);
onNetworkChange();
return;
} else {
Logger.printMessage(getClass().getSimpleName(),
"No network is available", Logger.DEBUG);
onNoConnectivity();
return;
}
}
}
}
Whats wrong with my request? Any ideas?
You can register the NetworkReceiver in onResume instead of onStart and check if it works
Make sure you added network permissions in your AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Register a broadcastreceiver in your manifest also:
<receiver
android:name=".NetworkReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Then the NetworkReceiver class:
public class NetworkReceiver extends BroadcastReceiver {
private static volatile boolean connected;
#Override
public void onReceive(final Context context, final Intent intent) {
Log.d("Network", "Network changed");
if (intent.getExtras() != null) {
update();
}
}
public static void update() {
ConnectivityManager connectivityManager = (ConnectivityManager) ApplicationLoader
.applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isConnected();
}
public static boolean isConnected() {
return connected;
}
}
Then if you want to check the network status call:
NetworkReceiver.update(); // Updates network status
if (NetworkReceiver.isConnected()) {
// do whatever you want.
}
Ive written some code in an app to check if the phone has a wifi connection, I can do this fine and it works but what I actually want to check for is when the phone is not connected to wifi but it doesn't seem to be working. I think I must have the syntax wrong somewhere. please see code below:
ConnectivityManager connManager = (ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE);
myWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!myWifi.isConnected()){
//do something
}
With the ACCESS_NETWORK_STATE permission in your manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Using the getActiveNetworkInfo() method, use this method:
private boolean notConnectedToWifi(){
final ConnectivityManager conMgr = (ConnectivityManager).getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected() && activeNetwork.getType() != ConnectivityManager.TYPE_WIFI)
return true;
else
return false;
}
All you have to do next is to call the method in your condition. Example
if(notConnectedToWifi){
// Oops! You're not connected to wifi!
}
Note that I check if activeNetwork is connected via activeNetwork.isConnected() so if the device is connected to a mobile network, the method notConnectedToWifi() will return false. It will also return false if it isn't connected to any network.
try this
/* Network check */
public static boolean haveNetworkConnection(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
if (haveNetworkConnection(youractivityname.this)) {
//do your work here ..
}
You should use BroadcastReciever for getting updates of wifi connectivity in your activity. Below is the sample code
public class MainActivity extends Activity {
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
Toast.makeText(MainActivity.this, "Is Wifi connected : "+wifi.isConnected(), Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initViews();
MainActivity.this.registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}
}
Also write <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> permission in AndroidManifest.xml file
With the help of ConnectivityManager, you will get the network info based on trace whether WIFI is connected or not.
Check below code (pass Activity context):
public boolean IsInternetConnected(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo nInfo = connectivity.getActiveNetworkInfo();
if (nInfo != null) {
//do your thing
if (nInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
}
}
return false;
}
return false;
}
hi im usuing simulator for testing application but when i run application, it still show gprs available any idea why?? in simulator there is no gprs then why its show gprs available?? what is ConnectivityManager.TYPE_MOBILE mean? is mean only gprs??
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
if (position == 0)
{
final ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if( mobile.isAvailable() ){
Toast.makeText(LoginScreen.this, " GPRS Connection Found "
, Toast.LENGTH_LONG).show();
}
else if( !mobile.isAvailable() ){
Toast.makeText(LoginScreen.this, "No GPRS
Connection Found " , Toast.LENGTH_LONG).show();
}
}
if (position == 1)
{
final ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if( wifi.isAvailable() ){
Toast.makeText(LoginScreen.this, " Wifi Found" ,
Toast.LENGTH_LONG).show();
}
else if( !wifi.isAvailable() ){
Toast.makeText(LoginScreen.this, "No Wifi found " ,
Toast.LENGTH_LONG).show();
}
}
if (position == 3)
{
final ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
BluetoothAdapter mBluetoothAdapter =
BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter.isEnabled()) {
Toast.makeText(LoginScreen.this, " BlueTooth Found" ,
Toast.LENGTH_LONG).show();
}else if( !mBluetoothAdapter.isEnabled() ){
Toast.makeText(LoginScreen.this, "No BlueTooth found "
, Toast.LENGTH_LONG).show();
}
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
The ConnectionManager doesn't check the type of with the provided type (TYPE_MOBILE). It only reports that a data connection exists regardless of the underlying protocol.
NetworkInfo.getSubTypeName() will have the subtype of the network.
Also there's this existing answer to a similar question.