Answered and trusted look comments !
Thank sania
public class Test extends Activity {
HTML5WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebView = new HTML5WebView(this);
Intent i = getIntent();
String url = i.getStringExtra("url"); // retrieve the value you passed
if (savedInstanceState != null) {
mWebView.restoreState(savedInstanceState);
} else {
mWebView.loadUrl(url); // use that value
}
setContentView(mWebView.getLayout());
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
Intent myIntent = new Intent(Test.this, fragment_main.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);// clear back stack
startActivity(myIntent);
finish();
return;
}
}
how can I stop last activity when clicked back button ? I was made a vimeo app working with listview how can I stop and close (vimeo videoplayer.class) that activity.when I click back button its going first activity or showing message Application was stopped :/
Add ondestroy () or video.stop() methods in backkey method
Related
I am using a CountDownTimer in a Fragment and trying to stop it if the user hit the physical back button in the phone. I have tried overriding onPause, onDestroy, onStop, onDestroyView but nothing seems to be working. Kind of lost here. Can some one give me a pointer here?
public class Foo extends Fragment {
CountDownTimer myTimer;
#Override
public void onStop() {
super.onStop();
myTimer.cancel();
}
#Override
public void onPause() {
super.onPause();
myTimer.cancel();
}
#Override
public void onDestroyView() {
super.onDestroyView();
myTimer.cancel();
}
#Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
}
#OnClick(R.id.btn_greenleft_no)
public void goBack() {
myTimer.cancel();
Objects.requireNonNull(getActivity()).onBackPressed();
}
#OnClick(R.id.btn_greenright_yes)
public void showSuccess(View view) {
markAll();
myTimer.cancel();
(new MusicPlayer()).playSound(getContext(), "cheers.mp3");
final Snackbar snackbar = Snackbar.make(snackBarView, R.string.congratulations, Snackbar.LENGTH_SHORT);
snackbar.show();
myTimer.cancel();
}
private void startTimer(final View view) {
int Seconds = 5;
myTimer = new CountDownTimer(Seconds * 1000 + 1000, 1000) {
public void onTick(long millisUntilFinished) {
String rem = String.valueOf(millisUntilFinished / 1000);
Log.d("APP_DEBUG", "Timer: " + rem);
}
public void onFinish() {
goBack();
}
}.start();
}
}
Here is my 2 cents. Fragment doesn't have an onBackPressed() method which is present in the Activity class. It gets called when physical back button is pressed by the user. Here is what docs says:
Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.
What you can do is override the onBackPressed() method in the parent activity of your Foo fragment, then using an interface communicate to the fragment that back button was pressed by the user. Inside the fragment you can have the desired code to cancel the timer. This answer in the question How to implement onBackPressed() in Fragments? can help with sample code.
Try to modify onBackPressed in Your fragment's parent activity.
#Override
public void onBackPressed() {
// I assume this is the way how You add fragment to fragment manager
//getSupportFragmentManager().beginTransaction().replace(android.R.id.content, Foo.getInstance(), Foo.TAG).commit()
// Find fragment by its string TAG and when You get it, call to stop countDownTimer
Foo foo = (Foo) getSupportFragmentManager().findFragmentByTag(Foo.TAG);
if (foo != null) {
foo.stopCountDownTimer();
}
super.onBackPressed();
}
Next step is to declare in Your Foo fragment two things:
public static final String TAG = "Foo";
and
public void stopCountDownTimer() {
myTimer.cancel();
}
For fragment you cant use onBackPressed method, Instead please use this code
#Override
public void onResume() {
super.onResume();
if (getView() == null) {
return;
}
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
myTimer.cancel();
return false;
}
return true;
}
});
}
You have to call countDownTime.finish() as well. I have used it and it works for me.
#Override
public void onDetach()
{
super.onDetach();
if (countDownTimer != null)
{
countDownTimer.cancel();
countDownTimer.onFinish();
}
}
have you tried onBackPressed()
#Override
public void onBackPressed() {
super.onBackPressed();
myTimer.cancel();
myTimer =null;
}
Have you tried adding an OnKeyListener in your fragment like this:
Here "view" is the parent layout of your fragment , the one that hosts the timer.
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(tag, "keyCode: " + keyCode);
if( keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
myTimer.cancel();
return true;
}
return false;
}
});
I want to implement the function : if user dosen't checked the autoLogin CheckBox, clear the login user information and logout when the application is quit normally or force closed(clean the memeory).
I write the code clearAutoStart() to clear user information both in finish() and OnDestory().
When the user press back button twice, the finish() will execute, and will logout success. But as you know, if the application force closed, OnDestory() will not execute all the time. So in this situation, it will not logout success.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
exitBy2Click(); //quit normal
}
return false;
}
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (isExit == false) {
isExit = true;
Toast.makeText(this, "press again to quit", Toast.LENGTH_SHORT).show();
tExit = new Timer();
tExit.schedule(new TimerTask() {
#Override
public void run() {
isExit = false;
}
}, 2000);
} else {
finish();
System.exit(0);
}
}
#Override
protected void onDestroy() {
clearAutoStart();
super.onDestroy();
}
#Override
public void finish() {
clearAutoStart();
super.finish();
}
#Override
protected void onStop() {
Log.i("ws", "---->>SmarterActivity onStop");
super.onStop();
}
public void clearAutoStart() {
RememberUser rememberUser = RememberUser.getInstance();
if (rememberUser.getIsAutoStart() == false) {
Log.i("ws", "---->>clearAutoStart getIsAutoStart false ");
UserLocalStore userLocalStore = UserLocalStore.getInstance();
userLocalStore.setUserLoggedIn(false);
userLocalStore.clearUserData();
Log.i("ws", "---->>clearAutoStart getIsAutoStart false OK ");
} else {
Log.i("ws", "---->>clearAutoStart getIsAutoStart true ");
}
}
I try to add the clearAutoStart() in onStop(), but this means if I press the HOME button , the application will logout.
When you press HOME onPause() is called and then onStop().
So you can put a member variable that keep the track of what is happening:
#Override
protected void onPause() {
mIsPause = true;
super.onPause();
}
#Override
protected void onStop() {
Log.i("ws", "---->>SmarterActivity onStop");
if(!mIsPause)
clearAutoStart();
super.onStop();
}
I am playing HTML 5 Video in activity that is working fine, but when i press back button get exit from the activity and slide(Video contains by slides) but sound is still playing in background of that particular slide until it gets finish. How can i stop that sound while pressing the back button get exit completely form the activity.
here is my code when i press back button:
#Override
protected void onPause() {
super.onPause();
mWebView.stopLoading();
}
#Override
public void onStop() {
super.onStop();
mWebView.stopLoading();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.inCustomView()) {
mWebView.hideCustomView();
mWebView.stopLoading();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
if (mWebView.isFocused() && mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
activity.finish();
}
}
}
Put below line in your onStop() method:
mWebView.destroy();
Try mWebView.destroy() or maybe load some dummy URL.
Like:
#Override
public void onBackPressed() {
if (mWebView.isFocused() && mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
activity.finish();
mWebView.destroy();
}
}
I have a splash activity that is displayed for 2 seconds before opening the main activity.
If the user presses the back button while the splash activity is being displayed, the splash activity closes. But a short time later, the main activity [which was triggered by the splash activity] opens up.
I don't want this to happen. I want the entire application to close if the back button is pressed while the splash screen is being displayed.
How do I accomplish this?
Edit:
below is my code for splash activity:
public class Splash2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// fading transition between activities
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_splash2);
Thread timer = new Thread() {
public void run() {
try {
sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent open = new Intent(
"com.example.puzzletimer.HOMESCREEN");
startActivity(open);
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Just add this code to your SplashActivity...
#Override
public void onBackPressed() {
super.onBackPressed();
android.os.Process.killProcess(android.os.Process.myPid());
}
or maintain one flag to determine to start Activity or not in Thread...
public class Splash2 extends Activity {
private volatile boolean interrupt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fullscreen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// fading transition between activities
overridePendingTransition(R.anim.fadein, R.anim.fadeout);
setContentView(R.layout.activity_splash2);
Thread timer = new Thread() {
public void run() {
try {
sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (!interrupt) {
Intent open = new Intent(
"com.example.puzzletimer.HOMESCREEN");
startActivity(open);
}
}
}
};
timer.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
#Override
public void onBackPressed() {
super.onBackPressed();
interrupt = true;
}
}
Try this-
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
// do something on back.
this.finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
Another way to do it is with runnable:
Declare Handler and Runnable in your Splash2 activity:
private Handler handler;
private Runnable startMain;
In onCreate(), initialize them and set the runnable to fire in 1.5 secs:
handler = new Handler();
startMain = new Runnable() {
#Override
public void run() {
Intent open = new Intent("com.example.puzzletimer.HOMESCREEN");
startActivity(open);
}
};
handler.postDelayed(startMain, 1500);
Override onBackPressed() and simply cancel runnable:
#Override
public void onBackPressed() {
handler.removeCallbacks(startMain);
super.onBackPressed();
}
That's it. If back key is pressed, it cancels runnable and your homescreen won't run.
I would like to find a solution on how to stop the music when user go back to the Main Activity.
My code is below, user can go back to the Activity A as usually but the music still play from Activity B.
I have the second Activity as the code below:
Layout A
<Button
android:id="#+id/buttonUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Song" />
Java of Activity A
public class MySongActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.buttonUrl);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, WebViewActivity.class);
startActivity(intent);
}
});
}
}
Layout B
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none" />
Java of Activity B
public class WebViewActivity extends Activity {
WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlist);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.loadUrl("http://m.orkun2u.com/msopheap/song/mysongs.htm");
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Kindly please help me. I do appreciate for your help.
Note:
I tried all the way that Google it but still doesn't stop the music.
just one more thing about what Padma Kumar said. the way to stop is to use the dismiss function.
#Override
public void onPause() {
mWebView.setVisibility(View.GONE);
mWebView.destroy();
super.onPause();
}
updated: chenged the function from dismiss() to destroy(), for more: read here: http://developer.android.com/reference/android/webkit/WebView.html
//onPause stop your music
public class MySongActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.buttonUrl);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(context, WebViewActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
//stop the music here
}
}
I just think the best way to deal this trouble is not webView.destory() in Activity's onPause().
I think that:
#Override
protected void onResume() {
super.onResume();
webView.resumeTimers();
webView.onResume();
}
#Override
protected void onPause() {
if (null != getWebView()) {
webView.pauseTimers();
webView.onPause();
webView.reload();
}
super.onPause();
}
Do my best.