BACK Button is not working ,while progressDialog is running - android

I have a little problem; I hope you can help me.
While progressDialog is running, the user presses the BACK Button. The current Activity progressDialog goes to Background, but progressDialog is running.
My problem is that when the user clicks on the BACK button, progressDialog should be foreground Activity, stop current progress and ask "Do you want to continue or exit?"
If the user presses Continue, progressDialog should continue the remaining work.
Otherwise, close the current activity.
CODE HERE:
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
return true;
}
return super.onKeyDown(keyCode, event);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
progressDialog.setCancelable(true);
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}

You need to override back button event. You can do this as:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing()) {
Log.d(this.getClass().getName(), "back button pressed");//write your own logic here, Whatever you want to do
}
return super.onKeyDown(keyCode, event);
}

Well, I had the same issue. The simplest method that worked for me is using progressDialog.setCancelable(true).. This declares whether the dialog is cancelable by hitting the back key.. Try it and let me know if it works for you or not. Good luck

Similar issue , When progressDialog.setCancelable(true) is set then hitting back button does not execute code written in back button code but just cancels the progress dialog..Hitting the key again works.
i want to cancel the progress dialog and execute some piece of code together which is not working.
Clicking back button twice does not make sense to me.

You can use progressDialog.setCancelable(true) and then use progressDialog.setOnCancelListener() to provide the OnCancelListener to execute your code to be executed onCancel().
See the Android documentation on Dialogs.

Related

Android Background issues when user is in active state

I'm working on app which is required user in active feature like if user is not available on the application more than 15 min. it shows some popup on the last activity we used, when we click okay it redirects to login screen.
It is working absolutely fine when i opened back my app exactly after 15 minutes to around 30 minutes .
My problem is now, when i open my app after 45 min or more than 1 hour, it doesn't work, it doesn't show in activity popup. it just opened the last activity i used.
I tried with below code added in splash activity:
if (!isTaskRoot()
&& getIntent().hasCategory(Intent.CATEGORY_LAUNCHER)
&& getIntent().getAction() != null
&& getIntent().getAction().equals(Intent.ACTION_MAIN)) {
finish();
return;
}
Here is my BaseActivity class used for in active state checking
public class MyBaseActivity extends AppCompatActivity {
AlertDialog alertDialog;
Context context;
public static final long DISCONNECT_TIMEOUT = 900000; // 15 min = 15 * 60 * 1000 ms
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
LayoutInflater li = LayoutInflater.from(MyBaseActivity.this);
View promptsView = li.inflate(R.layout.acount_status_dialogue, null);
final TextView userInput = (TextView) promptsView.findViewById(R.id.txtTitle);
final TextView userInput1 = (TextView) promptsView.findViewById(R.id.txtTitle1);
userInput1.setText("USER IN-ACTIVE");
userInput.setText("Due to user is inactive from last 15 minutes. Please Login Again");
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MyBaseActivity.this,R.style.DialogLevelsStyle);
// set prompts.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//do things
Intent i = new Intent(MyBaseActivity.this, SignInActivity.class);
//i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
Constant.val = 1;
AccountUtils.setValue("1");
}
});
// create alert dialog
alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
// Perform any required operation on disconnect
}
};
public void resetDisconnectTimer(){
Log.i("Main", "Invoking logout timer");
//disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
Log.i("Main", "cancel timer");
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
if (Constant.isAppIsInBackground(this)) {
stopDisconnectTimer();
resetDisconnectTimer();
}else {
stopDisconnectTimer();
}
super.onStop();
//stopDisconnectTimer();
}
}
Please find out my issue. thanks in advance.
Save the current time when the user put your app to background (for example in SharedPreferences), and when the user starts again your app calculate the diff and show what you want on the screen.

Issue about the return value of activityStarting

