I want to have the possibility of cancel the load of current Android MediaPlayer URL when pressing back button (onBackPressed) and quit to the previous activity as if there was nothing.
This all happens while Activity loads.
onCreate has a ProgressDialog call. I want to cancel this dialog, cancel the creating/starting MediaPlayer and go back.
How to make it correctly?
#Override
public void onBackPressed() {
if (pd!=null) {if (mp3Service!=null) mp3Service.reset(getApplicationContext()); pd.onBackPressed();};
super.onBackPressed();
}
This doesn't work, moreover, in some time the screen begins to darken and hang the APP.
What's wrong, maybe I must call another thread? (playSong launches in separate thread).
If your progress dialog is visible then you need to override its onBackPressed method to handle the event:
pd = new ProgressDialog(this) {
public void onBackPressed() {
dismiss();
mediaPlayer.stop();
}
};
pd.setTitle("Loading");
pd.setMessage("Please Wait..");
pd.setIndeterminate(true);
pd.setCancelable(false);
pd.show();
You could either try to check for OnCancelListenerin your dialog to the detect if your dialog has been canceled. Or you can try something like this
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
//Do your code here for canceling your service
return true;
}
return super.onKeyDown(keyCode, event);
}
When you create your dialog, you can add a cancel listener:
pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO cancel your music service
}
})
Related
First thing I want to say, this was done by seeing a tutorial. Here is the Custom Alert Dialog activity part I am calling from a broadcast receiver. The only problem is the back button click. Once the Alert dialog activity got started, when I press the back button it is getting closed.
public class AlertDialogActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setFinishOnTouchOutside(false);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
setContentView(R.layout.activity_inmsgdialog);
}
#Override
public void onBackPressed()
{
super.onBackPressed();
Toast.makeText(getApplicationContext(), "Back Pressed", Toast.LENGTH_SHORT).show();
}
}
I have tried onBackPressed and I'm able to see the toast message but the activity is getting closed.
See here:
#Override
public void onBackPressed()
{
super.onBackPressed(); //Remove this line
Toast.makeText(getApplicationContext(), "Back Pressed", Toast.LENGTH_SHORT).show();
}
Do not call super.onBackPressed(); code if you want to disable back button for activity. So remove this line. Hope it helps.
You can use the below option to handle back button press
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//your code
return true;
} else {
}
}
Don't propagate the event and you should be good.
#Override
public void onBackPressed()
{
//don't call super
}
I am using ProgressDialog in AsyncTask. And If user Press Back Button, then AsyncTask will be cancelled, current fragment will replace by any other Fragment.
There is no issue if user is still on Application. Bu if he goes back and back speedly and at last stop application, It gives error IllegalStateException: Fragment not attached to Activity.
How to solve this ?
My Code:
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(getActivity(), "", "Loading...", true,
true, new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
CancelDialog();
}
});
}
public void CancelDialog() {
new FetchData().cancel(true);
for (int i = 0; i < fm.getBackStackEntryCount(); ++i) {
fm.popBackStack();
}
((FrameLayout) flMain).removeAllViews();
fm.beginTransaction().add(R.id.frame, new Home()).commit();
}
Home.java:
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
getView().clearFocus();
getActivity().finish();
return true;
}
return false;
}
});
}
After so many tried, lastly I have found Simple Answer: isAdded()
It will Return true if the Fragment is currently added to its Activity.
I used below code and it solved my problem.
#Override
protected void onPostExecute(Void result){
if(isAdded()){
// Code to display Data...
}
}
You should be careful when to call e.g getActivity() - your fragment might not (yet/already) be attached to an activity when you call such methods. Check out this.
Alternatively you can save the Activity instance when onAttach is called, but then you'll have to be careful what you do with that Activity instance, so that you do not make conflicting updates with another Fragment that is actually still attached.
isAdded and isDetached can be useful to check the state and avoid calling invalid methods.
So I'm currently developing a turn based game app. And it displays toasts from a view on who's turn it is after each turn is taken. What's weird though, is if I hit the back button it will go back to the main menu(previous activity) but the toasts will still linger till they time out. Also if I hit back twice and it goes to the home screen, the toasts will still show until they finish. I want to implement a check or some way to cancel those toasts when the back button is pressed. I have to do this in my view too, my view contains all the toasts and all the code to the game, the gameActivity only has onCreate to create the view for the game. Any ideas?
In your Activity you have override method:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
// do something
yourView.notifyBackPressed();
return false;
}
return super.onKeyDown(keyCode, event);
}
And in your View you have to implement method, for example notifyBackPressed().
Try This...
Try to use Toast.LENGTH_SHORT or
You should set duration (milliseconds) for custom Toast like this.
Custom toast:
LayoutInflater inflater = getActivity().getLayoutInflater();
View layoutToast = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) getActivity().findViewById(R.id.toastcustom));
((TextView) layoutToast.findViewById(R.id.texttoast)).setText("I'm custom toast");
final Toast myToast = new Toast(
(EmployerNominationView) getActivity());
myToast.setView(layoutToast);
myToast.setDuration(300);
myToast.setGravity(Gravity.BOTTOM, 0, 45);
myToast.show();
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
myToast.cancel();
}
}, 1000);
Generate Toast
Toast toast;
toast = Toast.makeText(getBaseContext(), "Messages", Toast.LENGTH_LONG);
toast.show();
Cancel the Toast you may use onKeyDown() or onBackPressed() .
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
toast.cancel();
return true;
}
return super.onKeyDown(keyCode, event);
}
//Try with making Toast Global and cancel the toast on Back Pr
Toast mToast = new Toast(ApplicationContext);
public void onBackPressed(){
mToast.cancel();
}
I found this and will hellp you
Android AppMsg (Crouton) Library
Implementation of in-layout notifications. Based on Toast notifications.
I try the below method to detect the back button pressed on the action bar in activity by the first method and the second one is used to detecting the mobile hardware button back or kill activity button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
setResult(RESULT_CANCELED);
super.onBackPressed();
}
How can I specifically override just the back button while within a dialog to finish the entire activity and not just the dialog.
Using setOnCancelListener and setOnDismissListener do not work because there are other times that I simply close the dialog without closing the whole activity behind it.
Edit
Thanks Shubayu that may work!
I was also able to access just the back button in a dialog through this function.
dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK){
finish();
}
return false;
}
});
Override
public void onBackPressed ()
of the activity and put in the way you want the behavior in it. Also set a boolean from your dialog which you use inside onBackPressed() of the Activity. if the boolean is true, run the disabling part of the onBackPressed() code else don't.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK){
// your logic goes here
return true;
}
return super.onKeyDown(keyCode, event);
}
use the above code::
You can use : dialog.setOnCancelListener(.....)
first set dialog.setCancelable(true);
than you can place below code :
dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
#Override
public void onCancel(DialogInterface dialog)
{
// add code backpress
}
});
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.