ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
然后我检查视图是否为空,并通过getContext()获取上下文。
View v = SuspectedActivity.get_view();
if(v != null)
{
// an example for using this context for something not
// permissible in global application context.
v.getContext().startActivity(new Intent("rubberduck.com.activities.SomeOtherActivity"));
}
//Initialization
val lifeCycleHandler = ActivityLifeCycleHandler<Activity>()
//Detect only a specific type of activities
val lifeCycleHandler = ActivityLifeCycleHandler<MainActivity>()
//Get current activity
val instance = lifeCycleHandler.currentReference
//Get current activity state
val state = lifeCycleHandler.currentState
//Use listeners
lifeCycleHandler.addStateChangeListener { newState ->
//TODO: handle new state
}
lifeCycleHandler.addSpecificStateChangeListener(ActivityLifeCycleHandler.ActivityState.STARTED) {
//TODO: handle new state
}
//Removable listeners
val listener = { newState: Int ->
}
lifeCycleHandler.addStateChangeListener(listener)
lifeCycleHandler.removeStateChageListener(listener)
//Start listening
App.app.registerActivityLifecycleCallbacks(lifeCycleHandler)
//Stop listening
lifeCycleHandler.releaseListeners()
App.app.unregisterActivityLifecycleCallbacks(lifeCycleHandler)
public class App extends Application implements ActivityLifecycleCallbacks
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}