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.
Related
I am new to the java as well as Android.
Data write is working ok as i seen it on the modsim terminal(modbus protocol terminal), query is also valid as the response is generated through terminal but most of the time data is not received in the socket.
Here is the expected work flow of the code.
after pressing read button writing thread is being called after some delay like 500ms read thread is called and after some delay for ensuring reading is complete process the data if valid query is received or not. what i observe is in the received buffer data is 0 but rec_count showing the value.
and chk_data is being called.
I have tried the handler postdelayed but some error generated as i call thread there.
Also m'i using the CounDowntimer correctly?
Please suggest the good approach to delay the function call
I have skip the some code routine as it gets the unnecessary attention.
here is the code,
write_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.setMessage("Wait...");
builder.setCancelable(false);
//Creating dialog box
final AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Data Writing!");
alert.show();
((Myapplication) getApplication()).setData_array( 10,1);
data_length = write_multiple_reg(output_array);
new Thread(new Write_Thread()).start();
start_timer3();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
alert.cancel();
}
}, 5000);
}
});
read_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.setMessage("Wait...");
builder.setCancelable(false);
//Creating dialog box
final AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("Data Read!");
alert.show();
data_length = holding_register(output_array);
new Thread(new Write_Thread()).start();
start_timer1();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 500ms
alert.cancel();
cancel_timer1();
start_timer2();
}
}, 5000);
}
});
}
void start_timer1(){
timer1 = new CountDownTimer(300,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
new Thread(new Read_Thread()).start();
//cancel_timer1();
}
};
timer1.start();
}
void cancel_timer1(){
if(timer1 != null)
{
timer1.cancel();
}
}
void start_timer2(){
timer2 = new CountDownTimer(1000,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
chk_data();
}
},500);
//cancel_timer2();
}
};
timer2.start();
}
void cancel_timer2(){
if(timer2 != null)
{
timer2.cancel();
}
}
void start_timer3(){
timer3 = new CountDownTimer(500,10) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
new Thread(new Read_Thread()).start();
start_timer2();
//cancel_timer3();
}
};
timer3.start();
}
void cancel_timer3(){
if(timer3 != null)
{
timer3.cancel();
}
}
class Thread1 implements Runnable {
#Override
public void run() {
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = socket.getOutputStream();
input = socket.getInputStream();
runOnUiThread(new Runnable() {
#Override
public void run() {
//tvMessage.setText("Connected\n");
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_LONG).show();
}
});
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Write_Thread implements Runnable {
#Override
public void run() {
try {
output.write(output_array,0,data_length);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Read_Thread implements Runnable {
#Override
public void run() {
while (true) {
try {
rec_count = input.read(input_array);
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
}
}
}
void chk_data()
{
if(rec_count!=0) {
rec_crc = crc_generate(input_array, (byte) (rec_count - 2));
rec_crc &= 0x0000FFFF;
rec_high_crc = (byte) (rec_crc >> 8);
rec_low_crc = (byte) rec_crc;
if ((rec_high_crc == input_array[rec_count - 1]) && (rec_low_crc == input_array[rec_count - 2])) {
if (input_array[1] == 0x03) //holding register response
{
copy_input_data(rec_count);
if(cnv_data[10]==2)
{
//write successful message
cnv_data[10]=0;
builder1.setMessage("Successful");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
else if(cnv_data[10]==1)
{
//write failed message
cnv_data[10]=0;
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
}
if(input_array[1] == 0x10)
{
data_length = holding_register(output_array);
new Thread(new Write_Thread()).start();
start_timer3();
}
} else {
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
builder1.show();
}
}
else
{
builder1.setMessage("Failed");
builder1.setCancelable(true);
builder1.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder1.show();
}
rec_count=0;
cancel_timer2();
}
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);
}
}
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();
}
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'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();