How to let Fragment do some action before onBackPressed() kill it - android

I wonder if this is possible to do in AppCompatActivity. I want to let top most Fragment do some action before AppCompatActivity super.onBackPressed(); kill Fragment
HereĀ“s the mockup code which speaks for itself:
#Override
public void onBackPressed() {
ToppMosteFragment.doSomeActionBeforeBackPressedKillYou();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// this is not working..
super.onBackPressed();
}
}, 1000);
}

You can try to make doSomeActionBeforeBackPressedKillYou() return a boolean
and do
#Override
public void onBackPressed() {
if(ToppMosteFragment.doSomeActionBeforeBackPressedKillYou()) {
super.onBackPressed();
}
}
EDIT:
If you defined the animation , you can add a listener :
Animation animation = actionButton.getHideAnimation();
animation.setAnimationListener(new Animation.AnimationListener(){
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
listener.onFabAnimationEnd();
}
});
actionButton.setHideAnimation(animation);
listener is a interface that is implement by your activity class
And in you activity
#Override
public void onFabAnimationEnd() {
super.onBackPressed();
}

I got an Idea,
This could be an universal thing -
Create BaseFragment having the method like below -
public class BaseFragment extends Fragment {
public boolean onFragmentBackPressed() {
return true;
}
}
extend your MyFragment to BaseFragment
class MyFragment extends BaseFragment {
// override method
#Override
public boolean onFragmentBackPressed() {
return false;
}
}
Check in your MainActivity that if BaseFragment method onFragmentBackPressed() if returning false or what, if yes - perform some action before exiting
#Override
public void onBackPressed() {
if (MyFragment instance if BaseFragment) {
if (!((BaseFragment) MyFragment).onFragmentBackPressed()) {
// perform and action
} else {
super.onBackPressed();
}
} else {
super.onBackPressed();
}
}

Related

Doing something when returning to an Activity from Background

I want to execute a function only when returning to the Application from the background.
I have included the method in onResume, and this does it to a certain extent. Problem is since onResume is fired even on creating the Activity and when returning to the activity from another activity (Ex: From pressing the back button), and the function is executed there as well.
How to avoid this and execute the function only when returning from background?
Ps: My application already has multiple places using startActivity so changing to startActivityForResult is a tedious task.
Also all my Activities are extending from a common BaseAppCompactActivity class and it's where my method is located, so this will apply to the whole application.
Edit 2:
My BaseAppCompactActivity is as below with LifecycleObserver implemented now. This doesn't seem to work though.
public class BaseAppCompactActivity extends AppCompatActivity implements LifecycleObserver {
private String TAG = BaseAppCompactActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#Override
protected void onPause() {
super.onPause();
stopService();
}
#Override
protected void onPostResume() {
super.onPostResume();
startService();
}
// #Override
// protected void onResume() {
// super.onResume();
//// updateLastAccessedDate();
// }
private void startService() {
startService(new Intent(this, BusinessCacheService.class));
}
private void stopService() {
stopService(new Intent(this, BusinessCacheService.class));
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
private void updateLastAccessedDate() {
//Do something
}
}
Although its a duplicate . Here is a Java implementation i am sharing for sake of help ..
public class MyApplication extends MultiDexApplication implements LifecycleObserver {
private boolean previouslyInBackground;
#Override
public void onCreate() {
super.onCreate();
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
#OnLifecycleEvent(Lifecycle.Event.ON_STOP)
void onAppBackgrounded() {
previouslyInBackground=true;
}
#OnLifecycleEvent(Lifecycle.Event.ON_START)
void onAppForegrounded() {
if(previouslyInBackground){
// Do your stuff Here
}
previouslyInBackground=false;
}
}
Add the Gradle dependency from Lifecycle-aware components Documentation
You can use startActivityForResult instead of startActivity.
Then you can catch the returning inside onActivityResult method.
first set a global boolean variable like this:-
boolean isPaused = false;
now set a methods in your activity :-
#Override
protected void onUserLeaveHint() {
isPaused = true;
super.onUserLeaveHint();
}
or in your onResume method:-
#Override
protected void onResume() {
if(isPaused){
isPaused = false;
}
super.onResume();
}
Do like this
add these variable in your main activity
public static boolean isAppWentToBg = true;
public static boolean isWindowFocused = false;
public static boolean isBackPressed = false;
and also add these methods
private void applicationWillEnterForeground() {
if (isAppWentToBg) {
isAppWentToBg = false;
// Toast.makeText(getApplicationContext(), "App is in foreground", Toast.LENGTH_SHORT).show();
}
}
public void applicationdidenterbackground() {
if (!isWindowFocused) {
isAppWentToBg = true;
// Toast.makeText(getApplicationContext(), "App is Going to Background", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
isBackPressed = true;
Log.d(TAG, "onBackPressed " + isBackPressed + "" + this.getLocalClassName());
super.onBackPressed();
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
isWindowFocused = hasFocus;
if (isBackPressed && !hasFocus) {
isBackPressed = false;
isWindowFocused = true;
}
super.onWindowFocusChanged(hasFocus);
}
#Override
protected void onStart() {
Log.d(TAG, "onStart isAppWentToBg " + isAppWentToBg);
applicationWillEnterForeground();
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop ");
applicationdidenterbackground();
}
What I would suggest is create a new boolean variable which say if that is created for the first time in resume and work on it.
Boolean isForeGround = true;
#Override
public void onPause() {
super.onPause();
isForeGround = false;
}
#Override
public void onResume() {
super.onPause();
if(!isForeGround){
isForeGround = true;
// write your code here
}
}

how to disable back-button on rewarded video show/playing?

During the Rewarded video play i want to disable the back button and set a minimum waiting time . is it possible to do?On which function should i change to complete my desired functionality?
here is my code
if (mAd.isLoaded()) {
mAd.show();
} else {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
and here is Rewarded video ads handling methods
private void loadRewardedVideoAds() {
if (!mAd.isLoaded()) {
mAd.loadAd(getResources().getString(R.string.rewardedvideoid), new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
// onBackPressed();
}
#Override
public void onRewardedVideoStarted() {
// onBackPressed();
}
#Override
public void onRewardedVideoAdClosed() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
loadRewardedVideoAds();
}
#Override
public void onRewardedVideoCompleted() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
Try below code
private boolean isVideoPlaying;
#Override
public void onRewardedVideoStarted() {
isVideoPlaying = true;
}
#Override
public void onRewardedVideoAdClosed() {
isVideoPlaying = false;
}
and than onBackPress() check, if the video is playing or not
#Override
public void onBackPressed() {
if (!isVideoPlaying)
super.onBackPressed();
}
Before implementing this, please read the policies carefully.
You must override the onBackPressed callback in activity and remove line super.onBackPressed(). then if the user taps the back button the activity will not close.
If you have no access to the Essay_Answer_Show activity check can you create another activity which extends that or clone library and tries to modify activity?

How to disable long press on keys in custom keyboard android?

I want to disable long press on keys on my custom keyboard.for implementing customkeyboard i extended View class.like below but there is no method to handle longpress
public class CustomKeyboard extends View {
#Override
public void onPress(int arg0) {
Log.d("Gajanand", "onPress:GK ");
}
#Override
public void onRelease(int primaryCode) {
Log.d("Gajanand", "onRelease: GK");
}
#Override
public void onText(CharSequence text) {
}
#Override
public void swipeDown() {
}
#Override
public void swipeLeft() {
}
#Override
public void swipeRight() {
}
#Override
public void swipeUp() {
}
}
help me to handle on long press. i want to disable long press completely.
You can use PopupWindow class and populate it with custom layout.
PopupWindow popup = new PopupWindow(context);
popup.setContentView(custom);
On click in the popup you can dismiss it.
#Override
public void onRelease(int primaryCode) {
Log.d("Gajanand", "onRelease: GK");
popup.dismiss();
}
Happy coding!!

In Android where to put the global method?

Below is my code to exit my app.
Since I have more than 1 activity, where should I put exitBy2Click() so it can be use for all activities?
I tried to create a new class called "Global", and public exitBy2Click(), but Toast.makeText(this,... not work.
Thanks.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK) {
exitBy2Click();
}
return false;
}
private static Boolean isExit = false;
private void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click 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);
}
}
Checking your method, I think that best option would be Inheritance..
Note on example below that you can override onBackPressed() instead of onKeyDown()
public class BaseActivity extends Activity {
private static Boolean isExit = false;
#Override
public void onBackPressed() {
exitBy2Click();
}
public void exitBy2Click() {
Timer tExit = null;
if (!isExit) {
isExit = true;
Toast.makeText(this, "click 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);
}
}
}
Then, your "real" activities can extends that BaseActivity and this way, onKeyDown and exitBy2Click will be commom to all classes.
public class MainActivity extends BaseActivity {
#override
public void onCreate(Bundle savedInstance) {
}
}
public class SecundaryActivity extends BaseActivity {
#override
public void onCreate(Bundle savedInstance) {
}
}
//ETC
The best place to put this code is literally "nowhere".
Forcibly terminating an Android app is not recommended, and calling System.exit is definitely not something you should ever do in an Android app.

How can I check user interaction on android dialog?

Android activity has overridden method onUserInteraction.But how can I check the user interaction in the dialog?I want to develop some logic based on this.Please help
This code works (onUserInteraction)fine with Activity
public class MyBaseActivity extends Activity {
public static final long DISCONNECT_TIMEOUT = 300000; // 5 min = 5 * 60 * 1000 ms
private Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
}
};
public void resetDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
resetDisconnectTimer();
}
#Override
public void onStop() {
super.onStop();
stopDisconnectTimer();
}
}
But how can I use 'onUserInteraction' method with Dialog ?
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(MainActivity.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.cusotm_dialog_layout);
dialog.setTitle("Custom Dialog");
//adding text dynamically
TextView txt = (TextView) dialog.findViewById(R.id.textView);
txt.setText("Put your dialog text here.");
ImageView image = (ImageView)dialog.findViewById(R.id.image);
image.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_info));
//adding button click event
Button dismissButton = (Button) dialog.findViewById(R.id.button);
dismissButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
I have implemented onUserInteraction for DialogFragment. This has the same handling as Activity for onUserInteraction. The setUserInteractionEnabled method can also be implemented in an Activity subclass.
public abstract class BaseDialogFragment
extends DialogFragment
{
protected void onUserInteraction()
{
Activity activity = getActivity();
if(activity != null)
{
activity.onUserInteraction();
}
}
protected void setUserInteractionEnabled(Dialog dialog, boolean enabled)
{
if(!enabled)
{
dialog.getWindow().setCallback(dialog);
return;
}
dialog.getWindow().setCallback(new WindowCallbackWrapper(dialog)
{
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
onUserInteraction();
return super.dispatchKeyEvent(event);
}
#Override
public boolean dispatchKeyShortcutEvent(KeyEvent event)
{
onUserInteraction();
return super.dispatchKeyShortcutEvent(event);
}
#Override
public boolean dispatchTouchEvent(MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
onUserInteraction();
}
return super.dispatchTouchEvent(event);
}
#Override
public boolean dispatchTrackballEvent(MotionEvent event)
{
onUserInteraction();
return super.dispatchTrackballEvent(event);
}
#Override
public boolean dispatchGenericMotionEvent(MotionEvent event)
{
onUserInteraction();
return super.dispatchGenericMotionEvent(event);
}
});
}
}
Call this in your onCreateDialog.
public class MyDialogFragment
extends BaseDialogFragment
{
#Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
Dialog dialog = new Dialog(getContext());
setUserInteractionEnabled(dialog, true);
return dialog;
}
}
Note: this will not call onUserInteraction from the dialog's soft keyboard. That should be handled from a TextWatcher that calls onUserInteraction in afterTextChanged.

Categories

Resources