如何在 Android 中獲取活動前臺活動環境?
本示例演示如何獲取 Android 中當前的前臺活動環境
步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新專案並填寫所有必需的詳細資訊來建立新專案。
步驟 2 − 將以下程式碼新增到 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 ;
}
}步驟 3 − 將以下程式碼新增到 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 ) ;
}
}步驟 4 − 將以下程式碼新增到 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() ;
}
}步驟 5 − 將以下程式碼新增到 androidManifest.xml中
<? xml version= "1.0" encoding= "utf-8" ?> <manifest xmlns: android = "http://schemas.android.com/apk/res/android" package= "app.tutorialspoint.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>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP