So the question is, is it really possible to access Context
, Application
and specially Activity
anywhere. Like as in other static class methods without passing parameters?
Eg:
public static class YOUR_CLASS{
public static void YOUR_FUNCTION(){
Application app = /* GET APPLICATION */;
Activity act = /* GET ACTIVITY */;
Context c = /* GET CONTEXT */;
// USE THEM
}
}
Yes it's possible like this:
public static void YOUR_FUNCTION(){
Application app = getApplication();
Activity act = getActivity();
Context c = /* app or act, both are Contexts so u can use them as needed */;
// USE THEM
}
public static Activity getActivity() {
try{
Class activityThreadClass = Class.forName("android.app.ActivityThread");
Object activityThread = activityThreadClass.getMethod("currentActivityThread").invoke(null);
Field activitiesField = activityThreadClass.getDeclaredField("mActivities");
activitiesField.setAccessible(true);
Map<Object, Object> activities = (Map<Object, Object>) activitiesField.get(activityThread);
for (Object activityRecord : activities.values()) {
try
{
Class activityRecordClass = activityRecord.getClass();
Field pausedField = activityRecordClass.getDeclaredField("paused");
pausedField.setAccessible(true);
boolean paused=pausedField.getBoolean(activityRecord);
Field activityField = activityRecordClass.getDeclaredField("activity");
activityField.setAccessible(true);
Activity activity = (Activity) activityField.get(activityRecord);
if(!paused){
return activity;
}
}
catch (Throwable e)
{}
}
}catch (Throwable e)
{}
return null;
}
public static Application getApplicationContext(){
try
{
Application i=(Application)Class.forName("android.app.ActivityThread")
.getMethod("currentApplication").invoke(null, null);
if(i==null){
throw new NullPointerException();
}
return i;
}
catch (Throwable e)
{
try
{
Application i=(Application)Class.forName("android.app.AppGlobals")
.getMethod("getInitialApplication").invoke(null, null);
if(i==null){
throw new NullPointerException();
}
return i;
}
catch (Throwable e2)
{
return null;
}
}
}