Opening android application from background - android

Whenever my android application goes into the background i always wants to open my password activity every time application comes from background, How can i implement this functionality in my code?

Please follow these steps:
Add New Class Global
public class Global extends Application
{
private static Global mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
ApplicationLifeCycleHandler handler = new ApplicationLifeCycleHandler();
registerActivityLifecycleCallbacks(handler);
registerComponentCallbacks(handler);
}
public static Global getInstance(){
return mInstance;
}
}
Add this line in your manifest in application tag like
<application
android:name=".Global"
</application>
Add this class and open your password intent when app come background to foreground like
public class ApplicationLifeCycleHandler implements Application.ActivityLifecycleCallbacks, ComponentCallbacks2 {
public static Activity activity;
private static final String TAG = ApplicationLifeCycleHandler.class.getSimpleName();
public static boolean isInBackground = true;
#Override
public void onActivityCreated(Activity activity, Bundle bundle) {
}
#Override
public void onActivityStarted(Activity activity) {
this.activity = activity;
}
#Override
public void onActivityResumed(Activity activity) {
this.activity = activity;
if (isInBackground) {
Intent intent = new Intent(activity, PasswordActivity.class);//set your password activity
activity.startActivity(intent);
Log.d(TAG, "app went to foreground");
isInBackground = false;
}
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
#Override
public void onConfigurationChanged(Configuration configuration) {
}
#Override
public void onLowMemory() {
}
#Override
public void onTrimMemory(int i) {
if (i == ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN) {
Log.d(TAG, "app went to background");
isInBackground = true;
}
}
}
Hope it will help you and please let me know if you are facing any issue. Thanks

Related

How to use a CustomApplication class in a Flutter Plugin

I am generating a plugin in Flutter that will integrate a native library *.aar and this library needs to be initialized in the Application class of android, since it will extend the Application class of the library. The problem I am having is that at no time does it seem that the Application class is used in the Flutter plugin, I have tried to create the application class and define it in the plugin manifest, but at no time does it seem to enter the onCreate. I do not see how to solve this situation, any indication is welcome.
My class Application:
public class App extends SDKApplication{
#Override
public void onCreate() {
super.onCreate();
Log.e("App", "onCreate");
}
}
My manifest
<application
android:name=".App">
</application>
and the plugin class:
public class SdkPlugin implements FlutterPlugin, MethodCallHandler {
/// The MethodChannel that will the communication between Flutter and native Android
///
/// This local reference serves to register the plugin with the Flutter Engine and unregister it
/// when the Flutter Engine is detached from the Activity
private MethodChannel channel;
private EMTingSDK sdk = EMTingSDK.getInstance();
private Context context;
public SdkPlugin(){
Log.e("PRUEBAS","onMethodCall");
new App();
}
#Override
public void onAttachedToEngine(#NonNull FlutterPluginBinding flutterPluginBinding) {
context = flutterPluginBinding.getApplicationContext();
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), Constants.CHANNEL);
channel.setMethodCallHandler(this);
}
#Override
public void onMethodCall(#NonNull MethodCall call, #NonNull Result result) {
Log.e("PRUEBAS","onMethodCall");
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
}else {
result.notImplemented();
}
}
#Override
public void onDetachedFromEngine(#NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
}
P.D: I need to start it in the Application because the developers of the native library told us that it had to be spent in this way, then I will put a little more code regarding the application.
public class SDKApplication extends CompanyApplication implements ActivityLifecycleCallbacks {
public SDKApplication() {
}
public void onCreate() {
SDK.getInstance().setContext(this.getApplicationContext());
super.onCreate();
Log.i("InfoSDK", "SDKApplication - init from App ");
this.registerActivityLifecycleCallbacks(this);
}
public void onActivityCreated(Activity activity, Bundle bundle) {
SDK.getInstance().setHostActivity(activity);
}
public void onActivityStarted(Activity activity) {
}
public void onActivityResumed(Activity activity) {
SDK.getInstance().setHostActivity(activity);
}
public void onActivityPaused(Activity activity) {
}
public void onActivityStopped(Activity activity) {
}
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
public void onActivityDestroyed(Activity activity) {
}
}
And the Company Application is:
public class CompanyApplication extends Application {
public CompanyApplication () {
}
public void onCreate() {
super.onCreate();
RequestQueue mainQueue = null;
if (SDK.getInstance().isDevelopEnviroment()) {
mainQueue = Volley.newRequestQueue(this.getApplicationContext(), new HurlStack((UrlRewriter)null, this.newSslSocketFactory()));
} else {
mainQueue = Volley.newRequestQueue(this.getApplicationContext());
}
CompanyHttpClient.getInstance().setMainQueue(mainQueue);
}
}

How to handle auto logout after 5 minutes when app goes to background in android

