I need my application to give a notification whenever a specific WiFi goes offline.
I got it to give a notification every time the WiFi connection disconnects. But I need it to only give a notification when a specific WiFi network disconnects. Is my code suitable for this? I read something about class wifiinfo, is this the solution?
My question is, how do I alter the code to only give a notification when a specific WiFi goes offline? Any help in the right direction would be nice! Some examples would be even more awesome.
Thanks in advance!
(Eventually I need a button and when you press this the specific wifi your on atm will become that specific wifi when you disconnect from it you get a notification. If that makes sense.)
The code:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_hoofdmenu);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(!isNetworkConnectionAvailable(context)){
showNotification();
}
}
};
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;
}
To detect SSID changes, listen for WifiManager.NETWORK_STATE_CHANGED_ACTION, grab the SSID from the intent extra WifiManager.EXTRA_BSSID.
See: Execute code when wifi SSID changes
Related
I am having a problem related to Network Service Discovery.
When I start the app with wifi connected, NSD Works Totally fine discovering the service and smoothly resolving them.
But the problem arises when we connect wifi, after disabling wifi or switching the wifi from airplane mode.
It just gets stuck on DiscoveryStarted and never proceeds from there, although it establishes the connection to the wifi router after turning off airplane mode.
In code I have also ensured that the discovery will only start when the wifi connection is ensured but, no luck.
Right now I have to kill the app in order for NSD to work properly.
I am using NSD Helper from Google Gist:
https://android.googlesource.com/platform/development/+/master/samples/training/NsdChat/src/com/example/android/nsdchat/NsdHelper.java
NsdHelper helper;
BroadcastReceiver wifiReciever = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
//do stuff
helper.stopDiscovery();
helper = new NsdHelper(context);
helper.discoverServices();
} else {
// wifi connection was lost
helper.stopDiscovery();
}
}
}
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//startDiscovery();
// helper = new NsdHelper(this);
// helper.discoverServices();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(wifiReciever, intentFilter);
Toast.makeText(this,"Service Started",Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// if(service!= null)
// {
// service.stop();
// helper.stopDiscovery();
// }
unregisterReceiver(wifiReciever);
//
Toast.makeText(this,"Service destroyed",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
I implemented the code to check wifi state connected or not. I made a text view
TextView WifiTv = (TextView) findViewById(R.id.wifistate);
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiCheck = connectionManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
It works but it does not update dynamically and therefore if I turn off wifi I have to refresh the activity for the textview to change (not data binded). How can I make the textview update without refresh please? Thx
EDIT: I have this code in a seperate class which works well with a toast. All I want to do is display in textview instead. How can I connect the textview variable to this class which does not have xml please?
public void onReceive(Context context, Intent intent) {
NetworkInfo info =
intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info != null && info.isConnected()) {
// Do your work.
// e.g. To check the Network Name or other info:
WifiManager wifiManager = (WifiManager)
context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Toast.makeText(context, "Connected to: " + ssid,
Toast.LENGTH_SHORT).show();
}
You required BroadcastReceiver and wifimanager. BroadcastReceiver which start when app launches to receive the the implicit intent every time. wifimanager to to check the status.
did you try to add a onResume function to check again each time you resume yout activity?
Don't know your app but maybe this,
#Override
protected void onResume() {
super.onResume();
if (wifiCheck.isConnected()) {
// Do whatever here
WifiTv.setText("WiFi is Connected");
WifiTv.notify();
} else {
WifiTv.setText("WiFi is not Connected");
}
}
If your others variables are not global to Activity, create them again within the onResume
I would like to know how can I check when mobile data is connected using BroadcastReceiver.
Here's what I have so far:
private BroadcastReceiver MobileDataStateChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(TelephonyManager.EXTRA_STATE,
TelephonyManager.DATA_DISCONNECTED);
if (state == TelephonyManager.DATA_CONNECTED) {
mobileStatus.setText("Connected");
} else if (state == TelephonyManager.DATA_DISCONNECTED) {
mobileStatus.setText("Disconnected");
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.status_page);
mobileStatus = (TextView) this.findViewById(R.id.textView4);
registerReceiver(MobileDataStateChangedReceiver, new IntentFilter(
TelephonyManager.ACTION_PHONE_STATE_CHANGED));
}
What am I doing wrong in here?
I used the same concept on Wi-Fi checking and it worked great?
I am using the permissions of:
<uses-permission android:name="android.permission.INTERNET"/>
The TelephonyManager.ACTION_PHONE_STATE_CHANGED does not seem to work because as I could read in TelephonyManager class description it only fires with calls, but not with networks or mobile data.
Instead of this, I suggest you try setting a listener. It would be something like this:
1) Get the service with TelephonyManager tm = (TelephonyManager)Context.getSystemService(Context.TELEPHONY_SERVICE)
2) Set a listener with tm.listen(myCustomPhoneStateListener, PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
3) Once you have the listener you will be able to send custom intents to your BroadcastReceiver, if you still want to do that.
This question already has answers here:
Check INTENT internet connection
(13 answers)
Closed 3 months ago.
I am working on an Android app that will continuously remain connected to Internet. If Internet is dow, it should give an appropriate message to the User.
Is there any thing like Internet Listener? Or how to implement this event that whenever Internet connection is not available it should give alert.
The code from Chirag Raval above certainly works. The trouble is that the listener will get invoked even when the application is not running in foreground.
IMHO, the better approach is to register / unregister the receiver in the onResume() / onPause() methods of all your application activities. This code should do it:
private final NetworkStateReceiver stateReceiver = new NetworkStateReceiver();
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(stateReceiver, filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(stateReceiver);
}
Obviously, remove the registration from AndroidManifest.xml file.
Using this solution, the receiver will be called also when switching between activities of your application (assuming you are closing them). In such a case, use a static flag (being shared between all your activities) like in the example below (called online):
public class NetworkStateReceiver extends BroadcastReceiver {
private static boolean online = true; // we expect the app being online when starting
public static final String TAG = NetworkStateReceiver.class.getSimpleName();
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Network connectivity change");
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if (ni == null || ni.getState() != NetworkInfo.State.CONNECTED) {
Log.d(TAG,"There's no network connectivity");
if (online) // don't show the message if already offline
Toast.makeText(context, R.string.noInternet, Toast.LENGTH_SHORT).show();
online = false;
} else {
Log.d(TAG,"Network "+ni.getTypeName()+" connected");
if (!online) // don't show the message if already online
Toast.makeText(context, R.string.backOnline, Toast.LENGTH_SHORT).show();
online = true;
}
}
}
If starting your app when being offline, the Toast message will appear; otherwise it appears only when losing / re-establishing the connection .
I have an Activity which looks up data from the web in its onCreate method. The Activity is activated by the user hitting a notification. So it is a common problem that the user will quickly turn on their phone, unlock it, slide open notifications, tap the notification, and the Activity will activate before the phone is done connecting to internet.
I do have a friendly AlertDialog that pops up informing the user that the data couldn't be received and to try again when the network is connected; but is there a way for the Activity to actively tell the phone to connect and detect that a connection is being made and then wait for the connection to establish, and then load its data successfully?
Usually, you would do something like this:
#Override
public void onResume(){
super.onResume();
// first, check connectivity
if ( isOnline ){
// do things if it there's network connection
}else{
// as it seems there's no Internet connection
// ask the user to activate it
new AlertDialog.Builder(YourActivity.this)
.setTitle("Connection failed")
.setMessage("This application requires network access. Please, enable " +
"mobile network or Wi-Fi.")
.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// THIS IS WHAT YOU ARE DOING, Jul
YourActivity.this.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
YourActivity.this.finish();
}
})
.show();
}
}
The idea is ask the user to go and configure a network connection. Then, if the user does want to configure it, you will call the Settings.ACTION_WIRELESS_SETTINGS intent.
Also, notice the isOnline variable, which is a boolean that tells whether there's a network connection or not. In order to set that variable you can use an external simple class like this:
public class CheckConnectivity {
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if( cm == null )
return false;
NetworkInfo info = cm.getActiveNetworkInfo();
if( info == null )
return false;
return info.isConnectedOrConnecting();
}
}
Also, you will have to add this permission to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
From this last statement by Cristian
'return
info.isConnectedOrConnecting();' It seems you can do whatever you want to do with the activity based on the boolean value returned by the method.
Since what you after is a positive return value you can use it's variable to callback your activity's next action