Query regarding app using Internet connection - android

I have an application that uses Internet connection but when there is no internet connection available the application stop responding. Can anyone help on how i can resolve this problem. What I have thought that i can display an error when there no internet connection available but I dont know the way to do it.

Required permission is :
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Check Internet connection for each request
public boolean isOnline() {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
Use above method as
if(isOnline()) {
//Write code of request
} else {
showDialog("Internet connection error", "Connection is not available.")
}
Show dialog method
private void showDialog(String title, String text) {
// Access denied. Show dialogue to user
AlertDialog.Builder alertbox = new AlertDialog.Builder(YOUR_ACTIVITY.this);
alertbox.setTitle(title);
alertbox.setIcon(android.R.drawable.ic_dialog_info);
alertbox.setMessage(text);
alertbox.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
//finish(); //DO nothing
}
});
alertbox.show();
}
Edited :
Replace YOUR_ACTIVITY.this with activity name in which your are using this code.

You can show an AlertDialog to show the user that there is no internet connection.And if your application can't go on without connection,after clickin cancel button in AlertDialog, you can finish your activity and close the application.

Check out my HTTPclass.java class, how I did that, I have a method connect(url) that takes a String of url and connects it, if connection is received it responds and gives the responseCode = 200 or HTTP.OK, and if the connection is not connected I handle a catch block and set the responseCode = -1 which means its not connected.
So, you can do something like that only. When responsecode is -1 you can show the Message that "Internet Not Connected".
public class HTTPClass
{
private static int responseCode = -1;
private static HttpURLConnection httpconn = null;
private static URLConnection conn = null;
private static URL urlobj;
public static int connect(String url) throws IOException
{
try
{
urlobj = new URL(url);
conn = urlobj.openConnection();
httpconn= (HttpURLConnection)conn;
httpconn.setConnectTimeout(5000);
httpconn.setDoInput(true);
}
catch(Exception e)
{
e.printStackTrace();
}
try
{
responseCode = httpconn.getResponseCode();
}
catch(Exception e)
{
responseCode = -1;
e.printStackTrace();
}
return responseCode;
}
}

Related

How to set a fixed time if AsyncTask is not finished

I have an asynctask and I'm looking to do a wait if the async is taking too long, I'm downloading some data of the database , but I don't want to have the user looping around the progressdialog, I want to set a fixed time, lets say I'm downloading a file but is taking forever, so I tell the user, "hey, check your internet connection and try again" I'm looking to do this with a timer, but I'm kinda stuck, this is where I do my asynctask
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
String s;
public DownloadFilesTask(String s){
this.s = s;
}
#Override
protected Void doInBackground(Void... voids) {
DownloadMethod(s);
return null;
}
}
so let's say I want to execute that downloadmethod for a fixed time, 10 or 20 seconds, if the file is not downloaded at that time I return a message to the user saying that he needs to check for hes internet.
You can use handler to run after a definite amount time and maintain a boolean flag which you can update in postExecute function of async task.
In your activity/fragment class:
new Handler().postDelayed(new Runnable(){
public void run(){
//Check whether the flag has been updated or not
},1000)
You can use BroadcastReceiver to listen your internet connection. Here is an example:
public class NetworkControl extends BroadcastReceiver {
static boolean isConnected = false;
#Override
public void onReceive(final Context context, final Intent intent) {
isNetworkAvailable(context);
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
if(!isConnected){
isConnected = true;
Toast.makeText(context, "You're online!!", Toast.LENGTH_LONG).show();
}
return true;
}
}
}
}
isConnected = false;
Toast.makeText(context, "Connection interrupted.", Toast.LENGTH_LONG).show();
return false;
}
}
Also you need some permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Then start the service in your activity.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkControl();
registerReceiver(receiver, filter);
If you are using HttpURLConnection to download the file then you can do something like this:
private class DownloadFilesTask extends AsyncTask<String, Integer, Integer> {
#Override
protected Integer doInBackground(String... ulr) {
URL url = null;
try {
url = new URL(ulr[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(2000); //Timeout
//...Other codes for downloading
return 101;
} catch (java.net.SocketTimeoutException e) {
return 102;
} catch (MalformedURLException e) {
return 103;
} catch (IOException e) {
return 104;
}
}
#Override
protected void onPostExecute(Integer result) {
if(result == 102) {
Toast.makeText(getApplicationContext(), "Connection Timeout.", Toast.LENGTH_LONG).show();
}
}
}
First thing I want to say that is, while running downloading task it's not a good practice, to message a user that check your internet connection or
no internet connection. Because in this condition, if user do switch off then on network connection then your downloading task restarts again and takes whole time again. So, avoid this types of messages.
Now about solution, after execute background task you can check your task is running or completed. If it takes too much time
then show a message. For example,
YourBackgroundTask task = new YourBackgroundTask();
task.execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (task.getStatus == AsyncTask.Status.RUNNING){
Toast.makeText(this, "Please wait...", Toast.LENGTH_SHORT).show();
}
}
},20000); // time in milisecond
And if you want to repeat this, you can easily re-run handler.
Here is a basic idea you can try if it works
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void> implements TimerTask{
String s;
Timer timer;
Object objectResult;
public DownloadFilesTask(String s){
this.s = s;
timer = new Timer();
}
#Override
protected Void doInBackground(Void... voids) {
objectResult = DownloadMethod();
return null;
}
private Object DownloadMethod() {
//here implement the download logic and return the object
return null;
}
#Override
protected void onProgressUpdate(Integer... progress) {
// your code to update progress
}
public void checkProgress(){
timer.schedule(this,2000);
}
#Override
public void run() {
if (objectResult!=null){
//download completed
}else{
//show dialog here and schedule a task again
timer.schedule(this,2000);
}
}
}

