I am working over a project. In this, I am running a background service, in this their is connection between device and server. I want when device is connected to internet the service gets started and connection gets builtup between server and device and when internet disconnected the connection between server and device also gets disconnected
For this I have to send request to disconnect the connection, but that also requires internet connection that is currently not available.
So I want to disconnect the connection between server and device before internet gets disconnected. For this I need the stage i.e prior to internet disconnected that may be like Going to disconnect internet.
The code I tried is not sufficient for this work
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
try{
if(netInfo.isConnected() && netInfo != null){
System.out.println("Connected to internet");
context.startService(new Intent(context,MessageService.class));
}
}catch(NullPointerException e){
System.out.println("Not Connected to internet");
context.stopService(new Intent(context,MessageService.class));
}
}
}
Can anyone tell any soln for this?
Related
I'm currently working on an application that needs to know whether the phone has internet connection.
Using Connectivity Manager the app is able to generate an event when there is or there is no network connection. Problem is, I need to be connected to a WI-FI local hotspot for my app, and this WI-FI does not offer internet access. to summarise, ConnectivityManager tells me there is internet connection because i'm connected to this wi-fi, but this wi-fi does not offer a real connection.
Here is the code :
public void onReceive(Context context, Intent intent) {
if(intent == null || intent.getExtras() == null)
return;
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED) {
connected = true;
} else if(intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
connected = false;
}
notifyStateToAll();
}
Is there a way to specify ConnectivityManager that one special Wi-Fi does not offer internet access?
I'm writing an Android application which should react if the phone connects or disconnects to a WIFI network. I registered a BroadcastReceiver for this and it works great. Now with this code I'm able to get the current WIFI ID if the phone is connected to a WIFI:
WifiManager mainWifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo currentWifi = mainWifi.getConnectionInfo();
int id = currentWifi.getNetworkId();
But what if the WIFI disconnects and I want to get the WIFI ID of the last connected WIFI? My problem is that all this is in an BroadcastReceiver. This is allways new created if a new Broadcast comes in so I can not really save some data there. Is there a method or something else with which I can get the last connected WIFI ID?
Forgive me if I'm missing something. You could getSharedPreferences to have a context to access from Broadcast receiver.
This BroadcastReceiver intercepts the android.net.ConnectivityManager.CONNECTIVITY_ACTION, which indicates a connection change. It checks whether the type is TYPE_WIFI. If it is, it checks whether Wi-Fi is connected and sets the wifiConnected flag in the main activity accordingly.
public class NetworkReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connMgr =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
// Checks the user prefs and the network connection. Based on the result, decides
// whether
// to refresh the display or keep the current display.
// If the userpref is Wi-Fi only, checks to see if the device has a Wi-Fi connection.
if (WIFI.equals(sPref) && networkInfo != null
&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// If device has its Wi-Fi connection, sets refreshDisplay
// to true. This causes the display to be refreshed when the user
// returns to the app.
You can find here the sample app.
My android application is based on network connection i.e WIFI/Mobile Network. It works fine when my mobile is connected to internet but when internet connection disconnected it stops working (obesely) and it still stop working after my mobile again connected to internet.
I wish to (re)start my application automatically whenever internet connection is (re)established.
You can check the network state using broadcast receiver. Whenever the network is available, you can start your application.
First, create a background service and start your service when the device boots up. Now, in this service, register a broadcast receiver and monitor the network state. If the network is available, you can start your application; and if unavailable, you can close it.
Please refer to the code below for broadcast receiver.
public class BroadCastSampleActivity extends Activity
{
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
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())
{
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
}
}
};
}
I think you must need to checking continue for network connections, that means you need to check for internet connection in background tasks. Android Services is better option for that, create one Service and start it when your app starts, inside that just do one code and that is for checking Internet Connectivity, when it lost, do some task and when it found you can do whatever you want. So I suggest you to use services and get your task done.
Here are some links to refer.
http://www.tutorialspoint.com/android/android_services.htm
http://www.vogella.com/tutorials/AndroidServices/article.html
I think you should create a spread thread or service in background for checking network connection after some interval . use following code in thread or service whatever you want to create .
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
How to start a service when internet is enabled?
I need to start the service when the internet is active state. I have application that communicate with the web application when internet is present,even offline the mobile need a communication,it will known by server at the time of internet comes active.
The answer is in your question. Just create a BroadcastReceiver to listen network state, when internet is okay, start server as usual.
public class NetworkBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
ConnectivityManager mgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = mgr.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
isNetworkConnected = true;
//do your work here
}
}
}}
When I press a button on my app to open an image it shows a progress bar of the image being downloaded and then it opens. If there is no wifi connection it displays an error message saying "No wifi". I have used the code below to check for a wifi connection:
ConnectivityManager cm =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork.isConnectedOrConnecting();
boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
I want to implement an error message that is displayed when the connection is lost. So if you click on the image and while its downloading you turn off the wifi then it displays a message saying "wifi disconnected".
Is this possible? Whether a connection is lost or there is no wifi all you are doing is checking if there is a connection available which is the same thing
You need to use a BroadcastReceiver that will be triggered when the connectivity status for Wi-Fi has changed.
Set following things before registering BroadcastReceiver:
private class ConnectionChangeReceiver extends BroadcastReceiver {
public void onReceive( Context context, Intent intent ) {
Log.d(tag, "Inside Broadcast Reciever");
CheckWifiStatus();
}
}
private void RegisterWifiWatcher()
{
if(wifiWatcher == null)
wifiWatcher = new ConnectionChangeReceiver();
final IntentFilter intentFilter= new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
registerReceiver(wifiWatcher, intentFilter);
}
WIFI_STATE_CHANGED :
Broadcast intent action indicating that Wi-Fi has been enabled, disabled, enabling, disabling, or unknown.
Permissions in Manifest :
<user-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<user-permission android:name="android.permission.ACCESS_WIFI_STATE" />
NOTE:
The broadcast intents that we receive for the different WiFi states have extras along with them that you can access to determine the different states of the WiFi connection.
Sure its possible. Adding to the above answer another option:
You can check with your code if wifi is available first.
Then start downloading the image and if you catch an exception during that time, toast the message wi-fi disconnected.