I have written the following code for detecting the network status from within the BroadcastReceiver. I start a service when the network is available and stop the service when the network is not available.
I have the following class level variable.
private boolean IsNetworkAlreadyConnected = false;
Within onCreate method of the main class I start the service if the internet is available.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (InternetConnectivity.isConnected(MainActivity.this)) {
IsNetworkAlreadyConnected = true;
Intent timerIntent = new Intent(getBaseContext(), InActivityTimer.class);
startService(timerIntent);
}
}
and below is the code for my BroadcastReceiver in the same class,
public class mConnectivityCheckReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
try {
boolean networkAvailable = InternetConnectivity.isConnected(context);
if (networkAvailable) {
if (!IsNetworkAlreadyConnected) {
Intent timerIntent = new Intent(getBaseContext(), InActivityTimer.class);
startService(timerIntent);
IsNetworkAlreadyConnected = true;
}
else {
Log.d("KC_HomeActivity", "Network was already connected. No need to start service again.");
}
}
else {
Log.d("KC_HomeActivity", "Network Disconnected. Service Stopped.");
IsNetworkAlreadyConnected = false;
Intent timerIntent = new Intent(getBaseContext(), InActivityTimer.class);
stopService(timerIntent);
}
}
catch (Exception e) {
}
}
}
};
When both Mobile data and Wifi are turned on then the service is started from onCreate method and it is not started again in the BroadcastReceiver but when I turn off the Wifi the Android changes the network mode to Mobile Data but for few seconds there is no internet connectivity and the service is stopped and then started again. I don't want to do this. If there is no connectivity only then the service should be stopped. If the network is shifting from Wifi to Mobile Data then the service should not be stopped.
Note: To check the internet connectivity I am using,
NetworkInfo info = InternetConnectivity.getNetworkInfo(context);
return (info != null && info.isConnectedOrConnecting());
Network connections aren't that precise. You should make it relax a bit, or you'll pull your hair out.
I would implement a smoothing function from the broadcasts. When you get a connectivity change notification, set a timeout for like 15 seconds. At that time, check your status and either start, stop, or do nothing. If another broadcast comes in, clear the first and reset for another 15 seconds. That will give the device time to reconnect.
Related
I have an activity for upload from which I am calling Intent service. In there I am handling the API request call.
I want an activity to know whether the service is running or not, to show an uploading tag.
I tried following to determine if the service is running:
public void startUploadServiceTask() {
if (Util.isNetworkAvailable(mContext)) {
if (!isMyServiceRunning(UploadDriveService.class)) {
startService(new Intent(mContext,
UploadService.class));
}
} else {
Toast.makeText(mContext,
"Service is already running.", Toast.LENGTH_SHORT)
.show();
}
} else {
Toast.makeText(mContext,
getString(R.string.please_check_internet_connection),
Toast.LENGTH_SHORT).show();
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
Log.e("ALL SERVICE", service.service.getClassName().toString());
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
But in Activity Manager Running Service Info, I am not getting the class of intent service that I am running, so this always stands false.
I have used Broadcast for API calls response.
I have even checked this code.
if(startService(someIntent) != null) {
Toast.makeText(getBaseContext(), "Service is already running", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "There is no service running, starting service..", Toast.LENGTH_SHORT).show();
}
But in this code, on checking the service it also starts the service again, so service is called twice.
Please help me out with this.
IntentService needs to implement onHandleIntent() This method is invoked on the worker thread with a request to process Intent request and IntentService will be "alive" as long as it is processing a intent request (am not considering low memory and other corener cases here, but just thinking in terms of logic),
And When all requests have been handled, the IntentService stops itself, (and hence you should not call stopSelf() explicitly)
With this theory in place, You may try below logic: Declare a class variable inside your IntentService class.
public static boolean isIntentServiceRunning = false;
#Override
protected void onHandleIntent(Intent workIntent) {
if(!isIntentServiceRunning) {
isIntentServiceRunning = true;
}
//Your other code here for processing request
}
And in onDestroy() of IntentService class if you may choose, set isIntentServiceRunning = false;
And use isIntentServiceRunning to check if IntentService is Running!
In your code you are trying to get the status of service from Activity. The correct way is that status should be given by the service.
There are several possibilities for an activity to communicate with a service and vice versa. As you are using Broadcast receiver so you can broadcast a message in onHandleIntent() method when the service started.
and then when your task completes or in case of any error, again you can call the broadcast receiver for service finished event.
here is a link for a nice tutorial.
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;
I've got an IntentService which should perform some tasks after WiFi has been turned on.
I'm using a BroadcastReceiver on WifiManager.WIFI_STATE_CHANGED_ACTION to listen for WiFi changes.
The problem:
When I turn on WiFi via wifiManager.setWifiEnabled(true) the BroadcastReceiver only receives the states WifiManager.WIFI_STATE_DISABLED and WifiManager.WIFI_STATE_ENABLING. Then the IntentService is destroyed before the actual WifiManager.WIFI_STATE_ENABLED state can be received.
If I put Thread.sleep(2000) at the end of onHandleIntent() it works, but there must be a better solution?
Questions:
Why is the state WifiManager.WIFI_STATE_DISABLED broadcasted at all when I'm calling wifiManager.setWifiEnabled(true)?
How can I make the onHandleIntent() method wait until the state WifiManager.WIFI_STATE_ENABLED has been retrieved?
Code:
public class BackupService extends IntentService {
private BroadcastReceiver mWifiStateChangedReceiver;
public BackupService() {
super("BackupService");
}
#Override
protected void onHandleIntent(Intent intent) {
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
mWifiStateChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(
WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
// PERFORM TASK...
}
}
};
registerReceiver(mWifiStateChangedReceiver, new IntentFilter(
WifiManager.WIFI_STATE_CHANGED_ACTION));
wifiManager.setWifiEnabled(true);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mWifiStateChangedReceiver != null) {
unregisterReceiver(mWifiStateChangedReceiver);
}
}
}
How can I make the onHandleIntent() method wait until the state WifiManager.WIFI_STATE_ENABLED has been retrieved?
Ideally, you don't, as WiFi may not be available, and so you may never receive such a broadcast.
Instead:
Move your BroadcastReceiver to be one registered in the manifest, initially disabled
If the IntentService determines that it needs to wait for WiFi, have it enable the existing BroadcastReceiver via PackageManager and setComponentEnabledSetting(), then return out of onHandleIntent()
The BroadcastReceiver would use startService() to send a command to be processed by your IntentService once WiFi is ready, at which point it can then disable itself via PackageManager and setComponentEnabledSetting()
I have a service that runs upon boot completion. This service requires internet connectivity. What's the best practice for waiting for the device to connect to the internet? Mobile of wifi doesn't really matter.
My current solution involves a while loop that just checks ConnectivityManager until one of the networks becomes available, but this feels vulgar.
Is there a better way to do this?
but this feels vulgar
Indeed :D
Your receiver wakes your wakeful intent service (probably a simple intent service would do, as the phone does not sleep while booting AFAIK)
service registers a receiver for connectivity
service waits on a CountDownLatch
the receiver wakes the service up when the wifi is connected
Skeleton code : https://stackoverflow.com/a/19968708/281545 - your case is simpler as you do not have to wake the wifi, hold wifi locks etc. Otherwise (including the case this takes long and radios/CPU sleep - in which case a simple intent service won't do) between 2 and 3 you would need to :
2a. service acquires a wifi lock
2b. service calls reconnect(), reassociate() and whatever is needed (this may be device specific)
You could use a BroadcastReceiver:
private class ConnectionMonitor extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION))
return;
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
NetworkInfo aNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (!noConnectivity) {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// start your service stuff here
}
} else {
if ((aNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE)
|| (aNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI)) {
// stop your service stuff here
}
}
}
}
Then, you instantiate somewhere in your code:
ConnectionMonitor connectionMonitor = new ConnectionMonitor();
registerReceiver(connectionMonitor, intentFilter);
Note: this code comes from Detect 3G or Wifi Network restoration
I have an app in which I'm trying to detect WHEN the Internet connection appears and when it disappears.
At the moment, when it appears, I'm starting a new thread (different from the UI) which connects my app to a remote server.
For that I'm hardly trying to implement a broadcast receiver which LISTENS for connectivity, but I'm having problems in understanding the concept.
In my onCreate() I have somethig like:
onCreate()
{
cThread = new Thread(new ClientThread(syncToken));
cThread.start();
}
When there is connection to the Internet I'm sending data through the socket, when there is not I'm storing the data in a database. And when the Internet appears I'm restarting my thread to reconnect and send the old data (which hasn't been sent because of network crashing) and the new one.
Let's say I would implement something like this:
DoRefreshBroadcastReceiver refreshBroadcastReceiver;
...
onResume() {
// register the refreshing complete broadcast receiver
IntentFilter intentFilter = new IntentFilter(DO_REFRESH);
refreshBroadcastReceiver = new doRefreshBroadcastReceiver();
registerReceiver(refreshBroadcastReceiver, intentFilter);
}
public class DoRefreshBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// call method to run fetch code...
}
}
Does this mean that when the Internet connection is detected my onReceive() gets called? And I could start my thread there?
What is the concept of using an intent? Because I really don't get it. How to use it, and what its purpose?
THE IDEA: I don't really know how to use this intent in this case or how to use it in my app!
Would this thing detect the connection to the Internet even when I'm not in this activity?
EDIT:
Here is how my onReceive looks like:
onCreate()
{
cThread = new Thread(new ClientThread(syncToken));
// cThread.start();
connIntentFilter = new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE");
connListener = new MyConnectivityListener();
}
public void onReceive(Context context, Intent intent)
{
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (mNetworkInfo != null && mNetworkInfo.isConnected())
{
/*
* if(mNetworkInfo.getType()==ConnectivityManager.TYPE_WIFI);
*
*
* else
*/
cThread.start();
}
else {
System.out.println("There is no internet connection!");
try {
cThread.stop();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
mNetworkInfo != null && mNetworkInfo.isConnected()
Does this mean it's connected or should I verify for a certain type of connection on the emulator?
*I think that I should start my thread directly in onReceive(). As soon as my app starts it detects the Internet connection and BroadcastReceiver gets fired, doesn't it?
Try something like this...
public class MyActivity extends Activity {
private MyConnectivityListener connListener = null;
private IntentFiler connIntentFilter = null;
private Boolean connIntentFilterIsRegistered = false;
#Override
protected void onCreate(...) {
...
connIntentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
connListener = new MyConnectivityListener();
}
#Override
protected void onResume() {
...
if (!connIntentFilterIsRegistered) {
registerReceiver(connListener, connIntentFilter);
connIntentFilterIsRegistered = true;
}
}
#Override
protected void onPause() {
...
if (connIntentFilterIsRegistered) {
unregisterReceiver(connListener);
connIntentFilterIsRegistered = false;
}
}
protected class MyConnectivityListener extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// The NetworkInfo for the affected network is sent
// as an extra; it should be consulted to see what
// kind of connectivity event occurred.
}
}
}
A BroadcastReceiver is effectively a 'listener' which listens for events either sent by the system or, in some cases, by your own application components.
In this case, the system broadcasts android.net.conn.CONNECTIVITY_CHANGE whenever there is a connection change (connected/disconnected). By registering your BroadcastReceiver to 'listen' for that event, you can get the extra included in the Intent from your BroadcastReceiver's onReceive(...) method and do whatever you need to do accordingly. The extra is a `NetworkInfo object which will contain information about the particular network and whether it is connected or not.