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();
Related
When there is no internet, an alert dialog appear with cancel and retry button, and on retry button I am recursively calling newsResponse() method.
Now what I want is, on retry it should show progress dialog (means 5 seconds delay) and when there is no internet then again show alert dialog.
My Code.
public void newsResponse() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String str_response = response.toString();
News news = gson.fromJson(str_response, News.class);
news_list = news.getArticles();
newsListAdapter = new NewsListAdapter(NewsActivity.this, news_list);
newsGridAdapter = new NewsGridAdapter(NewsActivity.this, news_list);
progressBar.setVisibility(View.GONE);
listRecyclerView.setAdapter(newsListAdapter);
gridRecyclerView.setAdapter(newsGridAdapter);
if (isList) {
listRecyclerView.setVisibility(View.GONE);
} else {
gridRecyclerView.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (!checkInternet()) {
AlertDialog.Builder connectionBuilder = new AlertDialog.Builder(NewsActivity.this);
connectionBuilder.setMessage("Unable to load data!");
connectionBuilder.setCancelable(true);
connectionBuilder.setPositiveButton(
"Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
newsResponse();
}
});
connectionBuilder.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
});
AlertDialog alert11 = connectionBuilder.create();
alert11.show();
}
}
});
}
private boolean checkInternet() {
ConnectivityManager cm =
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
Add delay to your progess bar:
public void newsResponse() {
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
String str_response = response.toString();
News news = gson.fromJson(str_response, News.class);
news_list = news.getArticles();
newsListAdapter = new NewsListAdapter(NewsActivity.this, news_list);
newsGridAdapter = new NewsGridAdapter(NewsActivity.this, news_list);
progressBar.setVisibility(View.GONE);
listRecyclerView.setAdapter(newsListAdapter);
gridRecyclerView.setAdapter(newsGridAdapter);
if (isList) {
listRecyclerView.setVisibility(View.GONE);
} else {
gridRecyclerView.setVisibility(View.GONE);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (!checkInternet()) {
AlertDialog.Builder connectionBuilder = new AlertDialog.Builder(NewsActivity.this);
connectionBuilder.setMessage("Unable to load data!");
connectionBuilder.setCancelable(true);
connectionBuilder.setPositiveButton(
"Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
final ProgressDialog pDialog = new ProgressDialog(NewsActivity.this);
pDialog.setMessage("Loading...");
pDialog.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
pDialog.dismiss();
newsResponse();
}
}, 5000);
}
});
connectionBuilder.setNegativeButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
});
AlertDialog alert11 = connectionBuilder.create();
alert11.show();
}
}
});
}
private boolean checkInternet() {
ConnectivityManager cm =
(ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();
return isConnected;
}
It will show progress dialog for 5 seconds when you press retry button.
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);
}
}
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
...
}
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();
}
}
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.