I am using the following code to check the internet connection in my entire app.
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);
Toast.makeText(context, "net Connected", Toast.LENGTH_LONG)
.show();
}
else{
Log.i("NET", "not connecte" + isConnected);
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG)
.show();
}
}
}
The problem is when their is no internet connection/wi-fi signal, the toast message is displaying in other apps too.. how do I avoid that?
Thanks:)
Create an application class:
public class MyApplication extends Application {
private static MyApplication instance;
// Returns the application instance
public static MyApplication getInstance() {
if (instance == null)
instance = this;
return instance;
}
}
Add to manifest:
<application
android:name=".MyApplication"
... >
In your broadcast receiver:
Toast.makeText(MyApplication.getInstance().getApplicationContext(), "No Internet Connection", Toast.LENGTH_LONG)
.show();
Use this or getBaseContext() instead of contex .
You are using BroadcastReceiver receiver to check whether there is an internet connection. This will get executed whenever there is a change in network connectivity irrespective of the application. Since you are new, I'll explain it.
We can relate Broadcast receiver to a radio which listens for certain type of broadcasts and Broadcast is something which is send by the android system when ever an event occurs. So if the event is of the type of your broadcast receiver, you will get it.
So from your application if you just need to check for connection, you can simply create a method and call it.
public boolean isNetworkAvailable(Context context) {
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);
Toast.makeText(context, "net Connected", Toast.LENGTH_LONG)
.show();
}
else{
Log.i("NET", "not connecte" + isConnected);
Toast.makeText(context, "No Internet Connection", Toast.LENGTH_LONG)
.show();
}
return isConnected;
}
Call this method, whenever you need to check the connection.
OR
if you need to get notified of the above event changes as you require above, you can use the same broadcast receiver and instead of registering the broadcast receiver in Manifest file, register it from code of your application when it starts and unregister it when your application ends.
I am sorry to say none of the answers actually answers the original question "... the toast message is displaying in other apps too.. how do I avoid that?"
Toast is shown irrespective of which app is on the top. It is designed that way. So you can not 'avoid' that. You have to avoid using Tosat to avoid this behavior. The receiver acts in the background and shows a Toast. It does not bother which app is being shown currently to the user.
Please check this link also.
http://developer.android.com/guide/topics/ui/notifiers/toasts.html
Related
I am trying to detect network state change in my android app. I followed the answer in that question : Check INTENT internet connection
This works, but it takes time for broadcastreceiver to detect changes. When i turn wifi on or off, about 10 seconds later the onReceive() method is called. Why is that taking so much time? Can anyone help?
Thanks
Here is my code:
public class NetworkStateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("app", "Network connectivity change");
if (intent.getExtras() != 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");
Toast.makeText(context, "CONNECTED", Toast.LENGTH_LONG).show();
} else if (intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "DISCONNECTED", Toast.LENGTH_LONG).show();
Log.d("app", "There's no network connectivity");
}
}
}
}
and in my Manifest's application tag:
<receiver android:name="com.mypackage.NetworkStateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
I found the solution.
Instead of extending BroadcastReceiver class and creating NetworkStateChangeReceiver, i created a broadcastreceiver on my activity and registered it there. Now it works and onReceive() method is triggered immediately.
public static boolean isInternetAvailable(Context context) {
boolean isConnection = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null) {
for (int index = 0; index < info.length; index++) {
if (info[index].getState() == NetworkInfo.State.CONNECTED) {
isConnection = true;
break;
}
}
}
}
return isConnection;
}
I have similar code within my app to detect if there's a connection present, and prompt the user of connection state changes.
Within my application, it receives the connection change for disconnect within a second, however when you go to turn the WiFi on it takes around ~7 seconds before my app receives the change in connection state.
However I receive the state change exactly the same time Android makes the toast saying "Connected to Wi-Fi network [your network name]".
Chances are you'd be receiving the change simultaneously from when it connects to a network, and not from when you pushed the Wi-Fi toggle to turn it on.
Is there a particular reason you need that instant feedback from when the toggle is pressed?
I am noob in Android. I want to display device status at web dashboard whether device is offline/online. Is GCM helpful for this to do or something what should I use for this .
Or Should I call any Web API continuous to send the phone status from phone to server until phone is ON so that I can display here "Online" status of phone at web dashboard ??
Offline status when your device is OFF & Online status when your device is ON
Any idea ??
Step 1 -> Register for the Broadcast Receiver to check for device status offline/online.
Inside the onReceive() method of the Broadcast Receiver, check for network changes, if there is a change go to step 2.
Step 2 -> Get the device status and call the web api along with the POST parameter "device_status".
Use the below API to get status for Internet Connectivity.
public boolean testNetwork(Context context) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if ((connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connManager
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected())
|| (connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null &&
connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnected())) {
return true;
} else {
return false;
}
}
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean connectivity = CommonUtils.getInstance().testNetwork(
BaseActivity.this);
if (!connectivity) {
// write your code
} else {
//write your code
}
}
};
IntentFilter filter = new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION);
try {
registerReceiver(networkStateReceiver, filter);
} catch (Exception e) {
e.printStackTrace();
}
use this method :
You should not send ping to server.Server should send ping after some time interval to the device and device should reply. If device is not replying this means user is offline. Basically you need to create socket connection with server and exchange ping
same thing is implemented on openfire server
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
/*
* Toast.makeText(getActivity(), "No Internet connection!",
* Toast.LENGTH_LONG).show();
*/
return false;
}
return true;
}
and call it like
if (isOnline()) {
//code if online
} else {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
.create();
alertDialog.setTitle("Info");
alertDialog
.setMessage("Internet Not Available, Cross Check Your Internet Connectivity and Try Again!");
alertDialog.show();
}
Implement XMPP Protocol along with any Jabber server.
It gives you correct info because it was created to make the offline/ online system
for help use link below
https://xmpp.org/about/
This is my first time using broadcast-receivers, and i thought it would be a little more straight forward than this. I have a class looking like this:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = wifi != null && wifi.isConnectedOrConnecting() || mobile != null && mobile.isConnectedOrConnecting();
if (isConnected) {
Log.d("Network Available ", "YES" + getResultCode());
}else{
Log.d("Network Available ", "NO" + getResultCode());
}
}
}
and i've registered it in my application like this
mReceiver = new NetworkChangeReceiver();
registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
And this is working OK, when i shut off my wifi, i get "NO" in log.d.. But how do i get something to "happen"? I want a Return-value or something which i can work with, for example if isConnected is false, then restart activity or something.
I've googled for days trying to understand what they are and how they work... Please help!
Well, the method is of type void, so a return value is out of the question. And besides, the calling class would be BroadcastManager or LocalBroadcastManager, so you wouldn't have any access to a potential return value.
You could register custom listeners inside your BroadcastReceiver, but that would mean keeping unnecessary references.
What I would do in your situation is fire off another broadcast with a custom "action" String in the "NO" block:
else{
Log.d("Network Available ", "NO" + getResultCode());
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(YOUR_CUSTOM_ACTION_NAME));
}
Register a listener for that event wherever needed and handle the behavior there.
I am using eclipse with android sdk 3.2
I have some problems to make my broadcast receiver working when the connection is lost.
first I have checked the type of network to make sure I understand well :
ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
boolean is3g = manager.getNetworkInfo(
ConnectivityManager.TYPE_MOBILE)
.isConnectedOrConnecting();
boolean isWifi = manager.getNetworkInfo(
ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting();
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null)
Toast.makeText(getApplicationContext(), info.getTypeName(),
Toast.LENGTH_LONG).show();
else
Toast.makeText(getApplicationContext(), "Pas de connexion",
Toast.LENGTH_LONG).show();
if (!is3g)
Log.i("Network Listener", "DISCONNECTED");
else
Log.i("Network Listener", "CONNECTED");
==> this is a mobile network, I'm connected
Then I press F8 or I make :
telnet localhost 5554
gsm data off
to stop the connection
Here is my dynamic broadcast receiver in an activity :
public class ActivityA extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.query);
this.registerReceiver(this.networkStateReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
BroadcastReceiver networkStateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
//i have tried several things : State networkState = networkInfo.getState();
// if (networkState.compareTo(State.DISCONNECTED) == 0) ...
if (networkInfo != null && networkInfo.isConnected()) {
Toast.makeText(getApplicationContext(), "CONNECTED",
Toast.LENGTH_LONG).show();
Log.i("Network Listener", "Connected");
} else {
Toast.makeText(getApplicationContext(), "DISCONNECTED",
Toast.LENGTH_LONG).show();
Log.i("Network Listener", "Network Type Changed");
Intent offline = new Intent(AccountInfoActivity.this,
OfflineWorkService.class);
startService(offline);
}
};
My manifest :
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
The problem is : when the activityA is launched, my broadcast receive something and it displays "Connected"(Log) and my toast. When I turn off the connection manually, nothing happend. My service is not started, log message are not displayed, only toast messages work ...
And even better, when I turn on the connection again (by pressing F8), I test again the type of connection, Toast messages are shown but this time Log messages don't work.
Problems happend when I press F8. Anyway, I think I miss something with broadcast receivers, it's not totally clear.
Please help me.
This is what I would like to do :
=> IF WiFi is enabled AND active, launch an intent (in fact it's a WebView that gets its content=>the instructions of my app on the web)
=> IF NOT, then I would launch another intent so that I don't show a WebView with "Web page not available ... The Web page at http://www.mywebsite.com might be temporarily down or it may have moved ..."
I tought initially to use
if(wifi.isWifiEnabled())
but that does not say if the Wifi connection is ACTIVE or not. It says only that the user has turned the switch on. The device may or may not be connected... Is this correct ?
Then I tried to use :
if (wifi.getConnectionInfo().getSSID()!= null)
but I noticed that it returns a string even if the connection has been lost or has been disabled ... ?
How should I do then ?
wifi = (WifiManager)getSystemService(Context.WIFI_SERVICE);
Intent intent_instructions;
if (wifi.getConnectionInfo().getSSID()!= null){
Log.i("Hub", "WiFi is enabled AND active !");
Log.i("Hub", "SSID = "+wifi.getConnectionInfo().getSSID());
intent_instructions = new Intent(this, Instructions.class);
}else{
Log.i("Hub", "NO WiFi");
intent_instructions = new Intent(this, Instructions_No_WiFi.class);
}
this.startActivity(intent_instructions);
Is there a more general way to test if the device has the connectivity to the internet just before launching an intent ? be it through Wifi, 3G, etc ...
Thanks in advance for your help.
You can use the following code to check for connectivity:
private static boolean isConnected(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo =
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
}
return networkInfo == null ? false : networkInfo.isConnected();
}
Please make sure that you've registered the android.net.conn.CONNECTIVITY_CHANGE intent in your Manifest, or else, you'll never receive a notification that you're online.
I've been struggling with this issue for the last couple of days and I just now realized that I needed to register CONNECTIVITY_CHANGE and not only WIFI_STATE_CHANGED.
Try android.net.ConnectivityManager.getActiveNetworkInfo(): if it returns null you have no connection; if it returns a NetworkInfo object, you can check the connection's state with NetworkInfo.getState(), and if it's NetworkInfo.State.CONNECTED then you're connected, else you're not.
You can do it as follows:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action)){
Log.d("WIFI", "WIFI has changed");
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, -1);
Log.d("WIFI", "WIFI State = " + wifiState);
setCurrentWifiState(wifiState);
}
You will get 0,1,2,3 depending on which state the Wifi is in, so for example 2 is connecting, you can check the rest in the documents
In your BroadcastReceiver class:
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)){
boolean connected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
if (connected){
// start your service here
}
}
}
And in your AndroidManifest.xml make sure you register for the android.net.wifi.supplicant.CONNECTION_CHANGE broadcast intent.
<intent-filter >
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
</intent-filter>
isConnected() doesnt work fully ok, research something else
final ConnectivityManager connMgr = (ConnectivityManager)
this.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if( wifi.isAvailable() && wifi.getDetailedState() == DetailedState.CONNECTED){
Toast.makeText(this, "Wifi" , Toast.LENGTH_LONG).show();
}
else if( mobile.isAvailable() && mobile.getDetailedState() == DetailedState.CONNECTED ){
Toast.makeText(this, "Mobile 3G " , Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "No Network " , Toast.LENGTH_LONG).show();
}
this code check if you are with wifi or 3g or nothing , in the case of wifi on but not connected to a net or 3g have signal problem it detect this details, with DetailedStates