玩转Android之Activity详细剖析
本文主讲了什么是Activity,它的生命周期,不对的操作,调用了什么函数。以及不同的Activity之间的跳转、数据传递等。
Activity 是用户接口程序,原则上它会提供给用户一个交互式的接口功能。它是 android 应用程序的基本功能单元。Activity 本身是没有界面的。所以activity类创建了一个窗口,开发人员可以通过setContentView(View)接口把UI放到activity创建的窗口上,当activity指向全屏窗口时,也可以用其他方式实现:作为漂浮窗口(通过windowIsFloating的主题集合),或者嵌入到其他的activity(使用ActivityGroup)。activity是单独的,用于处理用户操作。几乎所有的activity都要和用户打交道。
一、Activity的生命周期简介
1、操纵生命周期的七种方法:
2、Activity的运作流程
一般启动Activity:onCreate -> onStart -> onResume
呼叫另一个Activity: onPause -> onCreate -> onStart -> onResume -> onStop
还原Activity: onPause -> onRestart -> onStart -> onResume -> onStop -> onDestroy
退出Activity: onPause -> onStop -> onDestroy
回收再启动Activity: onCreate -> onStart –> onResume
3、Activity生命周期的四种基本状态:
(1)Active/Runing:一个新 Activity 启动入栈后,它在屏幕最前端,处于栈的最顶端,此时它处于可见并可和用户交互的激活状态。
(2)Paused:当 Activity 被另一个透明或者 Dialog 样式的 Activity 覆盖时的状态。此时它依然与窗口管理器保持连接,系统继续维护其内部状态,所以它仍然可见,但它已经失去了焦点故不可与用户交互。
(3)Stoped。当 Activity 被另外一个 Activity 覆盖、失去焦点并不可见时处于 Stoped状态。
(4)Killed Activity。被系统杀死回收或者没有被启动时处于 Killed状态。
二、Activity生命周期代码范例
1:/**
2:*Activity生命周期学习
3:*@author林炳文(博客)
4:*@time2015.3.19
5:*/
6:packagecom.example.activitylearning;
7:importandroid.os.Bundle;
8:importandroid.app.Activity;
9:importandroid.util.Log;
10:publicclassMainActivityextendsActivity{
11:privatestaticfinalStringTAG="AvtivityTest";
12:@Override
13:protectedvoidonCreate(BundlesavedInstanceState){
14:super.onCreate(savedInstanceState);
15:Log.d(TAG,"onCreate()called");
16:setContentView(R.layout.activity_main);
17:}
18:@Override
19:protectedvoidonStart(){
20:super.onStart();
21:Log.d(TAG,"onStart()called");
22:
23:}
24:@Override
25:protectedvoidonResume(){
26:super.onResume();
27:Log.d(TAG,"onResume()called");
28:
29:}
30:@Override
31:protectedvoidonPause(){
32:super.onPause();
33:Log.d(TAG,"onPause()called");
34:
35:}
36:@Override
37:protectedvoidonStop(){
38:super.onStop();
39:Log.d(TAG,"onStop()called");
40:
41:}
42:protectedvoidonDestroy(){
43:super.onDestroy();
44:Log.d(TAG,"onDestroy()called");
45:
46:}
47:
48:
49:}
1、程序启动
一般启动Activity:onCreate -> onStart -> onResume
2、程序启动后按下后退键
退出Activity: onPause -> onStop -> onDestroy
可以看到,程序已退出了。
3、程序启动后按下主屏幕键
还原Activity: onPause -> onRestart -> onStart -> onResume -> onStop -> onDestroy
再打开程序:
三、多个Activity管理
1、Android 是通过一种 Activity 栈的方式来管理 Activity 的,一个 Activity 的实例的状态决定它在栈中的位置。
2、处于前台的 Activity 总是在栈的顶端,当前台的 Activity 因为异常或其它原因被销毁时,处于栈第二层的 Activity 将被激活,上浮到栈顶。
3、当新的 Activity 启动入栈时,原 Activity 会被压入到栈的第二层。一个 Activity 在栈中的位置变化反映了它在不同状态间的转换
注意:
在Android系统中,要使用Activity必须在AndroidManifest.xml文件中进行配置。
在<application…/>元素中添加<activity…/>子元素即可
配置Activity通常指定如下三个属性:
–name:指定该Activity的实现类。
–icon:指定该Activity对应的图标。
–label:指定该Activity的标签。
四、由一个Activity启动另一个Activity(不带数据传递)
1、布局
activity_1.xml(放在layout)
1:<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
2:xmlns:tools="http://schemas.android.com/tools"
3:android:layout_width="match_parent"
4:android:layout_height="match_parent"
5:tools:context=".Activity1">
6:<Button
7:android:id="@+id/id_button1"
8:android:layout_width="match_parent"
9:android:layout_height="wrap_content"
10:android:text="启动Activity2"
11:/>
12:</RelativeLayout>
activity_2.xml
1:<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
2:xmlns:tools="http://schemas.android.com/tools"
3:android:layout_width="match_parent"
4:android:layout_height="match_parent">
5:<Textview
6:android:text="欢迎来到Activity2"
7:android:layout_centerInParent="true"
8:android:layout_width="match_parent"
9:android:layout_height="wrap_content"
10:android:textSize="30sp"
11:/>
12:</RelativeLayout>
2、对应的代码:
Activity1.java
1:/**
2:*Activity生命周期学习
3:*@author林炳文(博客http://blog.csdn.net/evankaka/)
4:*@time2015.3.19
5:*/
6:packagecom.example.activitylearning;
7:importandroid.os.Bundle;
8:importandroid.app.Activity;
9:importandroid.content.Intent;
10:importandroid.util.Log;
11:importandroid.view.View;
12:importandroid.view.View.OnClickListener;
13:importandroid.widget.Button;
14:publicclassActivity1extendsActivity{
15:privatestaticfinalStringTAG="Avtivity1";
16:privateButtonmButton;
17:
18:@Override
19:protectedvoidonCreate(BundlesavedInstanceState){
20:super.onCreate(savedInstanceState);
21:Log.d(TAG,"onCreate()called");
22:setContentView(R.layout.activity_1);
23:mButton=(Button)findViewById(R.id.id_button1);
24:mButton.setOnClickListener(newOnClickListener(){
25:@Override
26:publicvoidonClick(Viewarg0){
27:startActivity(newIntent(Activity1.this,Activity2.class));
28:
29:}
30:});
31:}
32:@Override
33:protectedvoidonStart(){
34:super.onStart();
35:Log.d(TAG,"onStart()called");
36:
37:}
38:@Override
39:protectedvoidonResume(){
40:super.onResume();
41:Log.d(TAG,"onResume()called");
42:
43:}
44:@Override
45:protectedvoidonPause(){
46:super.onPause();
47:Log.d(TAG,"onPause()called");
48:
49:}
50:@Override
51:protectedvoidonStop(){
52:super.onStop();
53:Log.d(TAG,"onStop()called");
54:
55:}
56:protectedvoidonDestroy(){
57:super.onDestroy();
58:Log.d(TAG,"onDestroy()called");
59:
60:}
61:
62:
63:}
Activity2.java
1:packagecom.example.activitylearning;
2:
3:importandroid.app.Activity;
4:importandroid.os.Bundle;
5:importandroid.util.Log;
6:
7:publicclassActivity2extendsActivity{
8:privatestaticfinalStringTAG="Avtivity2";
9:@Override
10:protectedvoidonCreate(BundlesavedInstanceState){
11:super.onCreate(savedInstanceState);
12:Log.d(TAG,"onCreate()called");
13:setContentView(R.layout.activity_2);
14:}
15:@Override
16:protectedvoidonStart(){
17:super.onStart();
18:Log.d(TAG,"onStart()called");
19:
20:}
21:@Override
22:protectedvoidonResume(){
23:super.onResume();
24:Log.d(TAG,"onResume()called");
25:
26:}
27:@Override
28:protectedvoidonPause(){
29:super.onPause();
30:Log.d(TAG,"onPause()called");
31:
32:}
33:@Override
34:protectedvoidonStop(){
35:super.onStop();
36:Log.d(TAG,"onStop()called");
37:
38:}
39:protectedvoidonDestroy(){
40:super.onDestroy();
41:Log.d(TAG,"onDestroy()called");
42:
43:}
44:
45:}
3、Activity注册
Androidmanifest.xml中
增加:
1:<activity
2:android:name="com.example.activitylearning.Activity2"
3:android:label="@string/app_name">
4:</activity>
4、运行结果
(1)、在Activity中点击按钮:启动Activity2
从上面可以看出Activity1没被毁掉,而是变成Stop()了,当前变成不可见。
(2 )然后再点击后退键:
五、由一个Activity启动另一个Activity(带数据传递)
1、界面
activity_1.xml(放在layout)
1:<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
2:xmlns:tools="http://schemas.android.com/tools"
3:android:layout_width="match_parent"
4:android:layout_height="match_parent"
5:tools:context=".Activity1">
6:<Button
7:android:id="@+id/id_button1"
8:android:layout_width="match_parent"
9:android:layout_height="wrap_content"
10:android:text="启动Activity2"
11:/>
12:
13:<EditText
14:android:id="@+id/id_edittext1"
15:android:layout_below="@id/id_button1"
16:android:layout_width="match_parent"
17:android:layout_height="wrap_content"
18:/>
19:<EditText
20:android:id="@+id/id_edittext2"
21:android:layout_below="@id/id_edittext1"
22:android:layout_width="match_parent"
23:android:layout_height="wrap_content"
24:/>
25:</RelativeLayout>
activity_2.xml(放在layout)
1:<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
2:xmlns:tools="http://schemas.android.com/tools"
3:android:layout_width="match_parent"
4:android:layout_height="match_parent">
5:<TextView
6:android:id="@+id/id_textview1"
7:android:layout_width="match_parent"
8:android:layout_height="wrap_content"
9:android:textSize="30sp"
10:/>
11:<TextView
12:android:id="@+id/id_textview2"
13:android:layout_below="@id/id_textview1"
14:android:layout_width="match_parent"
15:android:layout_height="wrap_content"
16:android:textSize="30sp"
17:/>
18:</RelativeLayout>
两个效果如下:
2、主要代码。
Activity1.java中
1:IntentmIntent=newIntent(Activity1.this,Activity2.class);
2:StringmString1=mEditText1.getText().toString();
3:StringmString2=mEditText1.getText().toString();
4:mIntent.putExtra("one",mString1);
5:mIntent.putExtra("two",mString2);
6:startActivity(mIntent);
Activity2.java中
1:mTextView1=(TextView)findViewById(R.id.id_textview1);
2:mTextView2=(TextView)findViewById(R.id.id_textview1);
3:
4:StringmString1=getIntent().getStringExtra("one");
5:StringmString2=getIntent().getStringExtra("two");
6:
7:mTextView1.setText(mString1);
8:mTextView2.setText(mString1);
3、运行结果
左边为Activity1,右边为Activity2.它会得到Activity1的结果并在TextView中显示出来
六、得到返回的Activity的数据
这里要实现在Activity1中的两个EditText中输入内容,打开Activity2,将Activity1中的两个EditText的内容显示在Activity2的两个TextView中。
在在Activity2中的两个EditText中输入内容,按下返回键,将Activity2中的两个EditText的内容显示在Activity1的两个TextView中。
1、布局
2、主要代码
Activity1.java中:
1:mButton=(Button)findViewById(R.id.id_button1);
2:mButton.setOnClickListener(newOnClickListener(){
3:@Override
4:publicvoidonClick(Viewarg0){
5:IntentmIntent=newIntent(Activity1.this,Activity2.class);
6:StringmString1=mEditText1.getText().toString();
7:StringmString2=mEditText2.getText().toString();
8:mIntent.putExtra("one",mString1);
9:mIntent.putExtra("two",mString2);
10:startActivityForResult(mIntent,0);
11:
12:}
13:});
注意要用 startActivityForResult(mIntent, 0);//0表示标识,等下Activity也要标志为0
然后是处理Activity2返回后的事件
1:@Override
2:protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
3:super.onActivityResult(requestCode,resultCode,data);
4:if(null==data)
5:return;
6:TextViewmTextView3=(TextView)findViewById(R.id.id_textview3);
7:TextViewmTextView4=(TextView)findViewById(R.id.id_textview4);
8:
9:StringmString3=data.getStringExtra("three");
10:StringmString4=data.getStringExtra("four");
11:
12:mTextView3.setText(mString3);
13:mTextView4.setText(mString4);
14:}
Activity2.java中:
在按下返回键的事件中,增加一些数据传递,其实这里主要是setResult(0,result);注意0要和上面的startActivityForResult(mIntent, 0);对应。
1:@Override
2:publicbooleanonKeyDown(intkeyCode,KeyEventevent){
3:if(keyCode==KeyEvent.KEYCODE_BACK&&event.getRepeatCount()==0){
4:
5:EditTextmEditText3=(EditText)findViewById(R.id.id_edittext3);
6:EditTextmEditText4=(EditText)findViewById(R.id.id_edittext4);
7:StringmData1=mEditText3.getText().toString();
8:StringmData2=mEditText4.getText().toString();
9:Intentresult=newIntent();
10:result.putExtra("three",mData1);
11:result.putExtra("four",mData2);
12:setResult(0,result);
13:
14:}
15:returnsuper.onKeyDown(keyCode,event);
16:}
3、效果
从Activity1中启动Activity2,可以看到,数据传递过去了
Activity1 Activity2
从Activity2中返回到Activity1中,可以看到,数据返回了
Activity2 Activity1
八、额外内容
Activity返回值
使用startActivity方式启动的Activity和它的父Activity无关,当它关闭时也不会提供任何反馈。可变通的,你可以启动一个Activity作为子Activity,它与父Activity有内在的联系。当子Activity关闭时,它会触发父Activity中的一个事件处理函数。子Activity最适合用在一个Activity为其它的Activity提供数据(例如用户从一个列表中选择一个项目)的场合。
子Activity的创建和普通Activity的创建相同,也必须在应用程序的manifest中注册。任何在manifest中注册的Activity都可以用作子Activity。
启动子Activity
startActivityForResult方法和startActivity方法工作很相似,但有一个很重要的差异。Intent都是用来决定启动哪个Activity,你还可以传入一个请求码。这个值将在后面用来作为有返回值Activity的唯一ID。
下面的代码显示了如何启动一个子Activity:
private static final int SHOW_SUBACTIVITY = 1;
Intent intent = new Intent(this, MyOtherActivity.class);
startActivityForResult(intent, SHOW_SUBACTIVITY);
和正常的Activity一样,子Activity可以隐式或显式启动。下面的框架代码使用一个隐式的Intent来启动一个新的子Activity来挑选一个联系人:
private static final int PICK_CONTACT_SUBACTIVITY = 2;
Uri uri = Uri.parse(“content://contacts/people”);
Intent intent = new Intent(Intent.ACTION_PICK, uri);
startActivityForResult(intent, PICK_CONTACT_SUBACTIVITY);
返回值
当子Activity准备关闭时,在finish之前调用setResult来给调用的Activity返回一个结果。
setResult方法带两个参数:结果码和表示为Intent的负载值。结果码是运行子Activity的结果,一般是Activity.RESULT_OK或Activity.RESULT_CANCELED。在一些情况下,你会希望使用自己的响应代号来处理特定的应用程序的选择;setResult支持任何整数值。
作为结果返回的Intent可以包含指向一个内容(例如联系人,电话号码或媒体文件)的URI和一组用来返回额外信息的Extra。
接下来的代码片段节选自子Activity的onCreate方法,显示了怎样向调用的Activity返回不同的结果:
1:ButtonokButton=(Button)findViewById(R.id.ok_button);
2:
3:okButton.setOnClickListener(newView.OnClickListener(){
4:
5:publicvoidonClick(Viewview)
6:
7:{
8:
9:Uridata=Uri.parse(“content://horses/”+selected_horse_id);
10:
11:Intentresult=newIntent(null,data);
12:
13:result.putExtra(IS_INPUT_CORRECT,inputCorrect);
14:
15:result.putExtra(SELECTED_PISTOL,selectedPistol);
16:
17:setResult(RESULT_OK,result);
18:
19:finish();
20:
21:}
22:
23:});
24:
25:ButtoncancelButton=(Button)findViewById(R.id.cancel_button);
26:
27:cancelButton.setOnClickListener(newView.OnClickListener(){
28:
29:publicvoidonClick(Viewview)
30:
31:{
32:
33:setResult(RESULT_CANCELED,null);
34:
35:finish();
36:
37:}
38:
39:});
处理子Activity的结果
当子Activity关闭时,它的父Activity的onActivityResult事件处理函数被触发。
重写这个方法来处理从子Activity返回的结果。onActivityResult处理器接受好几个参数:
请求码
曾经用来启动子Activity的请求码。
结果码
结果码是由子Activity设置的,用来显示它的结果。它可以是任何整数值,但典型的值是Activity.RESULT_OK和Activity.RESULT_CANCELLED。
如果子Activity非正常关闭或在关闭时没有指定结果码,结果码都是Activity.RESULT_CANCELED。
数据
一个Intent来打包任何返回的数据。依赖于子Activity的目的,它可能会包含一个代表特殊的从列表中选择的数据的URI。可变通的,或额外的,子Activity可以使用“extras”机制以基础值的方式返回临时信息。
下面的框架代码实现了一个Activity中的onActivityResult事件处理函数:
1:privatestaticfinalintSHOW_SUB_ACTIVITY_ONE=1;
2:
3:privatestaticfinalintSHOW_SUB_ACTIVITY_TWO=2;
4:
5:@Override
6:
7:publicvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
8:
9:super.onActivityResult(requestCode,resultCode,data);
10:
11:switch(requestCode)
12:
13:{
14:
15:case(SHOW_SUB_ACTIVITY_ONE):
16:
17:{
18:
19:if(resultCode==Activity.RESULT_OK)
20:
21:{
22:
23:Urihorse=data.getData();
24:
25:booleaninputCorrect=data.getBooleanExtra(IS_INPUT_CORRECT,false);
26:
27:StringselectedPistol=data.getStringExtra(SELECTED_PISTOL);
28:
29:}
30:
31:break;
32:
33:}
34:
35:case(SHOW_SUB_ACTIVITY_TWO):
36:
37:{
38:
39:if(resultCode==Activity.RESULT_OK)
40:
41:{
42:
43://TODO:HandleOKclick.
44:
45:}
46:
47:break;
48:
49:}
50:
51:}
52:
53:}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。