Activity
Activity is an application component that provider a screen with which users can interact in order to do something. Each activity is given a window in which to draw its user interface. Each time a new activity starts, the previous activity is stopped, the system preserves the activity in a stack.
Start a Activity
You can start a activity by startActivity() method with an Intent that describes with you want to start.
Intent intent = new Intent(this, SignInActivity.class);
startActivity(intent);
Or create an Intent that describes an action you want to perform and launch an activity of another application.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, recipientArray);
startActivity(intent);
Or start with startActivityForResult() method instead of startActivity(), and you need implement the onActivityResult(), it will take an Intent to you onActivityResult() method.
Activity Lifecycle
Saving activity state
Sometimes, system need recreate the activity if user navigates back to it. In this situation, we should implements onSaveInstanceState() method for save some information.
The system calls onSaveInstanceState() before making the activity to destruction. The system passes this method a Bundle with your information. Then, if the system kills your application process and the user navigates back to your activity, the system recreates the activity and passes the Bundle to both onCreate() and onRestoreInstanceState().
Application、Task和Process
Application是应用,包括一些资源和Manifest解析打包后一个APK.
Task是对于Activity来说的,是一组Activity的集合,可以是跨应用的,是为Activity的连续性使用服务。
Process是操作系统概念,在Android中一个应用运行在个 dalvik虚拟机上,一个运行的dalvik实例占用一个进程,除非在Manifest中特别申明一些组件单独运行在一个独立的进程。比如:
<service
android:name=".MyTestAidlService"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="manfu.test.service"/>
</intent-filter>
</service>
Activity的启动模式
Activity有4种启动模式,必须要在Manifest中配置其Activity属性android:launchMode。
standard
默认方式,多次启动Activity会创建多个Activity实例,在Task中会有多个实例。
singleTop
启动栈顶的Activity时,不会重新创建Activity,会调用栈顶实例Activity的onNewIntent()方法。启动不处于栈顶的Activity时和standard模式一样。
singleTask
总在一个新task的底部创建Activity,被它启动的Activity都在这个新的task中,如果已经存在,则会调用onNewIntent()方法,只存在一个实例。如果此Activity没有设置单独的taskAffinity,如果在启动时发现它已经在一个task中运行,会清理掉此task中该Activity上面的所有Activity。只有当设置了taskAffinity后,没有其他task的taskAffinity和该Activity相同,此时,才是真正的singleTaks。
singleInstance
总在一个新的task中创建,新task只有这一个实例,它启动的Activity都运行在其他task中,如果存在,会调用onNewIntent()。