Android sockets reconnect to server

I'm building a android app that using connection with Java server (on computer).
I have a problem- when I find that there is no connection with the server, I'm trying to reconnect to the server but it doesn't work.
Here is the Client class code:
public class Client extends AsyncTask {
private final int port = 1978;
private final String ip = "192.168.14.22";
private Socket socket;
private DataOutputStream output;
private DataInputStream input;
public Client() {
}
#Override
protected Object doInBackground(Object[] objects) {
try {
socket = new Socket(ip, port);
output = new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
Log.d("Network c1", "Connected");
} catch (IOException e) {
socket = null;
Log.d("Network c1", "Not connected");
}
return null;
}
public boolean checkConnection() {
if (output == null)
return false;
try {
output.writeUTF("abc");
return true;
} catch (IOException e) {
return false;
}
}
#Override
protected void onProgressUpdate(Object[] values) {
}
}
And the Activity code:
public class LogInActivity extends AppCompatActivity {
Client client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
client = new Client();
client.execute();
//I used timer because it didn't work without it- That saied always 'not connected' message/Toast
new CountDownTimer(5, 0) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
check();
}
}.start();
}
private void check() {
boolean isProcess;
isProcess = !checkConnection();
if (isProcess) {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert);
builder.setTitle(getResources().getString(R.string.app_name));
builder.setMessage("Unable connect to the library");
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//See note 1.
check();
}
});
builder.setCancelable(false);
builder.show();
}
}
public boolean checkConnection() {
if (client.checkConnection()) {
Toast.makeText(getApplicationContext(), "Connected to the library", Toast.LENGTH_SHORT).show();
return true;
} else {
Toast.makeText(this, "Unable connect to the library", Toast.LENGTH_SHORT).show();
return false;
}
}
}
Note 1:
The problem is here.
This Dialog need to be shown until the server/Library connected.
If the server is on before the app turned on, the check() method works well and says 'Connected successful' and the Dialog doesn't show.
But if when the app started, the server was unreachable, and turned on later (And became reachable)- the check() method don't work and always shows the Dialog.
What is the problem?
By the way, I tried to restart the client AsyncTask Class, but i didn't succeed.
(I tried to do close(true) to it, and after do excute() to it again, but the cancel() method didn't worked, and was a error that said that after a AsyncTask Class excuted, it can't excute again)
Thanks.
You should not check for connectivity periodically (every couple of seconds like you do in this code).
Instead you should let the OS do this for you, it will be more reliable and more efficient in terms of battery and CPU.
Take a look at this answer

