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();
}
}
};
Try like this:
if(currentNetworkInfo != null &&
currentNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
currentNetworkInfo.getState() == NetworkInfo.State.DISCONNECTING) {
showNotification();
}
There are also other possible states(such as NetworkInfo.State.DISCONNECTED, maybe that is what you want), you can find the full list here:
http://developer.android.com/reference/android/net/NetworkInfo.State.html
Related
I am trying to get the Lat/Long for the device when using 4G/LTE. The code below works great when using WiFi but the onLocationChanged method doesn't get called at all when using 4G/LTE. Any idea why?
I only have a limited window to get the location coordinates as they need to be appended to an audit log at the beginning.
Does LTE/4G usually take much longer than WiFi to pinpoint the lat/long?
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (networkType.equals("WiFi")) {
lp = LocationManager.NETWORK_PROVIDER;
}
else {
lp = LocationManager.GPS_PROVIDER;
}
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
gpsTestLocation = locationStringFromLocation(location);
System.out.println("mcsoutput location: " + gpsTestLocation);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
// Register the listener with the Location Manager to receive location updates
lm.requestLocationUpdates(lp, 0, 0, locationListener);
Network Type is figured out by:
private String checkNetworkState() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
// NetworkInfo mEthernet = connManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
NetworkInfo m3G = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
TelephonyManager telephonyService = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mWifi!=null) isOnWifi = mWifi.isConnected();
if (m3G!=null) is3G = m3G.isConnected();
if(isOnWifi == true) {
return "WiFi";
}
else {
int cellType = telephonyService.getNetworkType();
return isConnectionFast(cellType);
}
}
You're using NETWORK_PROVIDER when on wifi and GPS when off. Odds are you aren't getting a GPS synch. Its actually very hard to do when indoors. Are you getting a flashing GPS symbol in your notification bar? If so, you aren't getting a full GPS synch and thus onLocationChanged won't be called.
When on wifi using NETWORK_PROVIDER you'll get an almost instant location because NETWORK_PROVIDER needs no satellites and is almost always available, it just isn't nearly as accurate.
i'm trying to use in my project a broadcast receiver which listens to battery status of charging/not charging and throw a toast in each of the options .
every time i change the charger status in the app ,the app crash.
(if i start the app with the charger connected it's show me the right toast
but when i uncharge the phone the app crashes)
here is the code
thanks in advance
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = this.registerReceiver(null, ifilter);
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging==true){
Toast.makeText(this, "Charging", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(this, "Charger not connected", Toast.LENGTH_SHORT).show();
UPDATE
i'm having an hard time to understand what i suppose to do.
i'm pretty new so be patient with me :)
here is the code i made
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBatteryState(null);
public void checkBatteryState(View sender) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = registerReceiver(null, filter);
int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
String strState;
switch (chargeState) {
case BatteryManager.BATTERY_STATUS_CHARGING:
case BatteryManager.BATTERY_STATUS_FULL:
strState = "charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
break;
default:
strState = "not charging";
Toast.makeText(this, strState, Toast.LENGTH_LONG).show();
}
}
}
http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html
is this what you're using?
Maybe you haven't ensured your Intent is sticky.
My advice would be not to use a registerreceiver with a null argument.
Try this method for creating a broadcastreceiver:
How to send data to another app which is not started
put your Toasts in the onReceive() function.
The code is not actually registering a receiver, just getting a sticky broadcast. If the broadcast has never been sent the this will return null which will cause a NPE in the remaining code.
I have a mUsbReceiver (BroadcastReceiver) and CameraActivity. The receiver setContentView(R.layout.main) from CameraActivity via an Intent. Then CamearActivity updates its View with this value. Notice that the setContentView is in the Broadcast receiver class and not in the CameraActivity Class.
public class CameraActivity extends Activity {
private static final String TAG = "openXC::Activity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
usbConnection();
}
public void usbConnection() {
UsbManager mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
PendingIntent mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), PendingIntent.FLAG_CANCEL_CURRENT);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
String txt = "default";
HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();
Log.i(TAG, "Device List: " + deviceList);
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
UsbDevice device = deviceIterator.next();
Log.i(TAG, "Device List: " + deviceList);
mUsbManager.requestPermission(device, mPermissionIntent);
}
private static final String ACTION_USB_PERMISSION ="com.ford.openxc.webcam.USB_PERMISSION";
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if(device != null){
Log.d(TAG, "Displayed Comten View " + device);
setContentView(R.layout.main);
}
}
else {
Log.d(TAG, "permission denied for device " + device);
}
}
}
}
};
}
This works fine sometimes but sometimes throws the following error
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/openXC::Activity( 5609): Device List: {/dev/bus/usb/001/002=UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421a1f50]}
I/Adreno200-EGLSUB( 5609): <ConfigWindowMatch:2087>: Format RGBA_8888.
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
E/ ( 5609): <s3dReadConfigFile:75>: Can't open file for reading
D/openXC::Activity( 5609): Displayed Comten View UsbDevice[mName=/dev/bus/usb/001/002,mVendorId=1133,mProductId=2085,mClass=239,mSubclass=2,mProtocol=1,mInterfaces=[Landroid.os.Parcelable;#421d3ed0]
D/WebcamPreview( 5609): WebcamPreview constructed
Technically, you can call setContentView any time you are executing on the event thread.
Otherwise you need to use a Handler to call it.
Also, here are some usefull links that might help you:
link1
link 2
link 3
I dont have much exp on USB sort of thing but since u said its saying cannot readfile.. i believe dat the error may be in the usb so for the debugging purpose i would suggest to move the setContentView(int) from if conditions to the onRecieve directly so dat whenever the onReceive is called ur contenview will change , this will help to ensure that the error is not with setcontentview... After dat u can see without setcontentview in the usb and now if the error is coming then surely the error is in the usb and not in the setContentView ....
Hope it works :)
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 an app that requires a permanent internet connection. If no internet connection is present I want the user to be logged out of the app (taken to the login screen).
I have a network receiver class that detects network connectivity. I want this class to either terminate the activity on top of the stack OR to start a new login activity and delete the entire history stack.
The problem is that I can't finish the foreground activity from inside the my receiver class, and there is no way of knowing which activity the user is in when there is a network fail. And if I'm starting a new login activity from this class, when the user presses "back" he is taken back to the app(if he reconnects to a network), but the app is not logged in and crashes.
Tried using myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK || FLAG_ACTIVITY_CLEAR_TOP); when starting a new login activity from my NetworkStateReceiver class. But it doesn't work, to my understanding this creates a new task in which the only activity is the one I started (login), but the old task with all the other activities remain intact.
So I need :
-either a way to finish a foreground activity from a class
-or a way to start a new activity from a class and emptying the activity stack
Here's the receiver code for what it's worth:
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) {
Login.apiKey = 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) && !Login.loginActive) {
Log.d("app","There's no network connectivity");
Toast.makeText(context, "No internet connection. Logging out", Toast.LENGTH_LONG).show();
//logout
Receiver.engine(context).halt();
Receiver.mSipdroidEngine = null;
Receiver.reRegister(0);
new Thread(ChatList.runnable).interrupt();
ChatList.buddyList.clear();
Login.apiKey = null;
Log.i("Logout", "Logged out!");
Login.loggedOut = true;
Intent myIntent = new Intent(context, Login.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// myIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
context.startActivity(myIntent);
}
}
}
SOLUTION:
Passed reference from all activities to receiver
//random user_activity
#Override
protected void onPause() {
super.onPause();
NetworkStateReceiver.curActivity = null;
}
#Override
protected void onResume() {
super.onResume();
NetworkStateReceiver.curActivity = user_activity.this; //edited : getParent() doesn't always work
}
and in network receiver in onReceive() :
if(curActivity != null)
{
curActivity.finish();
}
One way is to pass the receiver a reference to the current activity(say, in onResume?). Make sure to null it in onPause, though, or you're looking at some ugly memory leaks. Then, in onReceive, you can curActivity.finish()(or do nothing if it's null) before you start the login activity.