Well, after my SplashScreen screen. My app will check for an Internet connection. if there is internet available, it will call the WebView. Otherwise, it will call one Activity of error.
But how do I pair to check the internet DURING SplashScreen?
ACTIVITY SPLASH SCREEN:
public class Splash extends Activity{
private static int tempo_splash = 1000;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Para o layout preencher toda tela do cel (remover a barra de tit.)
new Timer().schedule(new TimerTask() {
public void run() {
finish();
Intent intent = new Intent();
intent.setClass(Splash.this, MainActivity.class); //Chamando a classe splash e a principal (main)
startActivity(intent);
}
}, 2000);
}
}
MY CLASS CheckINTERNET:
public class CheckInternet extends Activity{
boolean status = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.internet);
Button btnStatus = (Button) findViewById(R.id.check_btn);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = checkInternetConnection();
if (status) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(CheckInternet.this, MainActivity.class);
CheckInternet.this.startActivity(mainIntent);
CheckInternet.this.finish();
}
}, 5000);
}
else {
Toast.makeText(getApplicationContext(), "You don't have Internet connection. Try Again", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean checkInternetConnection() {
ConnectivityManager connectivity = (ConnectivityManager)getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] inf = connectivity.getAllNetworkInfo();
if (inf != null) {
for (int i = 0; i < inf.length; i++) {
return true;
}
}
}
return false;
}
}
try this code... maybe help you
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.splash_screen);
if(isWorkingInternetPersent()){
splash();
}
else{
showAlertDialog(SplashScreen.this, "Internet Connection",
"You don't have internet connection", false);
}
}
public void splash() {
Thread timerTread = new Thread() {
public void run() {
try {
sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent intent = new Intent(getApplicationContext(), New_Main_Activity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
}
};
timerTread.start();
}
public boolean isWorkingInternetPersent() {
ConnectivityManager connectivityManager = (ConnectivityManager) getBaseContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo[] info = connectivityManager.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
// alertDialog.setIcon((status) ? R.mipmap.ic_launcher : R.mipmap.ic_launcher);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
});
// Showing Alert Message
alertDialog.show();
}
You should not really have an Intent just for checking connectivity. My suggestion is to create a "utility" class - call is MyConnectivityChecker and in there you add a static method (isConnected) with the following code:
public class MyConnectivityChecker {
public static boolean isConnected(Context context){
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
connected = (wifi.isAvailable() && wifi.isConnectedOrConnecting() || (mobile.isAvailable() && mobile.isConnectedOrConnecting()));
return connected;
}
}
Then in your Splash Activity wherever you want to check connectivity, you call the isConnected method like this:
MyConnectivityChecker.isConnected(this)
For example you could do something like this:
if(MyConnectivityChecker.isConnected(this)){
//connectivity available
}
else{
//no connectivity
}
I hope this helps. Give it a try and let me know.
what you can do is check for internet connection inside of your timer of SplashScreen.
new Timer().schedule(new TimerTask() {
public void run() {
if(isOnline()){
Intent intent = new Intent(Splash.this,WebViewActivity.class);
startActivity(intent);
finish();
}else{
Intent intent = new Intent(Splash.this,ErrorActivity.class);
startActivity(intent);
finish();
}
}
}, 2000);
And for internet checking you can use this method.
public boolean isOnline() {
System.out.println("executeCommand");
Runtime localRuntime = Runtime.getRuntime();
try {
int i = localRuntime.exec("/system/bin/ping -c 1 8.8.8.8")
.waitFor();
System.out.println(" mExitValue " + i);
boolean bool = false;
if (i == 0) {
bool = true;
}
return bool;
} catch (InterruptedException localInterruptedException) {
localInterruptedException.printStackTrace();
System.out.println(" Exception:" + localInterruptedException);
return false;
} catch (IOException localIOException) {
localIOException.printStackTrace();
System.out.println(" Exception:" + localIOException);
}
return false;
}
NOTE: Add this method in your SplashScreen outside the onCreate() methode.
Happy Coding..
Create Following Utility Class as below :
public class Utility {
/**
* This function check <u>Mobile Data</u> or <u>WiFi</u> is switched on or not..<br />
* It will be return <b>true</b> when switched on and return <b>false</b> when switched off.<br />
* <br />
* Developed by <b>Suthar Rohit</b>
*
* #param context {#link Context} of activity
* #return true if <u>Mobile Data</u> or <u>WiFi</u> is switched on.
*/
public static boolean isOnline(Context context) {
try {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nInfo = cm.getActiveNetworkInfo();
return nInfo != null && nInfo.isConnected();
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
and use as below in splash screen :
if(Utility.isOnline()) {
// INTERNET AVAILABLE
} else {
// INTERNET NOT AVAILABLE
}
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
public class SplashACtivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
NetworkInfo activeNetwork = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
// Load Webview
startActivity(new Intent(SplashACtivity.this, WebViewActivity.class));
} else {
// Show No internet
startActivity(new Intent(SplashACtivity.this, NoInternetACtivity.class));
}
}
}, 5000);
}
}
Related
This is not a duplicate
I want to check real-time internet connection from my activity using AsyncTaskand Handler to display or hide TexView if a connection is available or not. But it doesn't work.
My code throws NetworkOnMainThreadException even using AsyncTask
I'm using this code:
class CheckNetWorkConnection extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
public checkNetWorkConnection(MyActivity activity) {
this.activity= activity;
}
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible;
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
}
});
// doInBackground always retun false
return networkAvalaible;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
// Using handler to repeat Task
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (aBoolean){
activity.noConnection.setVisibility(View.GONE);
}else {
activity.noConnection.setVisibility(View.VISIBLE);
}
}
},3000);
super.onPostExecute(aBoolean);
}
}
to use it, you call
new CheckNetWorkConnection().execute();
you will want your async task to run indefinitely until an internet connection is lost. your current code will only check one time.
you need to change your codes to be polling for it to work.
#Override
protected Boolean doInBackground(String... strings) {
boolean networkAvalaible = false;
do {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
networkAvalaible = true;
sleep(5000); //check connection every 5 seconds.
// you can call publish progress here to tell your process that
// connection is available
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
networkAvalaible = false;
}
} while (networkAvalaible);
//you only exit and asyncTask when connection is lost.
return networkAvalaible;
}
AsyncTask is not the right way to do it though... take a look at the following article below.
https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/
Put this Class into your util Package to chack internet connection anywhere into your project.
ConnectionDetector.java
package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by Pranav on 29/08/16.
*/
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
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) {
return true;
}
}
return false;
}
}
Here is a code snippet if MainActivity.java to check internet connection and if internet connection is on then call asynctask otherwise give toast message.
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import java.net.URL;
import java.net.URLConnection;
import util.ConnectionDetector;
/**
* Created by Pranav on 29/08/16.
*/
public class CaseDetaiksActivity extends Activity {
public static Context context;
ConnectionDetector mConnectionDetector;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
mConnectionDetector = new ConnectionDetector(context);
setContentView(R.layout.activity_mail);
if (mConnectionDetector.isConnectingToInternet()) {
MyAyncTask MyTask = new MyAyncTask();
MyTask.execute();
} else {
Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
}
}
public static class MyAyncTask extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
// You can track you progress update here
}
#Override
protected Void doInBackground(Void... params) {
try {
URL myUrl = new URL("https://www.stackoverflow.com");
URLConnection connection = myUrl.openConnection();
connection.setConnectTimeout(3000);
connection.connect();
} catch (Exception e) {
//I'm catching NetworkInMainThreadException here
e.printStackTrace();
}
return null;
}
}
}
Hope this helps you
a .Create a broadcast receiver class
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
if(checkInternet(context)){
Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show();
}
}
public boolean checkInternet(Context context) {
ServiceManager serviceManager = new ServiceManager(context);
if (serviceManager.isNetworkAvailable()) {
return true;
} else {
return false;
}
}
}
b. Create a Service manager class
public class ServiceManager {
Context context;
public ServiceManager(Context base) {
context = base;
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
}
Register permissions in the Android Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Declare Broadcast Receiver in the Android Manifest
<receiver android:name=".receivers.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
In your activity :
a. register your broadcast receiver in onResume()
registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
b. unregister your broadcast receiver in onPause();
unregisterReceiver(new NetworkChangeReceiver());
I want to close my application from splash screen automatically after showing an message if there is no internet connection available or any error occurs due to response error. My code closes the application but cant close the splash screen.Times of India(TOI) application does like this. How to implement this feature.
my splash screen activity is like this..
public class SplashScreen extends Activity {
// Splash screen timer
private static int SPLASH_TIME_OUT = 8000;
static String MENU = null;
ArrayList<String> ls = new ArrayList<String>();
private String[] categoryType;
private boolean flag = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
// requesting data for menu items in navigation drawer
String url = "http://guwahatinow.com/?json=get_category_index";
if (isOnline()) {
JsonObjectRequest jsonObjReqMenu = new JsonObjectRequest(Method.GET,
url, null, new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONArray jsonArrayMenu= response.getJSONArray("categories");
Log.d("request", "menu");
int loop;
ls.add("Top Stories");
for (loop = 0; loop <jsonArrayMenu.length() ; loop++) {
JSONObject jsonObj = (JSONObject) jsonArrayMenu.get(loop);
String category =jsonObj.getString("title") ;
//menu.add(category);
ls.add(loop+1, category);
Log.d("menu added", category);
Log.d("element in ls", ls.get(loop));
}
ls.add("Exit");
int i = ls.size();
categoryType = new String[i];
for (int j = 0; j < i; j++) {
categoryType[j] = ls.get(j);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Please check your internet connection and try again...", Toast.LENGTH_LONG).show();
VolleyLog.d("menu error", "Error: " + error.getMessage());
flag = false;
//finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
//System.exit(0);
}
});
RequestQueue menuQueue = Volley.newRequestQueue(this);
menuQueue.add(jsonObjReqMenu);
if (flag) {
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);
} else {
Toast.makeText(getApplicationContext(), "Internet connection error...", Toast.LENGTH_LONG).show();
finish();
System.exit(0);
}
/*new Handler().postDelayed(new Runnable() {
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
Log.d("main activity called", "true");
// close this activity
finish();
}
}, SPLASH_TIME_OUT);*/
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Calling the finish() method on an Activity when there is no connection available in your case or any other at where you want to close app.
In you major else block of if block for checking internet call finish() method. eg
You have you code as
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
}
Change it to
if (isOnline()) {
// your Code for calling API and starting timer
} else {
Toast.makeText(getApplicationContext(), "Please connect to internet...", Toast.LENGTH_LONG).show();
finish();
}
Hi please replace your code with below code where you used handler thread
CountDownTimer m_countDownTimer;
m_countDownTimer = new CountDownTimer(8000,1000) {
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
if(!isFinishing())
{
Intent i = new Intent(SplashScreen.this, MainActivity.class);
i.putExtra(com.hamburger.menu.SplashScreen.MENU, categoryType);
startActivity(i);
finish();
}
}
}.start();
Cancel CountDownTimer object in OnDestroy()
#Override
protected void onDestroy()
{
if(m_countDownTimer != null)
{
m_countDownTimer.cancel();
}
super.onDestroy();
}
I am trying to find out if my app is connected to the internet or not. I have a timeout set to 3 seconds. Sometimes the Internet Check will come back as "Not Connected" (even if I do have an internet connection) and sometimes it doesn't. Why does it take longer sometimes to check than others? Would I be able to have a dialogbox or something to popup while this is being checked?
public void isNetworkAvailable(final Handler handler)
{
new Thread()
{
private boolean responded = false;
#Override
public void run()
{
new Thread()
{
#Override
public void run()
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest);
responded = true;
}
catch (Exception e)
{
}
}
}.start();
try
{
int waited = 0;
while (!responded && (waited < 3000))
{
sleep(100);
if (!responded)
{
waited += 1000;
}
}
}
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
Log.i("Internet check", "Not connected");
}
else
{ // code if connected
Log.i("Internet check", "Connected");
}
}
};
Use the following code
if(!haveInternet()){
<Your Alert Dialog Here>
}
private boolean haveInternet() {
NetworkInfo info = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE))
.getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
return true;
}
return true;
}
are you consider use this http://developer.android.com/training/monitoring-device-state/connectivity-monitoring.html and/or register a BroadcastReceiver to notify it when connection is down/up, then you can handle it in any place of your application?
public class CustomApplication extends Application {
public static final String INTERNET_ACTION = "internet_action";
public static final String EXTRA_STATUS = "status";
#Override
public void onCreate() {
super.onCreate();
monitorNetworkAvailability();
}
private void monitorNetworkAvailability() {
//
// Improve the way to handle Thread
//
new Thread() {
private boolean responded = false;
#Override
public void run() {
while (true) {
new Thread() {
#Override
public void run() {
HttpGet requestForTest = new HttpGet("http://m.google.com");
try {
new DefaultHttpClient().execute(requestForTest);
responded = true;
} catch (Exception e) {
}
}
}.start();
try {
int waited = 0;
while (!responded && (waited < 3000)) {
sleep(100);
if (!responded) {
waited += 1000;
}
}
} catch (InterruptedException e) {
} // do nothing
finally {
Intent i = new Intent(INTERNET_ACTION);
i.putExtra(EXTRA_STATUS, responded);
sendBroadcast(i);
}
try {
Thread.sleep(1 * 60 * 1000);
} catch (InterruptedException e) {
}
}
}
}.start();
};
}
class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
registerReceiver(receiver, i);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
IntentFilter i = new IntentFilter(CustomApplication.INTERNET_ACTION);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
boolean responded = intent.getBooleanExtra(CustomApplication.EXTRA_STATUS, false);
if (!responded) {
Toast.makeText(MyActivity.this, "No connection", Toast.LENGTH_SHORT).show();
}
}
};
}
public static Boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if(ni != null && ni.isConnected())
return true;
//Toast.makeText(context, context.getString(R.string.no_internet_connection), Toast.LENGTH_SHORT).show();
return false;
}
Requires permission:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
Edit:
As you correctly point out this is not a solid solution. In my case (which I indeed failed to mention) this is sufficient as a first check paired with LocationClient.isConnected().
Looking at your code I would think that it is worth taking a look at LocationClient, even if you are not planning to use location awareness of you app.
My reasoning for this is that you get rid of the need to repeatedly use resources to check if you have a valid connection. LocationClient uses the already in place communication with Google Play to tell you whether you are connected or not.
This solution of course only works if you assume that your users have a Google Account added to their device.
Here is a link to the official guidelines: http://developer.android.com/training/location/retrieve-current.html the onConnected and onDisconnected parts are found in the Define Location Services Callbacks section.
You are right. Your problem is that, the device checks for internet connection, and sometimes get a response from the router which says it cannot connect to internet, but that itself is a response, so your code might think that there is a response. Below is a sample method to test if you really can connect to the internet.
public static boolean hasActiveInternetConnection()
{
try
{
new Socket().connect(new InetSocketAddress("google.com", 80), 4000);
return true;
} catch (Exception e)
{
return false;
}
}
Then inside your activity you can call. (Make sure not to run this inside the MAIN/UI thread. Use an async or thread/handler/runnable strategy)
if(hasActiveInternetConnection())
{
//yey I have internet
}
else
{
//no internet connection
}
I was able to complete this by putting it inside an AsyncTask.
class online extends AsyncTask<String, String, String>
{
boolean responded = false;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog2 = new ProgressDialog(Main.this);
pDialog2.setMessage("Checking internet, please wait...");
pDialog2.setIndeterminate(false);
pDialog2.setCancelable(false);
pDialog2.show();
}
protected String doInBackground(String... args)
{
HttpGet requestForTest = new HttpGet("http://m.google.com");
try
{
new DefaultHttpClient().execute(requestForTest); // can
responded = true;
}
catch (Exception e)
{
}
try
{
int waited = 0;
while (!responded && (waited < 5000))
{
mHandler.postDelayed(new Runnable()
{
public void run()
{
}
}, 100);
waited += 100;
}
}
finally
{
if (!responded)
{
h.sendEmptyMessage(0);
}
else
{
h.sendEmptyMessage(1);
}
}
return null;
}
protected void onPostExecute(String file_url)
{
pDialog2.dismiss();
}
}
In my main activity , there is a internet status TextView . In that TextView I want to show whether the internet connection is enabled or not. I have to refresh the status in every 10 sec.
I know that i have to do this in a separate thread but I tried a lot. I'm not getting perfect solution.
public class MainActivity extends Activity {
ImageView imageView;
TextView internetStausTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
internetStausTextView = (TextView) findViewById(R.id.tv1);
new InternetChecker();
}
public class InternetChecker implements Runnable {
Thread t;
boolean internetStatus;
ConnectivityManager conMgr;
public InternetChecker() {
t = new Thread(this);
t.start();
conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
}
public void run() {
while (true) {
if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING) {
internetStatus = true;
} else if (conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
|| conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
internetStatus = false;
}
runOnUiThread(new Runnable() {
public void run() {
if (internetStatus)
internetStausTextView.setText("connected");
else
internetStausTextView.setText("Not connected.");
}
});
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
}
}
Here is my code ....
But it is affecting performance of the app.
Can any one help me to take out the sub class InternetChecker to a separate file.
Try this :
EDITED :
First Create one Handler and Thread running flag:
Handler mHandler = new Handler();
boolean isRunning = true;
Then, use this thread from your onCreate() method :
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
displayData();
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Then, declare this method which called by your handler at every 10 seconds :
private void displayData() {
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
Toast.makeText(this, "Network Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Available");
}
else
{
Toast.makeText(this, "Network Not Available", Toast.LENGTH_SHORT).show();
myTextView.setText("Network Not Available");
}
}
To stop thread call this :
isRunning = false;
That's It.
Thanks.
DONOT use service.
User TimerTask and Timer to check and update internet connection regularly. Updating the UI from a Timer is the best example for your need.
Happy coding :)
First you need to create a Timer task to check network connectivty
_tv = (TextView) findViewById( R.id.TextViewTime );
UpdateNetworkInfo();
Timer _t = new Timer();
String conn;
_t.scheduleAtFixedRate( new TimerTask() {
#Override
public void run() {
ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo nf=cn.getActiveNetworkInfo();
if(nf != null && nf.isConnected()==true )
{
conn = " Avaialable";
}
else
{
conn = " Not Available";
}
}
}, 1000, 1000 );
Then update network info in the UI thread.
protected void UpdateNetworkInfo()
{
runOnUiThread(new Runnable()
{
public void run()
{
_tv.setText( "Network" + conn );
}
});
}
Dont forget to add appropriate permissions to the manifest file.
public boolean isNetworkAvailable(){
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo != null && networkInfo.isConnected()){
Toast.makeText(this, "Network is available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Network is not available", Toast.LENGTH_LONG).show();
}
return true;
}
is it posible ??
I have an activity and an alertdialog on it.
but i need the activity run first and then 2 seconds later appears the alertdialog.
i have no idea how. regards
pd: iam not an english speaker
public class Pantalladeinicio extends Activity {
private final int SPLASH_DISPLAY_LENGTH = 2000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.index);
if(checkInternetConnection()==true) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent mainIntent = new Intent(Pantalladeinicio.this,
NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
}, SPLASH_DISPLAY_LENGTH);
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
public void aceptar() {
// Toast t=Toast.makeText(this,"Bienvenido a probar el programa.", Toast.LENGTH_SHORT);
super.onDestroy();
finish();
}
private boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
//Log.v("TAG", "Internet Connection Not Present");
return false;
}
}
}
I don't understand your question, but looking at the accepted answer I suggest changing the order of your existing code:
new Handler().postDelayed(new Runnable() {
public void run() {
if(checkInternetConnection()) {
Intent mainIntent = new Intent(Pantalladeinicio.this, NetworkingActivity.class);
mainIntent.putExtra("MAIN", true);
startActivity(mainIntent);
finish();
}
else
{
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
}
}, SPLASH_DISPLAY_LENGTH);
Change your code as using Thread and runOnUiThread
//Your Code here...
else
{
myThread();
}
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
Pantalladeinicio.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
AlertDialog.Builder dialogo1 = new AlertDialog.Builder(Pantalladeinicio.this);
dialogo1.setTitle("Importante");
dialogo1.setMessage("Debe activar la Conexion a Internet");
dialogo1.setCancelable(false);
dialogo1.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogo1, int id) {
aceptar();
}
});
dialogo1.show();
Log.v("TAG", "Internet Connection Not Present");
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
I assume you want to wait for 2 seconds after you get into the else block.
You could do this by calling Thread.sleep(2000); before you call dialogo1.show();. However, this will make your program appear to "freeze". In order to avoid this you can create a seperate thread that sleeps and then displays the dialog.