Exit from application from home screen and close it - android

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

Related

Hold a Socket.IO Connection throughout Application while it in running foreground or background

I have made my one to one and group chat application using socket.io , everything is working fine , but If I am interacting with UI it establish the connection but after some time when I stop interacting with the application then the connect break and user goes offline as I am not using any event for putting my user offline. Can anyone help me in this.
public SocketConnection() {
{
try {
nSocket = IO.socket(Constants.NAME_SPACE);
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
public Socket getSocket(){
return nSocket;
}
this is where I am putting my user online.
public class SplashActivity extends ActivityManagePermission {
String permissionAsk[] = {PermissionUtils.Manifest_CAMERA
, PermissionUtils.Manifest_WRITE_EXTERNAL_STORAGE
, PermissionUtils.Manifest_READ_EXTERNAL_STORAGE
};
Context context = SplashActivity.this;
private JSONObject mJson;
SessionManagement session;
private Socket mSocket;
int SPLASH_TIME_OUT = 2000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new SessionManagement(context);
/**
* Creating the socket connection.
*/
SocketConnection obj = new SocketConnection();
try {
mSocket = obj.getSocket();
} catch (URISyntaxException e) {
e.printStackTrace();
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
askCompactPermissions(permissionAsk, new PermissionResult() {
#Override
public void permissionGranted() {
if(session.isSignedIn()) {
mJson = new JSONObject(); //creating json object
Object type = "M";
Object ID_USER = session.getUserDetails().get(SessionManagement.USER_ID);
try {
mJson.put("userId", ID_USER);
mJson.put("connection_type",type);
}catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit(Constants.event_new_user_online,mJson.toString());
mSocket.connect();
Intent i = new Intent(context,HomeActivity.class);
startActivity(i);
finish();
}else {
Intent i = new Intent(context, LoginActivity.class);
startActivity(i);
finish();
}
}
#Override
public void permissionDenied() {
Intent i = new Intent(context, SplashActivity.class);
startActivity(i);
finish();
}
#Override
public void permissionForeverDenied() {
Toast.makeText(context,
"Please allow the permissions"
,Toast.LENGTH_SHORT).show();
startActivity(new Intent(context,SplashActivity.class));
}
});
}
}, SPLASH_TIME_OUT);
}
}
You need to use Socket IO options.
IO.Options options = IO.Options()
options.setTimeout(60000L) // 60 seconds
options.setReconnection(true)
and then use it like this while making a connection.
nSocket = IO.socket(Constants.NAME_SPACE, options);

Thread dosen't interrupted

I'm work on crate server and android client
but thread doesn't interrupted by android client
My android Client has request for the RoomList from server
and Server receive, Client Accept
and fill in my ListView used the Adapter
here's problem if Click backButton,
than RoomListAcitivity was close and thread was stop
but thread dosen't stop just alive in my app
first Enter has work on sucessfully
but Press BackButton on and re-Enter this Activity
MyApp just White, No Action
how can i stop this thread?
(and sorry for my English skill...)
i tried .interrupt() method , and handler.removeMessages(0)
but failed thread keep alive
upload this full java code just in case...
ListView roomList;
RoomAdapter roomAdapter;
Socketservice ss;
String msg,rtitle;
String msgs[];
String list[];
Thread listthread,EnterRoomThread,removeV;
boolean staterun = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_room);
roomList = findViewById(R.id.roomList);
roomAdapter = new RoomAdapter();
listthread = new Thread() {
public void run(){
ss.out.println("163|");
ss.out.println("100|");
try {
while (staterun == true) {
msg = ss.in.readLine();
handler.post(new Runnable() {
public void run() {
msgs = msg.split("\\|");
String protocol = msgs[0];
switch (protocol) {
case "163":
list = msgs[1].split(",");
for (int i = 0; i < list.length; i++) {
String list1[] = list[i].split("-");
String listT = list1[0];
int listC = Integer.parseInt(list1[1]);
int listI = Integer.parseInt(list1[2]);
roomAdapter.CreateRoom(listI, listT, listC);
}
roomList.setAdapter(roomAdapter);
msg = "";
msgs = null;
break;
case "200":
Intent i = new Intent(getApplicationContext(), GameWaitingActivity.class);
i.putExtra("tname", rtitle);
staterun = !staterun;
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
startActivity(i);
finish();
break;
case "201":
Toast.makeText(getApplicationContext(), "방이 꽉 찼습니다.", Toast.LENGTH_SHORT).show();
break;
}
}
});
}
} catch (IOException e) {
}
}
};
listthread.start();
roomList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Room item = (Room) roomList.getItemAtPosition(position);
rtitle=item.getTitle();
EnterRoomThread = new Thread() {
public void run() {
ss.out.println("200|" + rtitle);
EnterRoomThread.interrupt();
}
};
EnterRoomThread.start();
}
});
}
Handler handler = new Handler();
#Override
public void onBackPressed() {
removeV = new Thread() {
public void run(){
ss.out.println("101|");
removeV.interrupt();
}
};
removeV.start();
handler.removeMessages(0);
staterun = false;
listthread.interrupt();
Toast.makeText(getApplicationContext(),""+listthread.isAlive(),Toast.LENGTH_SHORT).show();
finish();
}
}
Go ahead with this, write this inside run() method
//use this boolean value to keep track.
boolean shouldRunFlag = true;
while (shouldRunFlag) {
try {
Thread.sleep(10);
//Do your work............
} catch (Exception e) {
e.printStackTrace();
Log.v(TAG, "Interrupted Exception caught");
// change the flag, so that while loop can be broken.
shouldRunFlag = false;
Log.v(TAG, "run: breaking the loop");
break;
}
}
and this is how you interrupt and clean the thread
private void interrupt(Thread currentThread) {
Log.i(TAG, "interrupt");
if (currentThread != null) {
Thread dummyThread = currentThread;
dummyThread.interrupt();
currentThread = null;
}
}

Check Internet during SplashScreen

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

Automatic Login Always Returns Null

At present, the login of my app prompts a user with an input for username and password and then submission of a button to send the info to the service and my server:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
/*
* Start and bind the imService
*/
startService(new Intent(LoggingIn.this, MessagingService.class));
usernameText = (EditText) findViewById(R.id.username);
passwordText = (EditText) findViewById(R.id.password);
loginButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (imService == null) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_service,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_SERVICE);
return;
} else if (imService.isNetworkConnected() == false) {
Toast.makeText(getApplicationContext(),
R.string.not_connected_to_network,
Toast.LENGTH_LONG).show();
// showDialog(NOT_CONNECTED_TO_NETWORK);
} else if (usernameText.length() > 0
&& passwordText.length() > 0) {
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
usernameText.getText().toString().trim(),
passwordText.getText().toString().trim());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
/*
* if result not equal to authentication failed,
* result is equal to friend and group list of
* the user 0: is for friends, 1: is for groups
*/
handler.post(new Runnable() {
public void run() {
// If log in successful, then save
// username and password to shared
// preferences:
SaveSharedPreference.setUserName(
getApplicationContext(),
usernameText.getText()
.toString());
SaveSharedPreference.setPassword(
getApplicationContext(),
passwordText.getText()
.toString());
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
} else {
/*
* Username or Password is not filled, alert the user
*/
Toast.makeText(getApplicationContext(),
R.string.fill_both_username_and_password,
Toast.LENGTH_LONG).show();
// showDialog(FILL_BOTH_USERNAME_AND_PASSWORD);
}
}
});
Which works just fine. What I wish to implement is the automatic login of a user given they have already logged in and thus the username and password is stored in shared preferences.
So when they access the app again, it should auto log them in as:
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
imService = ((MessagingService.IMBinder) service).getService();
if (imService.isUserAuthenticated() == true) {
Intent i = new Intent(LoggingIn.this, MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
}
public void onServiceDisconnected(ComponentName className) {
imService = null;
Toast.makeText(LoggingIn.this, R.string.local_service_stopped,
Toast.LENGTH_SHORT).show();
}
};
startService(new Intent(LoggingIn.this, MessagingService.class));
final String userName = SaveSharedPreference.getUserName(getApplicationContext());
final String password = SaveSharedPreference.getPassword(getApplicationContext());
Thread loginThread = new Thread() {
private Handler handler = new Handler();
#Override
public void run() {
String result = null;
try {
result = imService.authenticateUser(
userName.trim(),
password.trim());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (result == null
|| result.equals(AUTHENTICATION_FAILED)) {
/*
* Authenticatin failed, inform the user
*/
handler.post(new Runnable() {
public void run() {
Toast.makeText(
getApplicationContext(),
R.string.make_sure_username_and_password_correct,
Toast.LENGTH_LONG).show();
// showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
}
});
} else {
handler.post(new Runnable() {
public void run() {
Intent i = new Intent(LoggingIn.this,
MainActivity.class);
startActivity(i);
LoggingIn.this.finish();
}
});
}
}
};
loginThread.start();
The users info is successfully stored in shared preferences, but upon executing this code block, it always returns NullPointerException on line:
result = imService.authenticateUser(
userName.trim(),
password.trim());
In the try {} catch block.
I have attempted placing a timer within the app that perhaps the service does not have time to boot up, but even after 20+ sec that still does not work.
How can I get the automatic login work and not return?
UPDATE NOTE: private Manager imService; is an interface as:
public interface Manager {
public boolean isNetworkConnected();
public boolean isUserAuthenticated();
}

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