如何在用户回到后台应用程序时触发一个function?

例如,用户打开一个应用程序,按下主页button,然后再次返回到应用程序。

当用户导航回应用程序时,有什么办法可以触发某些function吗? 比如当用户回到应用程序时自动加载视图对象。

这个问题适用于Android和iOS。

在项目的AppDelegate.m文件(仅适用于iOS)中使用以下内容

 - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } 

在onPause()方法中编写这段代码来知道你的应用程序已经到了后台。

 public void onPause() { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); Boolean flag=false; List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { flag=true; } } if(flag) { //App went to background... } } 

在onResume()中使用上面的标志来知道你的应用程序已经恢复。

对于android来说,你可以在你的代码中使用onResume函数。 但是请记住android的生命周期是这样的

的onCreate – >的onResume。

所以onResume总是被称为即使应用程序第一次运行或来自后台。 但只有在第一次创buildActivity时才会调用onCreate。

你可以在onPause方法上设置一些variables,这个方法在app进入后台时被调用

当你得到这个variables“true”并且onResume被调用时,你可以执行你的任务。

请享用。

尝试在Activity的两个方法onKeyDown和onPause中使用一个布尔variables。

 boolean backFromBackground = false; onCreate(){ //whatever you want } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_HOME) { backFromBackground = true; } } onPause(){ if(backFromBackground){ //do what ever you want } }