checking network connection android - android

Heres my code for checking the network connection of my app.I want my app run only when it is connected to a network and closes it if not. The code was running with no errors but the problem is the alertdialog show many times.
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
checkCon = false;
finish();
}
}).show();
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}

Answer by harism, thanks
private void checkConnectivity(){
final Thread checkConnection = new Thread(new Runnable(){
#Override
public void run()
{
while (checkCon == true){
if(!isNetworkAvailable(MainActivity.this)) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new AlertDialog.Builder(MainActivity.this)
.setMessage("No network connection.")
.setCancelable(false)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int which) {
finish();
}
}).show();
checkCon = false;
}
});
} else {
checkCon = true;
}
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
});
checkConnection.start();
}

Add a new method inside your current Activity or Fragment:
private boolean isNetworkAvailable(){
boolean available = false;
/** Getting the system's connectivity service */
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
/** Getting active network interface to get the network's status */
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if(networkInfo !=null && networkInfo.isAvailable())
available = true;
/** Returning the status of the network */
return available;
}
And here is how to use it. You can use it inside onCreate() method:
if (isNetworkAvailable() == true){ // if network is available
// do your thing here
...
}else{ // "else" means that the network is not available
// do your thing here
...
}

Related

Call Thread.wait()

I need to make currentThread wait when do some operations in UiThread and then in UiThread call currentThread().notify() . I was trying this code
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
try {
currentThread().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
currentThread().notify();
}
})
.create()
.show();
}
});
}
but got java.lang.IllegalMonitorStateException: object not locked by thread before wait() exception. Please help me.
Try this code:
final Thread CURRENT_THREAD = currentThread();
Handler uiHandler = new Handler(Looper.getMainLooper());
uiHandler.post(new Runnable() {
#Override
public void run() {
AlertDialog.Builder facultyChooser = new AlertDialog.Builder(ctx);
facultyChooser.setTitle("choose")
.setCancelable(false)
.setItems(arr, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
synchronized(CURRENT_THREAD) {
CURRENT_THREAD.notify();
}
}
})
.create()
.show();
}
});
}
synchronized(CURRENT_THREAD) {
try {
CURRENT_THREAD.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

Create AlertDialog while holding a thread

I'm pretty fresh to this android thing, so i'm a bit confused with some concepts still. What I want to do is, while i'm at my Splash Screen, to show an AlertDialog when the user is not connected to the internet. I've tried to do that in so many ways but I can never hold the Thread and so I always get an exception because the activity closes before the dialog is closed. I have tried to do this with an Handler but no success... Part of my code is here:
public class Splash extends Activity {
public void openDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle(R.string.app_name);
// set dialog message
alertDialogBuilder
.setMessage(R.string.dialogo_net)
.setCancelable(false)
.setPositiveButton("Sair",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Splash.this.finish();
}
})
.setNegativeButton("Definições",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
openDialog();//Display Alert
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread logoTimer = new Thread() {
public void run(){
try{
int logoTimer = 0;
while(logoTimer < 2000){
sleep(100);
logoTimer = logoTimer +100;
};
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting()) {
//opens the dialog in this case
mHandler.sendEmptyMessage(0);
} else {
//goes to main activity
startActivity(new Intent("pt.aeist.mobile.START")); }
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
finish();
}
}
};
logoTimer.start();
}
}
Thread logoTimer = new Thread()
{
public void run(){
try{
sleep(2000);
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnectedOrConnecting())
{
mHandler.sendEmptyMessage(0);
} else
{
startActivity(new Intent("pt.aeist.mobile.START")); }
finish();
}
}catch(Exception e)
{
e.printStackTrace();
}
}
};
logoTimer.start();
//handle finish() separately.
.setNegativeButton("Definições",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
startActivity(intent);
finish();
}
});
Just Remove finish() from all places. And check it.
You have to identify the cases where you want to put finish();

Create a dialogbox inside a thread while checking for an internet connection

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();
}
}

Inetrnet connection checking thread Android

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;
}

delay an alertdialog

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.

Categories

Resources