My goal is to detect when the user goes into the background. I used this answer to get me setup
However when I replace where there is "MyApplication" in his code, with my classname ("MainActivity"). I can the inconvertible types error.
I'm new to android studio and do not know how to go about fixing this. Any and help is appreciated.
Main Activity Code:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private Timer mActivityTransitionTimer;
private TimerTask mActivityTransitionTimerTask;
public boolean wasInBackground;
private final long MAX_ACTIVITY_TRANSITION_TIME_MS = 2000;
@Override
public void onResume()
{
super.onResume();
MainActivity myApp = (MainActivity)this.getApplication();
if (myApp.wasInBackground)
{
//Do specific came-here-from-background code
}
myApp.stopActivityTransitionTimer();
}
@Override
public void onPause()
{
super.onPause();
((MainActivity)this.getApplication()).startActivityTransitionTimer();
}
public void startActivityTransitionTimer() {
this.mActivityTransitionTimer = new Timer();
this.mActivityTransitionTimerTask = new TimerTask() {
public void run() {
MainActivity.this.wasInBackground = true;
}
};
this.mActivityTransitionTimer.schedule(mActivityTransitionTimerTask,
MAX_ACTIVITY_TRANSITION_TIME_MS);
}
public void stopActivityTransitionTimer() {
if (this.mActivityTransitionTimerTask != null) {
this.mActivityTransitionTimerTask.cancel();
}
if (this.mActivityTransitionTimer != null) {
this.mActivityTransitionTimer.cancel();
}
this.wasInBackground = false;
}
}
EDIT: AndroidManifest.xml below:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jstudios.cars">
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="Cars"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".SplashActivity"
android:label="@string/app_name"
android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:configChanges="orientation|keyboardHidden"
android:label="CarsApp"
android:screenOrientation="portrait"
android:theme="@style/AppTheme.NoActionBar"></activity>
</application>
</manifest>
Intent filter is for the splash screen.
EDIT: @Modi Harsh
LifeCycleObserverClassCode:
Directories Of LifeCycleObserver:
Input of Code in MainActivity:
EDIT 2 ERROR IN MainActivityJava:
EDIT 2 ERROR IN MyLifeCycleObserverClass: