Android学习路线(十四)Activity生命周期——停止和重启(Stopping and Restarting)一个Activity

先占个位置,下次翻译~ :p

Properly stopping and restarting your activity is an important process in the activity lifecycle that ensures your users perceive that your app is always alive and doesn‘t lose their progress. There are a few of key scenarios in which your activity is stopped
and restarted:

  • The user opens the Recent Apps window and switches from your app to another app. The activity in your app that‘s currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the
    Recent Apps window, the activity restarts.
  • The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted.
  • The user receives a phone call while using your app on his or her phone.

The Activity class provides two lifecycle
methods, onStop() and onRestart(),
which allow you to specifically handle how your activity handles being stopped and restarted. Unlike the paused state, which identifies a partial UI obstruction, the stopped state guarantees that the UI is no longer visible and the user‘s focus is in a separate
activity (or an entirely separate app).

Note: Because the system retains your Activity instance
in system memory when it is stopped, it‘s possible that you don‘t need to implement the onStop() and onRestart() (or
even onStart() methods at
all. For most activities that are relatively simple, the activity will stop and restart just fine and you might only need to useonPause() to
pause ongoing actions and disconnect from system resources.

Figure 1. When the user leaves your activity, the system calls onStop() to
stop the activity (1). If the user returns while the activity is stopped, the system calls onRestart() (2),
quickly followed by onStart() (3) and onResume() (4).
Notice that no matter what scenario causes the activity to stop, the system always calls onPause() before
calling onStop().

Stop Your Activity



When your activity receives a call to the onStop() method,
it‘s no longer visible and should release almost all resources that aren‘t needed while the user is not using it. Once your activity is stopped, the system might destroy the instance if it needs to recover system memory. In extreme cases, the system might
simply kill your app process without calling the activity‘s final onDestroy() callback,
so it‘s important you use onStop() to
release resources that might leak memory.

Although the onPause() method
is called before onStop(),
you should use onStop() to
perform larger, more CPU intensive shut-down operations, such as writing information to a database.

For example, here‘s an implementation of onStop() that
saves the contents of a draft note to persistent storage:

@Override
protected void onStop() {
    super.onStop();  // Always call the superclass method first

    // Save the note‘s current draft, because the activity is stopping
    // and we want to be sure the current note progress isn‘t lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    getContentResolver().update(
            mUri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.
            );
}

When your activity is stopped, the Activity object
is kept resident in memory and is recalled when the activity resumes. You don’t need to re-initialize components that were created during any of the callback methods leading up to the Resumed state. The system also keeps track of the current state for each View in
the layout, so if the user entered text into an EditText widget,
that content is retained so you don‘t need to save and restore it.

Note: Even if the system destroys your activity while it‘s stopped, it still retains the state of the View objects
(such as text in an EditText) in
Bundle (a blob of key-value pairs) and
restores them if the user navigates back to the same instance of the activity (the next lesson talks
more about using a Bundle to save other
state data in case your activity is destroyed and recreated).

Start/Restart Your Activity



When your activity comes back to the foreground from the stopped state, it receives a call to onRestart().
The system also calls the onStart() method,
which happens every time your activity becomes visible (whether being restarted or created for the first time). The onRestart() method,
however, is called only when the activity resumes from the stopped state, so you can use it to perform special restoration work that might be necessary only if the activity was previously stopped, but not destroyed.

It‘s uncommon that an app needs to use onRestart() to
restore the activity‘s state, so there aren‘t any guidelines for this method that apply to the general population of apps. However, because your onStop() method
should essentially clean up all your activity‘s resources, you‘ll need to re-instantiate them when the activity restarts. Yet, you also need to instantiate them when your activity is created for the first time (when there‘s no existing instance of the activity).
For this reason, you should usually use the onStart() callback
method as the counterpart to the onStop() method,
because the system calls onStart() both
when it creates your activity and when it restarts the activity from the stopped state.

For example, because the user might have been away from your app for a long time before coming back it, theonStart() method
is a good place to verify that required system features are enabled:

@Override
protected void onStart() {
    super.onStart();  // Always call the superclass method first
   
    // The activity is either being restarted or started for the first time
    // so this is where we should make sure that GPS is enabled
    LocationManager locationManager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
   
    if (!gpsEnabled) {
        // Create a dialog here that requests the user to enable GPS, and use an intent
        // with the android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS action
        // to take the user to the Settings screen to enable GPS when they click "OK"
    }
}

@Override
protected void onRestart() {
    super.onRestart();  // Always call the superclass method first
   
    // Activity being restarted from stopped state    
}

When the system destroys your activity, it calls the onDestroy() method
for your Activity. Because you should
generally have released most of your resources with onStop(),
by the time you receive a call to onDestroy(),
there‘s not much that most apps need to do. This method is your last chance to clean out resources that could lead to a memory leak, so you should be sure that additional threads are destroyed and other long-running actions like method tracing are also stopped.

