如何在Android中获取当前的前台活动上下文?
本示例演示了如何在Android中获取当前的前台活动上下文
步骤1-在AndroidStudio中创建一个新项目,转到File⇒NewProject并填写所有必需的详细信息以创建一个新项目。
第2步-将以下代码添加到src/MyApp.java
package app.nhooo.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 ; } }
步骤3-将以下代码添加到src/MyBaseActivity.java
package app.nhooo.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 ) ; } }
步骤4-将以下代码添加到src/MainActivity.java
package app.nhooo.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() ; } }
第5步-将以下代码添加到androidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.nhooo.com.sample" > <uses-permission android :name= "android.permission.CALL_PHONE" /> <application android :name= ".MyApp" android :allowBackup= "true" android :icon= "@mipmap/ic_launcher" android :label= "@string/app_name" android :roundIcon= "@mipmap/ic_launcher_round" android :supportsRtl= "true" android :theme= "@style/AppTheme" > <activity android :name= ".MainActivity" > <intent-filter> <action android :name= "android.intent.action.MAIN" /> <category android :name= "android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android :name= ".MyBaseActivity" /> </application> </manifest>