Today I'm developing an App which can intercept the launch between activities, My key code is:
ActivityManagerNative.getDefault().setActivityController(new InterceptActivityController(), false);
private class InterceptActivityController extends IWeChatActivityController.Stub {
void InterceptActivityController() {}
#Override
public boolean activityStarting(Intent intent, String pkg) {
showDialog();
return false;
}
}
private void showBottomDialog() {
Log.d(TAG, "showBottomDialog");
Dialog bottomDialog = new Dialog(mContext);
View contentView = LayoutInflater.from(this).inflate(android.R.layout.simple_list_item_2, null);
bottomDialog.setContentView(contentView);
ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
layoutParams.width = getResources().getDisplayMetrics().widthPixels;
contentView.setLayoutParams(layoutParams);
bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
bottomDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
bottomDialog.show();
}
I defined a Button and planned to start an Activity after clicking it. But now I intercept this action and just show a dialog in the function of activityStarting and then return false, after dismissing this dialog, I click the button again, but nothing works, dialog doesn't show any more, Who knows the reason ? Maybe I think this is a google source bug, but I'm not sure.
You know the Dialogs need to be Shown in a Timely manner. I mean You need the Dialog to be Shown for How Long? When you Start showing a Dialog and Dismiss it, It's Not Destroyed, It's just Dismissed.
Look at the Code below. I wrote this in my own app, It's Safe. Try it and see if you're satisfied with it:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bottomDialog.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
for (int i = 0; i <= 1200; i++) {
Thread.sleep(100); //The time it takes to update i
if (i = 1200) {
bottomDialog.dismiss();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
You can use AsyncTask as well. Also, I put the whole thing in a Click Listener just to show how it can be used.
The idea is define a showing Time for the Dialog

Activity not destroying to release Heap in android?

I am trying to release heap size by destroying the current activity, while going to another activity.
I am using finish(); on backPreess()
But this is not releasing the heap.
on setContentView()
The heap size increases 16Mb. I want to release this increase in the heap after going to another activity. Can any one help how to do this?
My code is as following:
package com.stancil.levels;
public class PaintActivity extends ZebraActivity implements
PaintView.LifecycleListener, PaintView1.LifecycleListener1 {
private static final int REQUEST_PICK_COLOR = 1;
....
....
public PaintActivity() {
_state = new State();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Constants.context = getApplicationContext();
setContentView(R.layout.paint);
..................
...................
...............
}
public void onPreparedToLoad() {
// We need to invoke InitPaintView in a callback otherwise
// the visibility changes do not seem to be effective.
new Handler() {
#Override
public void handleMessage(Message m) {
new InitPaintView();
Log.v("PaintActivity", "After InitPaintView Called");
}
}.sendEmptyMessage(0);
}
private class InitPaintView implements Runnable {
private Bitmap _originalOutlineBitmap;
private Handler _handler;
public InitPaintView() {
// Make the progress bar visible and hide the view
_paintView.setVisibility(View.GONE);
_progressBar.setProgress(0);
_progressBar.setVisibility(View.VISIBLE);
_state._savedImageUri = null;
_state._loadInProgress = true;
_originalOutlineBitmap=_imageBitmap;
_handler = new Handler() {
#Override
public void handleMessage(Message m) {
switch (m.what) {
case Progress.MESSAGE_INCREMENT_PROGRESS:
// Update progress bar.
_progressBar.incrementProgressBy(m.arg1);
break;
case Progress.MESSAGE_DONE_OK:
case Progress.MESSAGE_DONE_ERROR:
// We are done, hide the progress bar
// the paint view back on.
_state._loadInProgress = false;
_paintView.setVisibility(View.VISIBLE);
_progressBar.setVisibility(View.GONE);
initiatePopupWindow();
break;
}
}
};
new Thread(this).start();
}
public void run() {
Log.v("Wasimmmmmmmmmmmmmmmm", "qqqqq 22");
_paintView.loadFromBitmap(_originalOutlineBitmap, _handler);
}
}
private static class State {
// Are we just loading a new outline?
public boolean _loadInProgress;
// The resource ID of the outline we are coloring.
//public int _loadedResourceId;
//
// If we have already saved a copy of the image, we store the URI here
// so that we can delete the previous version when saved again.
public Uri _savedImageUri;
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exit")
.setMessage("Do you want to go to Main Menu?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Constants.check_new=true;
Intent i=new Intent(PaintActivity.this,MainActivity.class);
// i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Do nothing.
}
}).show();
}
}
}
release yoru objects in onDestroy method, anyways, if there are no references to the detroyed activity, GC will automaticly clean up whenever its needed (it doesnt need to happen right after you closed your activity).
Alternatively theres a method to force running GC, but I wont even write about it cuz its not really a feature a typical application should use

ProgressDialog not showing up in activity

I am trying to include a ProgressDialog in my application. But it is not showing up.
Here's the code snippet where i use the ProgressDialog:
public class abcActivity extends Activity {
public boolean onOptionsItemSelected(MenuItem item) {
case XYZ:
ProgressDialog dialog = ProgressDialog.show(abcActivity.this, "", "Please wait for few seconds...", true);
callSomeFunction();
dialog.dismiss();
showToast(getString(R.string.SomeString));
break;
}
}
Does anyone know why the dialog is not showing up? Any clues?
I think your code is wrong in a sense that you do all in the UI thread. You have to put callsomefunction() into a background thread.
public void runSomething()
{
showDialog(BACKGROUND_ID);
Thread t = new Thread(new Runnable()
{
public void run()
{
//do something
handler.post(finishThread);
}
});
t.start();
// The progress wheel will only show up once all code coming here has been executed
}
And as well
protected Dialog onCreateDialog(int id)
{
if(progressDialog == null) progressDialog = new ProgressDialog(this);
return progressDialog;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog)
{
if(id == BACKGROUND_ID)
{
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.setMessage("running for long ...");
}
}
Runnable finishThread = new Runnable()
{
public void run()
{
//long running
if(progressDialog != null) progressDialog.dismiss();
}
};
i think issue is in your switch condition pls verify it.
here is another method to display dialog in android try this.
public static final int DIALOG2_KEY = 1;
public static ProgressDialog dialog1;
showDialog(DIALOG2_KEY); // use it where you want to display dialog
dialog1.cancel(); // use it to cancel the dialog
#Override
public Dialog onCreateDialog(int id) {
if (id == 1) {
dialog1 = new ProgressDialog(this);
dialog1.setMessage("Please wait...");
dialog1.setIndeterminate(true);
dialog1.setCancelable(true);
}
return dialog1;
}
Ensure you have this code called by debugging or adding a log. The code seems right to me.
Also, if you want to perform some operations in background and show a progress dialog while the performing, please use AsyncTask with ProgressDialog bounded, like here.
ProgressDialog is deprecated in Android O , Use ProgressBar now.

Back button functionality not working while running my Android program

My program is working properly, but in the middle of the program running, user clicks on the BACK button, and the functionality of the back button does not work. But after completing the executing, BACK button functionality is working.
please observe my code here.
package com.sampleexample;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("SampleExample", "======= onCreate()====Start====");
// Setup the button that starts the progress dialog
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("SampleExample", "======= onClick()==Start======");
showDialog(PROGRESS_DIALOG);
Log.d("SampleExample", "======= onClick()===End=====");
}
});
Log.d("SampleExample", "======= onCreate()====End====");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
Log.d("SampleExample", " ------- Back Button onKeyDown()----Start--");
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
Log.d("SampleExample", " ------BackButton-onKeyDown()----End--");
return true;
}
return super.onKeyDown(keyCode, event);
}
// Toast.makeText(SampleExample.this, "U have pressed the Back Button",
// Toast.LENGTH_SHORT).show();
// Log.d(this.getClass().getName(),
// "*********back button pressed----------");
protected Dialog onCreateDialog(int id) {
Log.d("SampleExample", "99999 onCreateDialog () 999 Start");
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d("SampleExample", "8888 handleMessage () 8888 Start");
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
// Toast.makeText(SampleExample.this, "Download is completed",
// Toast.LENGTH_SHORT).show();
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
Log.d("SampleExample", "7777 run () 7777 Start");
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}
You haven't really explained the symptoms of your problem clearly, but from your code it appears that you are kicking off a background thread and popping up a ProgressDialog. I am assuming that it is while this is running that you are attempting to press the BACK key. The reason that this does not appear to do anything is that a Dialog is by default not cancelable using the BACK key. You have to call setCancelable(true) to enable this behaviour.
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
...
return progressDialog;
This will allow the ProgressDialog to be cancelled with the BACK button. However your background Thread will continue to run, even if the Dialog has been cancelled.
// handle phone back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return quitWithPID();
}
return super.onKeyDown(keyCode, event);
}
// reusable method (modifier may be public..)
private boolean quitWithPID() {
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit Boot Options?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Exit the activity
MainActivity.this.finish();
// Terminate the process ;)
android.os.Process.killProcess(android.os.Process.myPid());
}
}).show();
return true;
}
chandu Did you checked your logic before posting the question
Recheck the below code in your handler
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
your code won't reach dismissDialog until total >= 100 & hence even whilst the program you are unable to useyour BACK's Action
& also please stop posting multiple questions

Categories

Resources