I'm doing banking application after 5 mins activity should go to the login screen, I referred many links and implemented,
It's working when the app is in the foreground, I'm calling timer and checking after 5 mins I'm redirected to login screen.
But when the app is in the background how to handle, if I login same timer and redirected to login page means automatically its opened.it should not open right.
In background itself, it should move to login screen right. Please help me to solve my problem.
I referred this link:https://gist.github.com/dseerapu/b768728b3b4ccf282c7806a3745d0347
One of mine application is successfully working on auto logout after 5 minutes whether app is in background or foreground state.
To create auto logout for 5 minutes first create all class as below:
ApplockManager
public class ApplockManager {
private static ApplockManager instance;
private DefaultApplock currentAppLocker;
public static ApplockManager getInstance() {
if (instance == null) {
instance = new ApplockManager();
}
return instance;
}
public void enableDefaultAppLockIfAvailable(Application currentApp) {
currentAppLocker = new DefaultApplock(currentApp);
}
public void startWaitThread(Context context){
currentAppLocker.startWaitThread(context);
}
public void updateTouch(){
currentAppLocker.updateTouch();
}
public void setStopTrue(){
currentAppLocker.setStopTrue();
}
public void setStopFalse(){
currentAppLocker.setStopFalse();
}
}
DefaultApplock
public class DefaultApplock implements Application.ActivityLifecycleCallbacks {
final String TAG = DefaultApplock.class.getSimpleName();
private Application mCurrentApp;
private long WAIT_TIME = 5 * 60 * 1000;
private Waiter waiter;
private Date mLostFocusDate;
public DefaultApplock(Application app) {
super();
mCurrentApp = app;
//Registering Activity lifecycle callbacks
mCurrentApp.unregisterActivityLifecycleCallbacks(this);
mCurrentApp.registerActivityLifecycleCallbacks(this);
}
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
// for UserInactivity
// for Screen lock
if (shouldShowUnlockScreen()) {
Log.d(TAG, "time over");
Intent intent = new Intent(activity.getApplicationContext(), SplashActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
Log.d(TAG, "changing mLostFocus to null");
mLostFocusDate = null;
activity.getApplicationContext().startActivity(intent);
}
}
private boolean shouldShowUnlockScreen() {
Boolean isvalid = false;
if (mLostFocusDate == null) {
isvalid = false;
} else {
Log.d(TAG, "Timeout ->"+timeSinceLocked());
if (timeSinceLocked() >= (WAIT_TIME/1000)) {
isvalid = true;
} else {
mLostFocusDate = null;
}
}
Log.d(TAG, isvalid.toString());
return isvalid;
}
private int timeSinceLocked() {
return Math.abs((int) ((new Date().getTime() - mLostFocusDate.getTime()) / 1000));
}
#Override
public void onActivityPaused(Activity activity) {
/*if(waiter!=null) {
waiter.stopThread();
}*/
mLostFocusDate = new Date();
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
public void startWaitThread(Context context){
/*if(waiter!=null) {
waiter.stopThread();
}*/
waiter = new Waiter(context, WAIT_TIME);
waiter.start();
}
public void updateTouch() {
if(waiter!=null) {
waiter.touch();
}
mLostFocusDate = new Date();
}
public void setStopTrue() {
if(waiter!=null) {
waiter.setStopTrue();
}
}
public void setStopFalse() {
if(waiter!=null) {
waiter.setStopFalse();
}
}
}
Waiter
public class Waiter extends Thread
{
private static final String TAG=Waiter.class.getName();
private long lastUsed;
private long period;
private boolean stop = false;
private Context mContext;
SessionManager session;
public Waiter(Context context,long period) {
this.period=period;
stop=false;
mContext = context;
session = new SessionManager(context.getApplicationContext());
}
public void run() {
long idle=0;
this.touch();
do
{
idle = System.currentTimeMillis() - lastUsed;
if(idle > period)
{
idle=0;
// Perform Your desired Function like Logout or expire the session for the app.
stopThread();
}
}
while(!stop);
Log.d(TAG, "Finishing Waiter thread");
}
public synchronized void touch() {
lastUsed = System.currentTimeMillis();
}
public synchronized void setStopTrue() {
stop = true;
}
public synchronized void setStopFalse() {
stop = false;
}
public synchronized void forceInterrupt() {
this.interrupt();
}
public synchronized void setPeriod(long period)
{
this.period=period;
}
public synchronized void stopThread() {
stop = true;
session.logoutUserInBackgroundOrForeground(mContext);
}
public synchronized void startThread() {
stop = false;
}
}
SessionManager
public class SessionManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "MyAutoLogoutAppPref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
/**
* Create login session
*/
public void createLoginSession() {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// commit changes
editor.commit();
}
public void setIsLogin(boolean login) {
editor.putBoolean(IS_LOGIN, login);
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
public void logoutUserInBackgroundOrForeground(Context context) {
setIsLogin(false);
editor.clear();
editor.commit();
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
MyAutoLogoutApp
public class MyAutoLogoutApp extends Application {
public static MyAutoLogoutApp myAutoLogoutApp;
#Override
public void onCreate() {
super.onCreate();
myAutoLogoutApp = this;
ApplockManager.getInstance().enableDefaultAppLockIfAvailable(this);
ApplockManager.getInstance().startWaitThread(myAutoLogoutApp);
}
public void touch() {
ApplockManager.getInstance().updateTouch();
}
public void setStopTrue() {
ApplockManager.getInstance().setStopTrue();
}
public void setStopFalse() {
ApplockManager.getInstance().setStopFalse();
ApplockManager.getInstance().startWaitThread(MyAutoLogoutApp.myAutoLogoutApp);
}
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
}
BaseActivity
public class BaseActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onUserInteraction() {
super.onUserInteraction();
MyAutoLogoutApp.myAutoLogoutApp.touch();
}
}
Finally your every activity must extends BaseActivity so when user touches any where then onUserInteraction() method will fire and timer will reset and it will work for both background and foreground scenario.

Android - Use the Activity callback in a standard java class

I'm developing an .aar library and I really need to interact with the lifecycle of an activity (so the callback onCreate(), on onResume(), etc...) in a standard java class.
I tried a lot of things but nothing works.
Is there a way I can do that?
From my understanding you need some thing like this,
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
/**
* #Krish
*/
public class LifeCycleObserver {
private LifeCycleObserver() {}
private static LifeCycleObserver sLifeCycleObserver;
public static LifeCycleObserver getInstance()
{
if (sLifeCycleObserver == null)
{
sLifeCycleObserver = new LifeCycleObserver();
}
return sLifeCycleObserver;
}
public static void init(Application application)
{
application.registerActivityLifecycleCallbacks(sLifeCycleObserver.lifecycleCallbacks);
}
private Application.ActivityLifecycleCallbacks lifecycleCallbacks = new Application.ActivityLifecycleCallbacks() {
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityStarted(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
}
#Override
public void onActivityPaused(Activity activity) {
}
#Override
public void onActivityStopped(Activity activity) {
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
};
}
and use it like this in Application class,
import android.app.Application;
/**
* Created by krish
*/
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
LifeCycleObserver.init(this);
}
}

is there a way to create condition listener

is there a way to create a listener that activates an event under a certain condition(boolean)?
i tried reading about creating custom listeners using interfaces but i dont think it's the answer for my question.
right now in my app i write an if statement everywhere so if i could just create a listener for it, it would be much easier.
set_A==B_Listener(????? {//listener takes place if a==b
#Override
public boolean event(View v, MotionEvent e)
{
//do something
}
});
Create a class variable for your statement, than you can attach an OnChangeListener to your statement in the onCreate method of your Activity
public class DummyActivity extends Activity {
interface OnStateChangeListener{
public void onAttach(Activity activity);
public void onStateChange(boolean state);
}
private boolean state;
private OnStateChangeListener listener;
private YourClass stateChangedCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listener = new OnStateChangeListener() {
private Activity currentActivity;
#Override
public void onAttach(Activity activity) {
currentActivity = activity;
}
#Override
public void onStateChange(boolean state) {
if (((DummyActivity) this.currentActivity).state != state) {
stateChangedCallback.doSomething();
((DummyActivity) this.currentActivity).state = state;
}
}
};
}
private void yourFunction() {
boolean state = true;
listener.onStateChange(state);
}
}