Android学习路线(十四)Activity生命周期——停止和重启(Stopping and Restarting)一个Activity,布布扣,bubuko.com

时间: 2024-08-07 17:25:23

Android学习路线(十四)Activity生命周期——停止和重启(Stopping and Restarting)一个Activity的相关文章

Android学习路线(十三)Activity生命周期——停止和恢复(Pausing and Resuming )一个Activity

先占个位置,下次翻译~ :p During normal app use, the foreground activity is sometimes obstructed by other visual components that cause the activity to pause. For example, when a semi-transparent activity opens (such as one in the style of a dialog), the previou

Android学习路线(四)构建一个简单的UI

Android应用的图形化用户界面的构建使用的是View 和 ViewGroup 对象的层次嵌套. View 对象通常是UI部件,例如 buttons 或者 text fields ,而 ViewGroup 是用来定义它的子布局如何排布的容器,它通常是不可见的,例如一个网格或者一个垂直的列表. Android提供XML词汇与View或者ViewGroup的子类的对应,这样的话你就可以通过XML元素的层级嵌套来定义你的UI. 另一种布局 使用XML声明UI比在运行时代码中声明更有用处可以在很多地方

Android学习笔记十四.深入理解fragment(二) 之《图书详情》实战

深入理解fragment(二) 之<图书详情>实战 通过上一篇博文<深入理解fragment一>,我们学习了Android-Fragment的核心知识点.现在在此基础上,利用Fragment技术开发一款适用于大屏幕手机/平板的查找图书详情的应用软件.该项目主要在于两方面,一是Activity.Fragment的源码实现:二是,布局界面资源文件的实现. 1.res/../BookListFragment.java: 自定义类,继承于ListFragment,无需实现OnCreateV

Android学习(十四) Service组件

一.定义 运行在后台,没有页面,不可见.优先级高于Activity,当系统内存不足时,会先释放一些Activity.注意,Service同样是运行在主线程中,不能做一些耗时操作.如果一定要做一些耗时的操作,启动一个新的线程,在新的线程中来处理. 二.用途: 播放音乐,记录地理位置的改变,监听某些动作. 三.Sevice分类: 1.本地服务(Local Service):是一种本地服务,一般用于应用程序内部,通过startService方法启动,通过stopService,stopSelf,sto

android学习二十四(网络编程的最佳实践)

前面的博客已经讲解了HttpURLConnection和HttpClient的用法,知道了如何发起HTTP请求,以及解析服务器返回 的数据.但是可能你发现了,因为一个应用程序很多地方都可能使用网络功能,而发送HTTP请求的代码基本相同,如果每次我们都去编写一遍发送HTTP请求的代码,这显然不太好. 通常情况下我们都应该将这些通用的网络操作提取到一个公共的类里,并提供一个静态方法,当想要发起网络请求的时候只需简单地调用一下这个方法即可.比如下面的写法: package com.jack.netwo

android学习笔记28——Activity生命周期

Activity生命周期 Activity的活动状态由android已Activity栈的形式管理,当前活动的Activity位于栈顶.随着不同应用的运行,每个Activity都有可能从活动状态转入非活动状态,从非活动状态转入活动状态. Activity归纳大致会经过4个状态: 1.活动状态:当前Activity位于前台,用户可见,可获得焦点: 2.暂停状态:其他Activity位于前台,该Activity可见,不可获得焦点: 3.停止状态:该Activity不可见,失去焦点: 4.销毁状态:该

Android Activity生命周期的几个问题

每一个Android开发者都应该知道,android系统有四个重要的基本组件,即Activity(活动).Service(服务).Broadcast Receive(广播接收器)和Content Provider(内容提供器),其中,Activity是最重要的组件,打开你手机上的APP,你眼睛所能看到的都是Activity,下面将会介绍关于Activity生命周期的几个问题. 1 Activity生命周期的8个回调函数 下图是Activity的生命周期图,相信许多人都看过不止一次,但有的人是看到

Android之Activity生命周期浅析(一)

??Activity作为四大组件之一,出现的频率相当高,基本上我们在android的各个地方都能看见它的踪影,因此深入了解Activity,对于开发高质量应用程序是很有帮助的.今天我们就来详细地聊聊Activity的生命周期,以便我们在以后的开发中能如鱼得水. 一.初识Activity ??在日常应用中Activity是与用户交互的接口,它提供了一个用户完成相关操作的窗口.当我们在开发中创建Activity后,通过调用setContentView(View)方法来给该Activity指定一个布局

浅谈Android之Activity生命周期

 Activity作为四大组件之一,出现的频率相当高,基本上我们在android的各个地方都能看见它的踪影,因此深入了解Activity,对于开发高质量应用程序是很有帮助的.今天我们就来详细地聊聊Activity的生命周期,以便我们在以后的开发中能如鱼得水. 一.初识Activity   在日常应用中Activity是与用户交互的接口,它提供了一个用户完成相关操作的窗口.当我们在开发中创建Activity后,通过调用setContentView(View)方法来给该Activity指定一个布局界