阅读:http://developer.android.com/guide/components/activities.html

An application usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an application is specified as the "main" activity, which is presented to the user when launching the application for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the Tasks and Back Stack document.)

  不同Activity的切换依靠back stack,如果有新的Activity出现,新的Activity将入栈。

onCreate()You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setContentView() to define the layout for the activity's user interface.

  在此方法中,必须初始化最基础的组件,但是最重要的是,必须初始化该Activity的layout。

onPause()The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back).

  在这个方法中,最重要的就是提交用户的设置。

The most common way to define a layout using views is with an XML layout file saved in your application resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity's behavior. You can set the layout as the UI for your activity with setContentView(), passing the resource ID for the layout. However, you can also create new Views in your activity code and build a view hierarchy by inserting new Views into a ViewGroup, then use that layout by passing the root ViewGroup tosetContentView().

  定义一个布局有两种方法:1、一直是脱离代码使用XML文件进行布局;2、往ViewGroup添加Views,然后递交给setContentView()。

The <action> element specifies that this is the "main" entry point to the application. The <category> element specifies that this activity should be listed in the system's application launcher (to allow users to launch this activity).

If you intend for your application to be self-contained and not allow other applications to activate its activities, then you don't need any other intent filters. Only one activity should have the "main" action and "launcher" category, as in the previous example. Activities that you don't want to make available to other applications should have no intent filters and you can start them yourself using explicit intents (as discussed in the following section).

However, if you want your activity to respond to implicit intents that are delivered from other applications (and your own), then you must define additional intent filters for your activity. For each type of intent to which you want to respond, you must include an <intent-filter> that includes an <action> element and, optionally, a<category> element and/or a <data> element. These elements specify the type of intent to which your activity can respond.

For more information about how your activities can respond to intents, see the Intents and Intent Filtersdocument.

  <intent-filter>可以让你的Activity被其他程序所调用,如果你不需要这个功能,那么就不需要添加多余的<intent-filter>。

  

Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);

直接调用当前程序的某Activity。

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);

告诉系统你要做什么,并且在intent里添加一些数据。

private void pickContact() {// Create an intent to "pick" a contact, as defined by the content provider URIIntent intent = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);startActivityForResult(intent, PICK_CONTACT_REQUEST);
}@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {// If the request went well (OK) and the request was PICK_CONTACT_REQUESTif (resultCode == Activity.RESULT_OK && requestCode == PICK_CONTACT_REQUEST) {// Perform a query to the contact's content provider for the contact's nameCursor cursor = getContentResolver().query(data.getData(),new String[] {Contacts.DISPLAY_NAME}, null, null, null);if (cursor.moveToFirst()) { // True if the cursor is not emptyint columnIndex = cursor.getColumnIndex(Contacts.DISPLAY_NAME);String name = cursor.getString(columnIndex);// Do something with the selected contact's name...
        }}
}

这些代码显示了如何使用startActivityForResult()。

在使用startActivityForResult()的时候需要多一个参数,用于返回成功的基本标识。

还有一个重要的一点就是,需要实现onActivityResult(),在这个方法里有int requestCode, int resultCode, Intent data三个参数,requestCode可用来识别是否成功返回(有可能用户取消选择),resultCode对应startActivityForResult()里的第二个参数,而data则表示返回的数据。

For more information, see the Content Providers document.

For more information about using intents, see the Intents and Intent Filters document.

You can shut down an activity by calling its finish() method. You can also shut down a separate activity that you previously started by calling finishActivity().

Note: In most cases, you should not explicitly finish an activity using these methods. As discussed in the following section about the activity lifecycle, the Android system manages the life of an activity for you, so you do not need to finish your own activities. Calling these methods could adversely affect the expected user experience and should only be used when you absolutely do not want the user to return to this instance of the activity.

  官方建议不要亲自对Activity使用finish(),而让系统自动管理Activity。

Resumed

The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".)

  当前状态的Activity意味着它正运行着。

Paused
Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn't cover the entire screen. A paused activity is completely alive (the Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations.
Stopped
The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere.

If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling itsfinish() method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over.

  Paused 与 Stopped  的区别在于,Paused还部分可见,而Stopped表示ACtivity已经完全被掩盖了。

  但两者拥有许多共同点:1、尽管出在这种状态,但是对象仍然存在于内存中;2、处在这两个状态的Activity都可以被系统finish,如果真的被系统结束了,那么下次打开就需要从头再来了。

