每当我的广播执行时,我想显示对前景活动的警报。
当前回答
知道ActivityManager管理活动,所以我们可以从ActivityManager获取信息。我们得到当前的前景运行活动
ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
更新2018/10/03 getRunningTasks()已弃用。请参阅下面的解决方案。
此方法在API级别21中已弃用。 从Build.VERSION_CODES开始。LOLLIPOP,这种方法不再适用于第三方应用程序:以文档为中心的最近记录的引入意味着它可能会向调用者泄露人员信息。为了向后兼容,它仍然会返回它的数据的一个小子集:至少是调用者自己的任务,可能还有一些已知不敏感的其他任务,比如home。
其他回答
waqas716的答案很好。我针对需要更少代码和维护的特定情况创建了一个变通方案。
我通过一个静态方法从我怀疑是在前景的活动中获取一个视图,找到了一个特定的工作。 您可以遍历所有活动并检查您是否希望或从martin的回答中获得活动名称
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"));
}
为了向后兼容:
ComponentName cn;
ActivityManager am = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
cn = am.getAppTasks().get(0).getTaskInfo().topActivity;
} else {
//noinspection deprecation
cn = am.getRunningTasks(1).get(0).topActivity;
}
更新3:已经为此添加了官方api,请改用ActivityLifecycleCallbacks。
就我个人而言,我是按照“Cheok Yan Cheng”说的去做的,但我使用了一个“列表”来对我所有的活动进行“备份”。
如果你想检查哪个是当前活动,你只需要得到列表中的最后一个活动类。
创建一个扩展“application”的应用程序,这样做:
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks,
EndSyncReceiver.IEndSyncCallback {
private List<Class> mActivitiesBackStack;
private EndSyncReceiver mReceiver;
private Merlin mMerlin;
private boolean isMerlinBound;
private boolean isReceiverRegistered;
@Override
public void onCreate() {
super.onCreate();
[....]
RealmHelper.initInstance();
initMyMerlin();
bindMerlin();
initEndSyncReceiver();
mActivitiesBackStack = new ArrayList<>();
}
/* START Override ActivityLifecycleCallbacks Methods */
@Override
public void onActivityCreated(Activity activity, Bundle bundle) {
mActivitiesBackStack.add(activity.getClass());
}
@Override
public void onActivityStarted(Activity activity) {
if(!isMerlinBound){
bindMerlin();
}
if(!isReceiverRegistered){
registerEndSyncReceiver();
}
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
}
@Override
public void onActivityStopped(Activity activity) {
if(!AppUtils.isAppOnForeground(this)){
if(isMerlinBound) {
unbindMerlin();
}
if(isReceiverRegistered){
unregisterReceiver(mReceiver);
}
if(RealmHelper.getInstance() != null){
RealmHelper.getInstance().close();
RealmHelper.getInstance().logRealmInstanceCount("AppInBackground");
RealmHelper.setMyInstance(null);
}
}
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
}
@Override
public void onActivityDestroyed(Activity activity) {
if(mActivitiesBackStack.contains(activity.getClass())){
mActivitiesBackStack.remove(activity.getClass());
}
}
/* END Override ActivityLifecycleCallbacks Methods */
/* START Override IEndSyncCallback Methods */
@Override
public void onEndSync(Intent intent) {
Constants.SyncType syncType = null;
if(intent.hasExtra(Constants.INTENT_DATA_SYNC_TYPE)){
syncType = (Constants.SyncType) intent.getSerializableExtra(Constants.INTENT_DATA_SYNC_TYPE);
}
if(syncType != null){
checkSyncType(syncType);
}
}
/* END IEndSyncCallback Methods */
private void checkSyncType(Constants.SyncType){
[...]
if( mActivitiesBackStack.contains(ActivityClass.class) ){
doOperation() }
}
}
在我的例子中,我使用了“应用程序”。ActivityLifecycleCallbacks”:
Bind/Unbind Merlin Instance (used to get event when the app lose or get connection, for example when you close mobile data or when you open it). It is useful after the "OnConnectivityChanged" intent action was disabled. For more info about MERLIN see: MERLIN INFO LINK Close my last Realm Instance when the application is closed; I will init it inside a BaseActivity wich is extended from all others activities and which has a private RealmHelper Instance. For more info about REALM see: REALM INFO LINK For instance I have a static "RealmHelper" instance inside my "RealmHelper" class which is instantiated inside my application "onCreate". I have a synchronization service in which I create I new "RealmHelper" because Realm is "Thread-Linked" and a Realm Instance can't work inside a different Thread. So in order to follow Realm Documentation "You Need To Close All Opened Realm Instances to avoid System Resources Leaks", to accomplish this thing I used the "Application.ActivityLifecycleCallbacks" as you can see up. Finally I have a receiver wich is triggered when I finish to synchronize my application, then when the sync end it will call the "IEndSyncCallback" "onEndSync" method in which I look if I have a specific Activity Class inside my ActivitiesBackStack List because I need to update the data on the view if the sync updated them and I could need to do others operations after the app sync.
以上就是全部内容,希望对大家有所帮助。见u:)
我在Kotlin中做了以下工作
Create Application Class Edit the Application Class as Follows class FTApplication: MultiDexApplication() { override fun attachBaseContext(base: Context?) { super.attachBaseContext(base) MultiDex.install(this) } init { instance = this } val mFTActivityLifecycleCallbacks = FTActivityLifecycleCallbacks() override fun onCreate() { super.onCreate() registerActivityLifecycleCallbacks(mFTActivityLifecycleCallbacks) } companion object { private var instance: FTApplication? = null fun currentActivity(): Activity? { return instance!!.mFTActivityLifecycleCallbacks.currentActivity } } } Create the ActivityLifecycleCallbacks class class FTActivityLifecycleCallbacks: Application.ActivityLifecycleCallbacks { var currentActivity: Activity? = null override fun onActivityPaused(activity: Activity?) { currentActivity = activity } override fun onActivityResumed(activity: Activity?) { currentActivity = activity } override fun onActivityStarted(activity: Activity?) { currentActivity = activity } override fun onActivityDestroyed(activity: Activity?) { } override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) { } override fun onActivityStopped(activity: Activity?) { } override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) { currentActivity = activity } } you can now use it in any class by calling the following: FTApplication.currentActivity()
推荐文章
- 如何在android中获得当前前景活动上下文?
- 如何在Android中获取当前日期?
- 获取Android设备名称
- 在WebView中上传文件
- 加载HTML文件到WebView
- Android:为什么视图没有maxHeight ?
- 如何获得具有已知资源名称的资源id ?
- 在Android上将字符串转换为整数
- 为什么“System.out。”println“工作在Android?
- WebView显示err_cleartext_not_allowed尽管站点是HTTPS
- Android M权限:对shouldShowRequestPermissionRationale()函数的使用感到困惑
- 为什么构建类型与产品风味不同?
- 我如何在一个片段中访问getSupportFragmentManager() ?
- 调试在哪里。Android Studio中的密钥存储库
- 从资产中读取文件