Android event listener for app lifecycle

I am writing an Android code segment to help tracing Android event as a service tool for app developers.
For example, the main app body can be just to display 'hello world'. My code will listen to the app event, such as onStart(), onResume(), onDestroy(), etc, and keep a trace on these events.
Certainly, the code can be inserted directly under the main activity. But that means my code will be allover the places. Is there a way, I can create an object (i.e., a listener), and only request the app developer to add 1~2 liner to use my code?
For API Level 14 and higher, you can call registerActivityLifecycleCallbacks() on the Application to set up a listener to be informed about activity lifecycle events.
Try this Approach
public class mYApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new MyLifecycleHandler());
}
}
MyLifecycleHandler :
public class MyLifecycleHandler implements Application.ActivityLifecycleCallbacks {
private static int resumed;
private static int paused;
private static int started;
private static int stopped;
#Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
#Override
public void onActivityDestroyed(Activity activity) {
}
#Override
public void onActivityResumed(Activity activity) {
++resumed;
}
#Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
}
#Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
#Override
public void onActivityStarted(Activity activity) {
++started;
}
#Override
public void onActivityStopped(Activity activity) {
++stopped;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
public static boolean isApplicationVisible() {
return started > stopped;
}
public static boolean isApplicationInForeground() {
return resumed > paused;
}
}
and then call isApplicationInForeground static method to check if application is in foreground or background

Categories

Resources