Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to get current foreground activity context in Android?
This example demonstrate about How to get current foreground activity context in Android
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to src/MyApp.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.app.Application ;
public class MyApp extends Application {
private Activity mCurrentActivity = null;
@Override
public void onCreate () {
super .onCreate() ;
}
public Activity getCurrentActivity () {
return mCurrentActivity ;
}
public void setCurrentActivity (Activity mCurrentActivity) {
this . mCurrentActivity = mCurrentActivity ;
}
}
Step 3 − Add the following code to src/MyBaseActivity.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.os.Bundle ;
import android.support.v7.app.AppCompatActivity ;
public class MyBaseActivity extends AppCompatActivity {
protected MyApp mMyApp ;
public void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
mMyApp = (MyApp) this .getApplicationContext() ;
}
protected void onResume () {
super .onResume() ;
mMyApp .setCurrentActivity( this ) ;
}
protected void onPause () {
clearReferences() ;
super .onPause() ;
}
protected void onDestroy () {
clearReferences() ;
super .onDestroy() ;
}
private void clearReferences () {
Activity currActivity = mMyApp .getCurrentActivity() ;
if ( this .equals(currActivity))
mMyApp .setCurrentActivity( null ) ;
}
}
Step 4 − Add the following code to src/MainActivity.java
package app.tutorialspoint.com.sample ;
import android.app.Activity ;
import android.support.v7.app.AppCompatActivity ;
import android.os.Bundle ;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate (Bundle savedInstanceState) {
super .onCreate(savedInstanceState) ;
setContentView(R.layout. activity_main ) ;
Activity currentActivity = ((MyApp)
getApplicationContext()).getCurrentActivity() ;
}
}
Step 5 − Add the following code to androidManifest.xml
xml version= "1.0" encoding= "utf-8" ?>
Advertisements