public class ExampleActivity extends Activity {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// The activity is being created.
    }@Overrideprotected void onStart() {super.onStart();// The activity is about to become visible.
    }@Overrideprotected void onResume() {super.onResume();// The activity has become visible (it is now "resumed").
    }@Overrideprotected void onPause() {super.onPause();// Another activity is taking focus (this activity is about to be "paused").
    }@Overrideprotected void onStop() {super.onStop();// The activity is no longer visible (it is now "stopped")
    }@Overrideprotected void onDestroy() {super.onDestroy();// The activity is about to be destroyed.
    }
}

  • The entire lifetime of an activity happens between the call to onCreate() and the call to onDestroy(). Your activity should perform setup of "global" state (such as defining layout) in onCreate(), and release all remaining resources in onDestroy(). For example, if your activity has a thread running in the background to download data from the network, it might create that thread in onCreate() and then stop the thread inonDestroy().
  • The visible lifetime of an activity happens between the call to onStart() and the call to onStop(). During this time, the user can see the activity on-screen and interact with it. For example, onStop() is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register aBroadcastReceiver in onStart() to monitor changes that impact your UI, and unregister it in onStop() when the user can no longer see what you are displaying. The system might call onStart() and onStop() multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user.

  • The foreground lifetime of an activity happens between the call to onResume() and the call to onPause(). During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground—for example, onPause() is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait.

  简而言之,onDestroy的时候必须释放所有资源。

  程序可见的时间在onStart() and the call to onStop() ,这期间程序都可以被看见,如果有一个在前台很好资源的显示控件,那么应该在onStop的时候暂停它、

  程序处于前台的时间再onResume() and the call to onPause().

  

The column labeled "Killable after?" indicates whether or not the system can kill the process hosting the activity at any time after the method returns, without executing another line of the activity's code. Three methods are marked "yes": (onPause()onStop(), and onDestroy()). Because onPause() is the first of the three, once the activity is created, onPause() is the last method that's guaranteed to be called before the process canbe killed—if the system must recover memory in an emergency, then onStop() and onDestroy() might not be called. Therefore, you should use onPause() to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained during onPause(), because any blocking procedures in this method block the transition to the next activity and slow the user experience.

Methods that are marked "No" in the Killable column protect the process hosting the activity from being killed from the moment they are called. Thus, an activity is killable from the time onPause() returns to the timeonResume() is called. It will not again be killable until onPause() is again called and returns.

  onPause是三个有可能被kill掉的最早的状态,因此,最好在这个时刻进行必要数据的存储,避免被系统结束之后失去了重要数据。

onSaveInstanceState()的方法在此时有作用:因为内存紧缺处于暂停或者停止状态的ACtivity被摧毁,但是用户有可能会回来,这个时候有些数据就需要被回复了,系统会在摧毁的时候调用onSaveInstanceState()来存储数据。

该方法的参数是一个Bundle,用键值对来存储数据。而当系统重新建立Activity的时候,存储了数据的Bundle会作为oncreate或者onRestoreInstanceState的参数。

onRestoreInstanceState()与onSaveInstanceState()在父类已经实现,我们可以选择不重写覆盖,但是我们必须为每一个空间增添一个ID作为标志。你也可以选择重写覆盖这两个方法,但是必须先调用父类的实现之后再去做其他的事情。

关于这两个方法最好的例子就是,旋转手机,系统会先摧毁当前的Activity然后重建并且恢复数据。

  1. Activity A's onPause() method executes.
  2. Activity B's onCreate()onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
  3. Then, if Activity A is no longer visible on screen, its onStop() method executes.

  这是两个Activity协调的一个例子,总的来说,但启动了另外一个Activity之后,当前ACtivity立即执行onPause(),直到新的Activity获得焦点,老的Activity才进行onStop()。

转载于:https://www.cnblogs.com/yutoulck/p/3378083.html

Activities相关推荐

  1. SAP PM入门系列29 - IW65 Display Activities

    SAP PM入门系列29 - IW65 Display Activities 事务代码 IW65是SAP PM模块里的一个标准报表.这个报表用于查询PM 维修通知单里的Activities. 不过,这 ...

  2. jbpm 6 vs activities 5评估(持续更新、亲测实际项目评估)

    最近我们有个使用了jbpm 6.2(6.2是一个较大的里程碑)的批处理模块,因为大BOSS一直觉得太重了,希望有更加轻量级的解决方案,因为我们基本上没有真正意义上流程的概念,只有静态的流程图,因为一直 ...

  3. 【起航计划 011】2015 起航计划 Android APIDemo的魔鬼步伐 10 App-Activity-Reorder Activities 后退栈 Intent FLAG...

    Reorder Activities 示例有四个相关的Activitives: ReorderOnLaunch, ReorderTwo,ReorderThree, ReorderFour.其中Reor ...

  4. Android之Only fullscreen opaque activities can request orientation

    1 问题 使用透明的activity主题,并且固定了方向,在Android8.0手机上提示错误如下 Only fullscreen opaque activities can request orie ...

  5. grove 套件_如何通过使用Andy Grove的High Leverage Activities加快发展?

    grove 套件 by Guido Schmitz 由Guido Schmitz 如何通过使用Andy Grove的High Leverage Activities加快发展? (How to spee ...

  6. android 获取栈顶activity,Android : 如何得到Activities栈顶的Activity名称

    众所周知,Android中的任务等等都是通过栈来管理的,Activities的管理也不例外.栈这种数据结构是大家再熟悉不过了.它的先进后出特性让Android可以很容易实现从当前Activity回到或 ...

  7. 英语笔记:写作:Recreational activities

    Recreational activities 娱乐活动 Nowadays, in an era of information and technology, abundant recreationa ...

  8. Android8.0适配-Only fullscreen opaque activities can request orientation

    背景 2018年7月18日上午,电信终端产业协会(TAF)发布<移动应用软件高API等级预置与分发自律公约>(以下简称<公约>).OPPO.华为.百度.360.阿里.小米.VI ...

  9. android 打印流程图,Android实现Activities之间进行数据传递的方法

    本文实例讲述了Android实现Activities之间进行数据传递的方法.分享给大家供大家参考.具体分析如下: 首先,先说明一下Activity的启动及关闭: 1. startActivity(In ...

  10. Quote Form OnLoad Implement Add Leftnav, count Activities

    //--Add Label Textif(crmForm.all.esp_billto_fulladdress!=null) {varhtml=document.createElement(" ...

最新文章

  1. opencv-python图像处理之轮廓算法
  2. 代码改动两三行,AI数据秒换隐身衣!隐私计算+AI?中科院博士实践分享一键切换...
  3. (三十一)java版spring cloud+spring boot+redis多租户社交电子商务平台-spring-cloud-config...
  4. Eclipse 应用的初步认识
  5. Java中包装类型和基本类型的使用场景(阿里开发规范)
  6. 使用Spring-hadoop小结
  7. 2017.5.15 项链工厂 思考记录
  8. 双十一喜报式实时成交额今年没了
  9. [转]android刷新后R.java不见了
  10. 在PhpStorm9中与Pi的xdebug进行调试
  11. read H264 Nal
  12. 民企信息化建设个人经历(二)
  13. github.com连接超时 ping不通
  14. LeetCode - 644 子数组最大平均数 II
  15. NOIP2016模拟 星际争霸(二分)
  16. X64位驱动保护-隐藏进程躲避游戏检测
  17. [附源码]计算机毕业设计springboot高校流浪动物领养网站
  18. stm32f429的u-boot、uclinux内核烧写说明
  19. 集美大学计算机毕业论文,咨询关于集美大学毕业论文检测的问题
  20. 九年级计算机教学计划,实用的九年级教学计划四篇

热门文章

  1. The “QtRunWork“ task returned false but did not log an error
  2. QT显示图片和中途修改图片
  3. Windows核心编程_锁屏
  4. python的UML类图自动生成工具--pyreverse安装和使用
  5. Android图片控件,跟随列表(recyclerView)的上下滚动而同步平移。
  6. Navi.Soft31.任务管理器(定时同步+数据采集)
  7. 理解C语言——从小菜到大神的晋级之路(9)——多维数组
  8. 成都Uber优步司机奖励政策(1月16日)
  9. OA办公系统需要专业的系统管理员
  10. 分布式业务Redis安装与集群配置