新建一個java繼承Application類html
import android.app.Application; import android.content.Context; /** * 編寫自定義Application,管理全局狀態信息,好比Context * @author autumn */ public class MyApplication extends Application { private static Context context; @Override public void onCreate() { super.onCreate(); //獲取Context context = getApplicationContext(); } //返回 public static Context getContextObject(){ return context; } }
在AndroidManifest.xml中註冊,在application標籤中添加android:name="com.***.MyApplication"便可java
<application android:name="com.***.MyApplication" 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"> </application>
調用獲取全局Contextandroid
MyApplication.getContextObject();