Show progress bar while reconnecting to internet - android

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.

Related

Trouble expanding image in samsung s8

As screen height of samsung s8 is quite large.My images in LoginUI(attached) were looking small.I calculated phone's height in dp programmatically.
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
float dpHeight = displayMetrics.heightPixels / displayMetrics.density;
Log.d("checkheightdp",dpHeight+"");
It gave me dpheight 692.So,I create a separate layout-h692dp and put my layout with increased image height.For some reason,It is still picking the default layout and hence image not expanding.
My code:
public class LoginActivity extends AppCompatActivity {
private EditText email, psd;
public ImageView deleteEmail;
public ImageView deletePsd;
public ImageView contactUs;
GlobalProvider globalProvider;
private int a = 0;
private Button sign_in_button, tourist_in_button;
private List<String> history = new ArrayList<String>();
private String usernameStr, newVersion = "x";
public static String character = "character";
private ConnectivityManager mConnectivityManager;
private NetworkInfo netInfo;
private ProgressDialog dialog;
public Thread thread;
private BroadcastReceiver myNetReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
netInfo = mConnectivityManager.getActiveNetworkInfo();
if (netInfo == null) {
Toast.makeText(LoginActivity.this, "网络链接不可用!", Toast.LENGTH_SHORT).show();
}
}
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
globalProvider = GlobalProvider.getInstance(LoginActivity.this);
IntentFilter mFilter = new IntentFilter();
mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myNetReceiver, mFilter);
//找到对象email、psd、sign_in_button并绑定监听事件
email = (EditText) findViewById(R.id.email);
psd = (EditText) findViewById(R.id.psd);
contactUs = (ImageView) findViewById(R.id.contact_us);
sign_in_button = (Button) findViewById(R.id.sign_in_button);
tourist_in_button = (Button) findViewById(R.id.tourist_in_button);
deleteEmail = (ImageView) findViewById(R.id.deleteEmail);
deletePsd = (ImageView) findViewById(R.id.deletePsd);
// gview=(GridView) findViewById(R.id.grid_layout);
// ImageAdapter imgAdapter=new ImageAdapter(LoginActivity.this);
//gview.setAdapter(imgAdapter);
contactUs.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(LoginActivity.this, ContactActivity.class);
startActivity(intent);
}
});
deleteEmail.setVisibility(View.GONE);
deletePsd.setVisibility(View.GONE);
try {
findHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
email.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deleteEmail.setVisibility(View.VISIBLE);
} else {
deleteEmail.setVisibility(View.GONE);
}
}
});
psd.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
deletePsd.setVisibility(View.VISIBLE);
} else {
deletePsd.setVisibility(View.GONE);
}
}
});
deleteEmail.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
email.setText("");
}
});
deletePsd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
psd.setText("");
}
});
sign_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (email.getText() == null || email.getText().toString().equals("") || psd.getText() == null || email.getText().toString().equals("")) {
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.notempty))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} else {
try {
setHistoryList();
} catch (IOException e) {
e.printStackTrace();
}
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginAction(v);
}
}
});
//为sign_in_button绑定监听事件,调用loginAction(v)
tourist_in_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog = new ProgressDialog(LoginActivity.this);
dialog.setMessage(getString(R.string.loging));
dialog.show();
sign_in_button.setEnabled(false);
loginActionTourist(v);
}
});
}
public static void setCharacter(Context context, String cha) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
editor.putString(character, cha);
editor.commit();
}
public static String getToken(Context context) {
SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
String cha = settings.getString(character, ""/*default value is ""*/);
//Log.v("err", tokenStr);
return cha;
}
//创建loginAction()方法
public void loginAction(View view) {
//分别把email、psd的值传递给usernameStr、passwordStr
final String usernameStr = email.getText().toString();
String passwordStr = psd.getText().toString();
Log.d("checkentries",usernameStr+" "+passwordStr);
setCharacter(this, "user");
// Log.d("chkpassword",passwordStr);
//GlobalProvider.getInstance().character =
Map<String, String> params = new HashMap<>();
params.put("password", passwordStr);
params.put("email",usernameStr );
CustomRequest jsonObjectRequest = new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
Log.d("responsevolley", response.getString("token"));
dialog.dismiss();
globalProvider.IsLoging = true;
sign_in_button.setEnabled(true);
String token;
token = response.getString("token");
token = token.replaceAll("\"", "");//把token中的"\""全部替换成""
Constants.setToken(LoginActivity.this, token);
globalProvider.isLogined=true;
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("errorvolley", error.toString());
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
sign_in_button.setEnabled(true);
}
});
globalProvider.addRequest(jsonObjectRequest);
}
public void loginActionTourist(View view) {
usernameStr = "guest#veg.com";
String passwordStr = "12345678";
setCharacter(this, "tourist");
globalProvider.isLogined = true;
// GlobalProvider.getInstance().character = "tourist";
// 绑定参数
Map<String,String> params = new HashMap();
params.put("email", usernameStr);
params.put("password", passwordStr);
CustomRequest customRequest=new CustomRequest(Request.Method.POST, loginUrlStr, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
dialog.dismiss();
globalProvider.IsLoging = true;
tourist_in_button.setEnabled(true);
String token;
try {
token = response.getString("token");
token = token.replaceAll("\"", "");
Constants.setToken(LoginActivity.this, token);
} catch (JSONException e) {
e.printStackTrace();
}
//把token中的"\""全部替换成""
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.putExtra("isLogin", usernameStr);
startActivity(intent);
//this.setResult(Activity.RESULT_OK);//为结果绑定Activity.RESULT_OK
finish();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
dialog.dismiss();
new AlertDialog.Builder(LoginActivity.this)
.setMessage(getString(R.string.errorId))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
tourist_in_button.setEnabled(true);
}
});
}
private void findHistoryList() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String s = null;
while ((s = br.readLine()) != null) {
history.add(s);
//System.out.println(arrs[0] + " : " + arrs[1] + " : " + arrs[2]);
}
if (history.size() > 0) {
email.setText(history.get(0));
psd.setText(history.get(1));
}
br.close();
isr.close();
fis.close();
}
public void setHistoryList() throws IOException {
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory().getAbsolutePath() + "/EasybuyCustomer.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write("");
bw.write(email.getText().toString());
bw.newLine();
bw.write(psd.getText().toString());
bw.newLine();
bw.close();
osw.close();
fos.close();
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
hideSoftInput(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}
private boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = { 0, 0 };
v.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
+ v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {
return false;
} else {
return true;
}
}
return false;
}
private void hideSoftInput(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//按下键盘上返回按钮
if(keyCode == KeyEvent.KEYCODE_BACK){
new AlertDialog.Builder(this)
.setMessage(getString(R.string.youconfirmtologout))
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
a=a+1;
finish();
}
}).show();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(myNetReceiver);
if(a>0){
System.exit(0);
}
a=0;
}
}
Finally I got my answer,why creating a separate height layout was not working.
Though screen height of samsung s8 is 692 dp,but 25dp is not available as It is used by system UI.
Apparently it was stated in developer.android.com.
The Android system might use some of the screen for system UI (such as the system bar at the bottom of the screen or the status bar at the top), so some of the screen might not be available for your layout.
Therefore,subtracting 25 dp from 692 gives 667dp.Creating layout-h667dp worked.
I went to this post.
https://medium.com/#elye.project/an-important-note-when-managing-different-screen-height-3140e26e381a

Set timeout function with AsyncTask [Android]

In my case, I would like to get the button pressed and get process with the timeout. When button clicked then it will verify the accNo with web services, if the verification (ProgressDialog) is over 5 seconds then it will stop and display the alertDialog to notice user "Timeout".
But now I have not idea when I in testing with 1 milliseconds, in logically it will pause in alertDialog until get pressed, but now it will display the dialog in milliseconds then auto dismiss and intent to next activity. Here is my code:
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information3);
btn_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (title.getText().toString().equals("INFO")) {
InfoAsyncTask infoAsyncTask = new InfoAsyncTask();
try {
infoAsyncTask.execute().get(1, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Verify Timeout. Please try again.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
});
}
private class InfoAsyncTask extends AsyncTask<Void, Void, String> {
private String results;
private ProgressDialog pDialog;
private Object resultRequestSOAP;
String accNo = et_accNo.getText().toString().trim();
int timeout = 15000;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(Information3.this);
pDialog.setMessage("Verifying...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(Void... params) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("Code", InfoCode);
request.addProperty("AccNo", accNo);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, timeout);
androidHttpTransport.debug = true;
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
String requestDumpString = androidHttpTransport.requestDump;
Log.d("request Dump: ", requestDumpString);
} catch (Exception e) {
e.printStackTrace();
}
try {
resultRequestSOAP = envelope.getResponse();
results = resultRequestSOAP.toString();
Log.d("Output: ", results);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
if (resultRequestSOAP == null) {
if (pDialog.isShowing()) {
pDialog.dismiss();
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Error ::");
alertDialog.setMessage("Connection error, please check your internet connection.");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
pDialog.dismiss();
}
} else {
if (results.equals("false")) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in correct account number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_billNo.getText().toString().trim().isEmpty()) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in bill number");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (et_amountNo.getText().toString().trim().isEmpty() || Integer.parseInt(et_amountNo.getText().toString().trim()) <= 0) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Information3.this);
alertDialog.setTitle(":: Warning ::");
alertDialog.setMessage("Please fill in amount");
alertDialog.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
} else if (results.equals("true")) {
Title = title.getText().toString();
String value1 = et_accNo.getText().toString().trim();
String value2 = et_billNo.getText().toString().trim();
int value3 = Integer.parseInt(et_amountNo.getText().toString().trim());
addSearchInput(value1);
addSearchInput(value2);
addSearchInput(String.valueOf(value3));
Intent intent = new Intent(Information3.this, confirmation3.class);
intent.putExtra("name", Title);
intent.putExtra("value1", value1);
intent.putExtra("value2", value2);
intent.putExtra("value3", value3);
startActivity(intent);
} else {
super.onPreExecute();
}
pDialog.dismiss();
}
}
}
get() method will block the UI thread and I guess you don't want this.
You should implement cancel mechanics in doInBackground and call AsyncTask.cancel() by timeout [like that](https://developer.android.com/reference/android/os/Handler.html#postDelayed(java.lang.Runnable, long))
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
AsyncTask.cancel();
}
}, 1);
Be aware there are many gotchas with AsyncTask, check my article.

android print "connection timeout" when timeout in loopj

android I finding more but none of get solution..
when occur time out in loopj , I want print Time-out message..
Follow code for time-out which I used.
private static final int DEFAULT_TIMEOUT = 15 * 1000;
private static AsyncHttpClient client = new AsyncHttpClient();
public static void setTimeOutTime() {
client.setTimeout(DEFAULT_TIMEOUT);
System.out.println("timeout");
}
try {
response = client.newCall(request).execute();
jsonObj = new JSONObject(response.body().string());
} catch (IOException e) {
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
if (getStatus() == Status.RUNNING) {
cancel(true);
if(!hiddenDialog) {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setTitle("Timeout error")
.setMessage("Sorry server doesn't response!\nCheck your internet connection and try again.")
.setCancelable(true)
.setPositiveButton("Try again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Log.d(TAG, "load again");
}
}).setIcon(R.drawable.ic_dialog_alert_dark);
AlertDialog alert = builder.create();
alert.show();
}
});
} catch (JSONException e) {}
EDIT
for your case it should be the same way
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// make toast
}
});

Create AlertDialog while holding a thread

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

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