Static method call from AsyncTask is async?

I'm trying to use a AsyncTask to check if internet connection is available and then doing some stuff.
My problem is while the comprobation is being executed I canĀ“t interacting with the UI. The "progressbar" is on front and if I try to click on a button the UI doesn't respond
This is the call to AsyncTask
#Override
public void onStart(){
super.onStart();
AsyncHttpHandler check = new AsyncHttpHandler(**paramaters**);
check.execute("checkshared");
}
This is the code of AsyncTask
public class AsyncHttpHandler extends AsyncTask<String, Integer, String>{
public AsyncHttpHandler(Context c, Intent i, Bundle _data, String _language){
ctx = c;
intent = i;
data = _data;
language = _language;
startClock();
}
public void startClock(){
mDialog = new ProgressDialog(ctx,R.style.MyTheme);
mDialog.setProgressStyle(android.R.style.Widget_ProgressBar_Small);
mDialog.setCancelable(false);
mDialog.show();
}
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... peticion) {
String response = "null";
//call to check if internet connection is available
if(Utils.isInternetConn(ctx)){
try {
// do stuff
response = "...";
}
else response = "offline";
return response;
}
}
protected void onPostExecute(String response) {
if(mDialog != null) mDialog.dismiss();
if(!response.equals("offline")){
// do stuff
}
else Toast.makeText(ctx, ctx.getResources().getString(ctx.getResources().getIdentifier(language+"_toast_nointernet", "string", ctx.getPackageName())), Toast.LENGTH_LONG).show();
}
}
And this is the method to check if the internet connection is available:
public static Boolean isInternetConn(Context ctx){
ConnectivityManager connec = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean conectado = false;
if((wifi != null && wifi.isConnectedOrConnecting()) || (mobile != null && mobile.isConnectedOrConnecting())){
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
URL myurl = new URL("http://www.google.com");
URLConnection connection;
connection = myurl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
int responseCode = -1;
responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
conectado = true;
httpConnection.disconnect();
}
else {
httpConnection.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return conectado;
}
What am I doing wrong?
The problem is not in your AsyncTask calling static method. That will also execute async. Problem is that you are showing progress dialog until your task finishes. And, of course, while your progress dialog is visible you will not be able to interact with the UI. If you want to interact with the UI, show your progress in another way, not with dialog.
You display a progressDialog on top of the screen. The progress dialog takes the UI interaction, so the buttons underneath don't respond. If you use a progress bar in your UI instead of a progress dialog, your buttons will work.
If you want to show the progress of your task to the user, use the method onProgressUpdate, as it has been implemented to run on the UI thread.
Now, each time you want to show the progress from doInBackground, call it by passing an argument. To be clear, AsyncTask (String, Integer, String) uses argument types:
First is the type of argument you pass when you call execute
Second is the type of the argument you pass to onProgressUpdate
Third is the type of argument you pass to onPostExecute
I'm not sure if I understood what is your problem, but it seems to me, that you cannot interact with UI because the ProgressDialog is not cancelable, and it's in front of everything else.
You will only have feedback when dialog is dismissed.

Modified example application NetworkUsage not working properly

I am trying to build my first app for Android and, firstly, I compiled the example application in the networkusage.zip file on the Android Developers website (location: http://developer.android.com/training/basics/network-ops/index.html). It worked fine, so I tried to modify it according to my goal.
The modified code works fine when connects to a Wi-Fi network, but if I set it to any network it fails displaying the message: "Lost connection."
I modified only "NetworkActivity.java"
public class NetworkActivity extends Activity {
public static final String WIFI = "Wi-Fi";
public static final String ANY = "Any";
private static final String URL ="http://www.kibao.org/simu/wap.php?lng=";
final Context context = this;
// Whether there is a Wi-Fi connection.
private static boolean wifiConnected = false;
// Whether there is a mobile connection.
private static boolean mobileConnected = false;
// Whether the display should be refreshed.
public static boolean refreshDisplay = true;
// The user's current network preference setting.
public static String sPref = null;
public static String pagina = "";
// The BroadcastReceiver that tracks network connectivity changes.
private NetworkReceiver receiver = new NetworkReceiver();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register BroadcastReceiver to track connection changes.
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
receiver = new NetworkReceiver();
this.registerReceiver(receiver, filter);
}
// Refreshes the display if the network connection and the
// pref settings allow it.
#Override
public void onStart() {
super.onStart();
// Gets the user's network preference settings
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// Retrieves a string value for the preferences. The second parameter
// is the default value to use if a preference value is not found.
sPref = sharedPrefs.getString("listPref", "Wi-Fi");
updateConnectedFlags();
// Only loads the page if refreshDisplay is true. Otherwise, keeps previous
// display. For example, if the user has set "Wi-Fi only" in prefs and the
// device loses its Wi-Fi connection midway through the user using the app,
// you don't want to refresh the display--this would force the display of
// an error page instead of stackoverflow.com content.
if (refreshDisplay) {
loadPage();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (receiver != null) {
this.unregisterReceiver(receiver);
}
}
// Checks the network connection and sets the wifiConnected and mobileConnected
// variables accordingly.
private void updateConnectedFlags() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
if (activeInfo != null && activeInfo.isConnected()) {
wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
} else {
wifiConnected = false;
mobileConnected = false;
}
}
// Uses AsyncTask subclass to download the XML feed from stackoverflow.com.
// This avoids UI lock up. To prevent network operations from
// causing a delay that results in a poor user experience, always perform
// network operations on a separate thread from the UI.
private void loadPage() {
if (((sPref.equals(ANY)) && (wifiConnected || mobileConnected))
|| ((sPref.equals(WIFI)) && (wifiConnected))) {
// AsyncTask subclass
//new DownloadXmlTask().execute(URL);
String lng = getResources().getString(R.string.lng);
new DownloadWebpageTask().execute(URL.concat(lng));
} else {
showErrorPage();
}
}
// Displays an error if the app is unable to load content.
private void showErrorPage() {
setContentView(R.layout.main);
// The specified network connection is not available. Displays error message.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadData(getResources().getString(R.string.connection_error),
"text/html", null);
}
// Populates the activity's options menu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
// Handles the user's menu selection.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings:
Intent settingsActivity = new Intent(getBaseContext(), SettingsActivity.class);
startActivity(settingsActivity);
return true;
case R.id.refresh:
loadPage();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// Given a string representation of a URL, sets up a connection and gets
// an input stream.
private InputStream downloadUrl(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
InputStream stream = conn.getInputStream();
return stream;
}
/**
*
* 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.
refreshDisplay = true;
Toast.makeText(context, R.string.wifi_connected, Toast.LENGTH_SHORT).show();
// If the setting is ANY network and there is a network connection
// (which by process of elimination would be mobile), sets refreshDisplay to true.
} else if (ANY.equals(sPref) && networkInfo != null) {
refreshDisplay = true;
// Otherwise, the app can't download content--either because there is no network
// connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there
// is no Wi-Fi connection.
// Sets refreshDisplay to false.
} else {
refreshDisplay = false;
Toast.makeText(context, R.string.lost_connection, Toast.LENGTH_SHORT).show();
}
}
}
// Implementation of AsyncTask used to download Webpage
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadWebpageFromNetwork(urls[0]);
} catch (IOException e) {
return getResources().getString(R.string.connection_error);
}
}
#Override
protected void onPostExecute(String result) {
setContentView(R.layout.main);
// Displays the HTML string in the UI via a WebView
WebView myWebView = (WebView) findViewById(R.id.webview);
//myWebView.loadData(result, "text/html", null);
//myWebView.loadDataWithBaseURL("http://www.kibao.org",result, "text/html", "utf-8",null);
String lng = getResources().getString(R.string.lng);
myWebView.loadUrl(URL.concat(lng));
}
}
// Uploads XML from stackoverflow.com, parses it, and combines it with
// HTML markup. Returns HTML string.
private String loadWebpageFromNetwork(String urlString) throws IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
pagina = getStringFromInputStream(stream);
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (stream != null) {
stream.close();
}
}
// StackOverflowXmlParser returns a List (called "entries") of Entry objects.
// Each Entry object represents a single post in the XML feed.
// This section processes the entries list to combine each entry with HTML markup.
// Each entry is displayed in the UI as a link that optionally includes
// a text summary.
return pagina;
}
// convert InputStream to String
private static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
Please help me to understand my mistake.
Thanks a lot,
Nino V
I found my mistake: it was a very stupid one! It was in my arrays.xml where I localized both names and values, so the code didn't recognize the value "ANY" which in my Italian phone was "Qualsiasi"!
Thank you for your attention.
Nino V

Android check wifi connection

I have a specific question about wifi connection in Android.I'm working on a project which is downloading some data from web server and every time before starting the synchronization I'm checking about internet connection like this :
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
public static boolean chkNetworkStatus(Context context) {
boolean result = false;
new Thread() {
#Override
public void run() {
for(int i=0;i<3;i++){
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest);
responded = true;
} catch (Exception e) {
responded = false;
}
}
}
}.start();
boolean isOnline = isOnline(context);
if(responded && isOnline){
result = true;
} else {
result = false;
}
Log.e("","responded : "+responded);
return result;
}
But in this situation when I'm still connected to wifi and i'm walking (loosing connection) and press sync button it's still returning true because I'm connected, but actually it's not doing anything.
Is there anyway that I can detect this or I should use connectionTimeOut function in HttpURLConnection class which I'm using?
Actually, I don't know this one solve your problem or not but, you can set connection time-out with your HttpGet request,
This works in my case, So i don't need to check Internet availability..
try
{
HttpGet request = new HttpGet(url));
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 60000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 60000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
// create object of DefaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpClient.execute(request);
// get response entity
HttpEntity entity = response.getEntity();
// convert entity response to string
if (entity != null)
{
result = EntityUtils.toString(entity);
}
}
catch (SocketException e)
{
return "-222" + e.toString();
}
catch (Exception e)
{
return "-333" + e.toString();
}
Note: the request and other code may be different in your case, It just the idea of how HttpGet params used for set Connection TimeOut..
Basically you will receive broadcast when network connectivity changes if you register.
android.net.conn.CONNECTIVITY_CHANGE
For Solution
Here you go.
You will need to register for and handle BroadCastReceiver android.net.conn.CONNECTIVITY_CHANGE
Step 1
Include following permission in manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step2
Let Android know which class will be register for BroadCast Receiver.
<receiver android:name="ConnectivityReceiver_package_name.ConnectivityReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Step 3
Put your logic for various Network States.
public class ConnectivityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY,false);
if(noConnectivity){
//Show Warning Message
//Take appropriate actions.
}
}
}
try to do it like this:
public static void isNetworkAvailable(final Handler handler, final int timeout)
{
// ask fo message '0' (not connected) or '1' (connected) on 'handler'
// the answer must be send before before within the 'timeout' (in
// milliseconds)
new Thread()
{
private boolean responded = false;
#Override
public void run()
{
// set 'responded' to TRUE if is able to connect with google
// mobile (responds fast)
new Thread()
{
#Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest); // can
// last...
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < timeout))
{
sleep(100);
if (!responded)
{
waited += 100;
}
}
}
catch (InterruptedException e)
{
} // do nothing
finally
{
if (!responded)
{
handler.sendEmptyMessage(0);
}
else
{
handler.sendEmptyMessage(1);
}
}
}
}.start();
}
Handler h = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what != 1)
{ // code if not connected
}
else
{ // code if connected
}
}
};
And in your Activity, call it like that:
isNetworkAvailable(h, 2000);

Categories

Resources