I am stuck with following problem.I want my application to exit if it detects no network connection.My application starts with splash screen.Is it possible to show splash screen followed by toast if no network connection is on device.and then terminate the application
I have something like this in my splash screen code :
Inside onCreate()
ConnectivityManager connectivitymanager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkinfo = connectivitymanager.getActiveNetworkInfo();
connected = networkinfo != null && networkinfo.isAvailable()
&& networkinfo.isConnected();
Log.v("Network state : ", connected + "");
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while (waited < 5000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Looper.prepare();
if (connected == false) {
Toast.makeText(
splashscreenActivity.this,
"No Network Connection is available on device.",
Toast.LENGTH_LONG).show();
finish();
System.exit(0);
} else {
finish();
startActivity(new Intent(splashscreenActivity.this,
mainActivity.class));
}
Looper.loop();
}
}
};
splashThread.start();
1.Please see my code and guide me how can i show up that toast.
2.Or suggest me some other better way to do this
Thanks
EDIT :
Thank you everybody for replying :
I opted Dharmendra's way of showing toast via splashscreen activity :
The code that worked for is :
if (connected == false) {
splashscreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(splashscreenActivity.this,
"No Internet Connection.", 3000).show();
}
});
finish();
} else {
//migrate to main activity from splashscreen
}
You can do it like this, use Handler .Put the following code in the else condition
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
public void run() {
Toast.makeText(Splash.this, "Network error", Toast.LENGTH_LONG).show();
finish();
}
});
Or ,I am doing this in my application :
if(status.equals("CONNECTED"))
{
startActivity(new Intent(Splash.this,Activity.class));
finish();
}else
{
startActivity(new Intent(Splash.this,NetworkError.class));
finish();
}
where NetworkError class shows another layout with the image like "No Network,,,,"(or whatever you want to show instead of splash...)
You are creating and showing Toast from Thread so it may be not called
You have to write this code
splashscreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(c, "Internet connection not currently available.", 3000).show();
}
});
Just add a if else block.(using ur connection network info)
if(connected){
//put the splash thread here
}else{
finish();
}
A finally block is used if you do not wish to catch any exceptions. In your code, place all your code in a else loop, If time of 5000 lapses then, go to else statement and execute it. If you are adding catch you can remove finally.
Related
Here is my code:
automaticCountryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
if (ContextCompat.checkSelfPermission(HomeActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
setUpLocationPermission();
return;
}
Log.d(TAG, String.valueOf(gps.canGetLocation()));
Log.d(TAG, String.valueOf(gps.getLocation()));
Log.d(TAG, String.valueOf(gps.getLatitude()));
Log.d(TAG, String.valueOf(gps.getLongitude()));
Geocoder myLocation = new Geocoder(HomeActivity.this);
try
{
myList = myLocation.getFromLocation(gps.getLatitude(), gps.getLongitude(), 1);
}
catch (Exception e)
{
Log.d(TAG, "unable");
e.printStackTrace();
}
if(myList != null) {
try {
String country = myList.get(0).getCountryName();
Log.d(TAG, country);
findCountryInArrayList(country);
}
catch (Exception e)
{
Toast.makeText(HomeActivity.this, "Didn't manage to automatically detect location.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
});
}
I want that immediately after the view is clicked the progressbar will become visible. However, it donesn't become visable until all the code is finished, which is against the whole point.
WHy is this not happening right at the beginning of the click? I have put progressBar.setVisibility(View.VISIBLE) at the top, why is it only executed after all the code is done, which sometimes takes a few seconds.
Thanks very much.
This is because you are trying to do your work on the UI thread - the UI will not actually be updated at all until this method finishes.
Try changing up your call to this:
public void onClick(View view) {
progressBar.setVisibility(View.VISIBLE);
progressBar.post( new Runnable() {
public void run() {
// long running code that has UI interactions
}
});
}
This will show the view immediately, and submit the runnable - long running task - to the message queue; this task will be run on a background thread that can still manipulate the UI, but will not cause it to hang.
I have created an android apps that using async task to call web service,
when authentication fail, user will stop current activity and redirect back to login page.
My problem is when user redirect back to login page, a toast text still showing, this toast text is under async thread onPostExceute() event.
any solution for this problem?
in the webService.cs
catch (UnauthorizedException ua) {
Log.d(tag, ua.getMessage());
Intent intent = new Intent(activity, LoginActivity.class);
if(condition a){
intent.putExtra("toast_text", R.string.a);
}else{
intent.putExtra("toast_text", R.string.b);
}
activity.finish();
activity.startActivity(intent);
}
return null;
then in asyncTask.cs
protected JSONArray doInBackground(String... parameters) {
ConnectivityManager cm =
(ConnectivityManager) SingleFormActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if (isConnected) {
}
return null;
}
public void onPostExecute(JSonArray result){
if(result != null){
}else{
Toast.makeText(Something.this, R.string.b, Toast.LENGTH_LONG).show();
}
}
you can Use
Create Toast like
Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
and before calling finish() cancel toast using below code
if (toast != null )
toast.cancel();
Try like this
Return request status from doInBackground.and show toast using that status in onPostExecute
may be there is any syntax error in this code.But i hope it help you
public class AsyncConnectTask extends AsyncTask<Void, Void, Boolean> {
private MyInterface mListener;
public AsyncConnectTask(Context context, String address, String user,
String pass, int port, MyInterface mListener) {
}
#Override
protected Boolean doInBackground(Void... params) {
....
return result;
}
#Override
protected void onPostExecute(Boolean result) {
if (result == true) {
//Show toast here
}else{
}
}
}
In onPause() add below code
if(isFinishing()){
if (toast != null || toast.getView().getWindowVisibility() == View.VISIBLE) {
toast.cancel();
}
}
when authentication fail, user will stop current activity and redirect back to login page.
with your above question, I assume you got two different activity (one for login and another for doing something also showing the toast message. If its correct then before showing the toast check if the activity is finishing if not then show the toast.
if(!isFinishing()){
// show toast
}
http://developer.android.com/reference/android/app/Activity.html#isFinishing%28%29
Maybe the code kind of shows what I'm attempting to do, so I'll start with that
private void getLicenseResults() {
if (licensed && didCheck == true) {
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent openStartingPoint = new Intent(
"***.MAINACTIVITY");
startActivity(openStartingPoint);
finish();
}
}
};
timer.start();
}
if (didCheck == false) {
Toast.makeText(Splash.this, "Checking License, Please Wait",
Toast.LENGTH_LONG).show();
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
getLicenseResults();
Log.i("LICENSE", "re-checking");
}
}
};
timer.start();
}
}
I ran the license check without trying to loop it before, and it worked except if the checking took more than a couple seconds it skipped over the
if (licensed && didCheck == true)
and the activity just kind of stood and waited without launching my main activity (this check is on the splash screen).
So I want the "if didCheck = true" part to be called only after didCheck is in fact finally true. I'm sure there's an easy solution, but I'm self-taught and I have no experience with loops or callbacks(?).
Thank you for any help!
You are not setting didCheck to true in your second if statement before the call to getLicenseResults
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android - detect whether there is an Internet connection available
this is the code to check the internet availability on android device:
public boolean isInternetAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo() != null)
return cm.getActiveNetworkInfo().isConnected();
else
return false;
}
So this code is working correctly if no wifi or network available.
But if device is connected to wifi network but internet is not available then what should i do to check the internet is there or not?
any suggestion will be appreciated.
I do it like this:
I try to reach google.com and watch for response:
public static void isGoogleAvailable(final Handler handler)
{
new Thread()
{
private boolean hasGoogleResponded = false;
#Override
public void run()
{
new Thread()
{
#Override
public void run()
{
HttpGet requestForTest = new HttpGet("https://www.google.com/");
try
{
new DefaultHttpClient().execute(requestForTest);
hasGoogleResponded = true;
}
catch (Exception e)
{}
}
}.start();
try
{
int waited = 0;
while(!hasGoogleResponded && (waited < 60000))
{
sleep(100);
if(!hasGoogleResponded )
{
waited += 100;
}
}
}
catch(InterruptedException e)
{}
finally
{
if (hasGoogleResponded)
{
handler.sendEmptyMessage(1);
}
else
{
handler.sendEmptyMessage(0);
}
}
}
}.start();
}
Then I retrive messages in my handler:
Handler internetHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
if (msg.what == 1) //connected
{
}
else //not connected
{
}
}
};
I hope this helps.
You could try to ping a server like google (that should always exist)
see this topic
You can try
ConnectivityManager m;
m.getAllNetworkInfo();
First check internet connection,then others.
But sometimes its depends on app architecture.
If application needed wifi and you havent - you can not check internet because
it is not necessary
I’m a android developer beginner, so I want to put 2 threads running simultaneously in background (or not), one is for testing Wifi connectivity, and another for timeout respond with progress bar( or another thing for showing that application is not dead), in “main” I want to waiting, if wifi testing is faster than timeout, send user for one page, if timeout ran out, send user for different page.
I already have to threads, one doing timeout+progressBar and other checking connectivity, my problem is who to waiting for the fast thread that end, I tried with a loop checking for thread.isalive(), but in that way progress bar doesn’t show, and the application frozen until some thread ends… =\
any help?! Sorry my bad english...
public void startProgress() {
Runnable r1 = new Runnable() {
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
public void run() {
progress.setProgress(value);
}
});
}
setContentView(R.layout.error_menu);
//finish();
}
};
Thread th1 = new Thread(r1);
th1.start();
Runnable r2 = new Runnable() {
// Setup the run() method that is called when the background thread
// is started.
public void run() {
// Do you background thread process here...
// Checking if WIFI is ON and IF URL is Reachable
if(isOnline()){
String URL_STR="http://10.0.1.2/ShopList_for_app.php";
try
{
URL url = new URL(URL_STR);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(7000); // This is time limit if the connection time limit
urlc.connect();
if (urlc.getResponseCode() == 200){
setContentView(R.layout.menu1);
//finish();//return;
}else{
//finish();//return;
}
}
catch (MalformedURLException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
//finish();//return;
}
catch (IOException e){
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
//finish();//return;
}
}else{
//finish();//return;
}
}
};
Thread th2 = new Thread(r2);
th2.start();
Toast.makeText(getBaseContext(), "..Correu todas as Threads..", Toast.LENGTH_LONG).show();
while(true){
if(th2.isAlive()){
//Toast.makeText(getBaseContext(),"checking...", Toast.LENGTH_LONG).show();
}else{
th1.interrupt();
setContentView(R.layout.menu1);
break;
}
if(th1.isAlive()){
//Toast.makeText(getBaseContext(),"checking...", Toast.LENGTH_LONG).show();
}else{
th2.interrupt();
setContentView(R.layout.error_menu);
break;
}
}
}