android开发步步为营之30:四大组件之Activity

Activit(活动)无疑是整个android开发过程中最重要的组件,一直想写这一节,但是一直认为反正这个简单,先学复杂的,现在认识到最简单的往往是最容易犯错的,只有把基础打扎实才能往上筑高楼。
一、理论知识:
类的继承关系:
public class Activity extendsContextThemeWrapper
implementsComponentCallbacks KeyEvent.Callback LayoutInflater.Factory2View.OnCreateContextMenuListener Window.Callback
 
java.lang.Object
   ?android.content.Context
     ? android.content.ContextWrapper
       ? android.view.ContextThemeWrapper
         ? android.app.Activity
Activity在mvc设计模式中就相当于controller,一个activity需要和一个layout文件夹里面的页面xml文件(相当于mvc里面的view)搭配使用,这样就相当于组成了一个form,页面之间的跳转也是依赖于Activity来实现的。而Activity之间的跳转,我们又必须借助于Intent(意图)来实现,意图里面可以设置需要跳转的Activity,也可以放置需要传递过去的数据。
然后我们在看看Activity的生命周期。
 

 

看这个图可能理解起来还是有难度的,还是通过实践来检验,就容易理解了。
 
 
二、实践操作
 
我们实现的效果有:1、普通的跳转 2、要求有返回值的跳转 3、跳转到其他应用的Activity
第一步、设计页面
main.xml
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="@+id/textView1"/>
<Button android:id="@+id/button1"android:text="跳转到HelloChinaActivity" android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView1" android:layout_alignParentLeft="true"android:layout_marginLeft="21dp"android:layout_marginTop="41dp"></Button>
<Button android:id="@+id/button2"android:text="要求返回Result跳转到HelloChinaActivity" android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_alignLeft="@+id/button1"android:layout_alignRight="@+id/button1"></Button>
<Button android:id="@+id/button3"android:text="跳转到外部Actitivity" android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/button2" android:layout_alignLeft="@+id/button2" android:layout_marginBottom="31dp" android:layout_alignRight="@+id/button1"></Button>
</RelativeLayout>
hellochina.xml
<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hellochina"
    android:id="@+id/textView1"/>
<Button android:id="@+id/buttona"android:text="返回HelloWorldActivity" android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView1" android:layout_alignParentLeft="true"android:layout_marginLeft="21dp"android:layout_marginTop="41dp"></Button>
<Button android:id="@+id/buttonb"android:text="带有Result返回HelloWorldActivity" android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_centerVertical="true"android:layout_alignLeft="@+id/button1"android:layout_alignRight="@+id/button1"></Button>
</RelativeLayout>
 
 
 
第二步、 设计Activity
HelloWorldActivity.java
 
package com.figo.helloworld;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class HelloWorldActivity extends Activityimplements OnClickListener {
 
                                 privatefinal String Tag = "HelloWorldActivity";
                                 privateint requestCode=1;
                                 privateButton btn1, btn2, btn3;
 
                                 /**Called when the activity is first created. */
                                 @Override
                                 publicvoid onCreate(Bundle savedInstanceState) {
                                    super.onCreate(savedInstanceState);
                                    setContentView(R.layout.main);
                                    Log.i(Tag,"HelloWorldActivity onCreate");
                                    btn1= (Button) findViewById(R.id.button1);
                                    btn2= (Button) findViewById(R.id.button2);
                                    btn3= (Button) findViewById(R.id.button3);
                                    btn1.setOnClickListener(this);
                                    btn2.setOnClickListener(this);
                                    btn3.setOnClickListener(this);
                                 }
 
                                 @Override
                                 protectedvoid onStart() {
                                    //TODO Auto-generated method stub
                                    super.onStart();
                                    Log.i(Tag,"HelloWorldActivity onStart");
                                 }
 
                                 @Override
                                 protectedvoid onRestart() {
                                    //TODO Auto-generated method stub
                                    super.onRestart();
                                    Log.i(Tag,"HelloWorldActivity onRestart");
                                 }
 
                                 @Override
                                 protectedvoid onResume() {
                                    //TODO Auto-generated method stub
                                    super.onResume();
                                    Log.i(Tag,"HelloWorldActivity onResume");
                                 }
 
                                 @Override
                                 protectedvoid onPause() {
                                    //TODO Auto-generated method stub
                                    super.onPause();
                                    Log.i(Tag,"HelloWorldActivity onPause");
                                 }
 
                                 @Override
                                 protectedvoid onStop() {
                                    //TODO Auto-generated method stub
                                    super.onStop();
                                    Log.i(Tag,"HelloWorldActivity onStop");
                                 }
 
                                 @Override
                                 protectedvoid onDestroy() {
                                    //TODO Auto-generated method stub
                                    super.onDestroy();
                                    Log.i(Tag,"HelloWorldActivity onDestroy");
                                 }
 
                                 @Override
                                 protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
                                    //这个事件只有在startActivityForResult会执行
                                    super.onActivityResult(requestCode,resultCode, data);
                                    Log.i(Tag,"HelloWorldActivity onActivityResult");
                                    switch(requestCode)
                                    {
                                    case1://表明是HelloChinaActivity回传回来的数据
                                        if(resultCode==12)//这里假设返回12表示成功
                                        {
                                            Stringworld=data.getExtras().getString("china");
                                            Log.i(Tag,"数据返回成功,返回的数据为:"+world);
                                        }else
                                        {
                                            Log.i(Tag,"数据返回失败");
                                        }
                                        break;
                                    case2://其他Activity回传回来的,requestCode=2或其他,自己定义
                                        break;
                                      
                                    }
                                  
                                 }
 
                                 //按钮事件
                                 @Override
                                 publicvoid onClick(View v) {
                                    //TODO Auto-generated method stub
                                    switch(v.getId()) {
                                    caseR.id.button1://简单的传值跳转
                                        Intentintent1=new Intent();//意图,Activity之间跳转要依靠它来表达
                                                                     intent1.setClass(HelloWorldActivity.this,HelloChinaActivity.class);//设置跳转到HelloChinaActivity
                                        Bundlebundle1=new Bundle();
                                        bundle1.putString("world","hello,world");
                                        intent1.putExtras(bundle1);//其实发现这里我们完全可以不用Bundle,把需要携带的值塞进intent就可以了
                                        startActivity(intent1);//开始跳转
                                        HelloWorldActivity.this.finish();//结束这个activity
                                        break;
                                    caseR.id.button2://要求有返回结果的跳转
                                        Intentintent2=new Intent();
                                                                     intent2.setClass(HelloWorldActivity.this,HelloChinaActivity.class);//设置跳转到HelloChinaActivity
                                        Bundlebundle2=new Bundle();
                                        bundle2.putString("world","hello,world");
                                        intent2.putExtras(bundle2);//其实发现这里我们完全可以不用Bundle,把需要携带的值塞进intent就可以了,当然你也可以什么数据都不传,直接一个intent就行了
                                        startActivityForResult(intent2,requestCode);//开始跳转,要求有返回值
                                        //HelloWorldActivity.this.finish();//这里必须注释掉,不然onActivityResult不会触发
                                        break;
                                    caseR.id.button3:
                                         Uri uri =Uri.parse("http://google.com");
                                         Intent intent3 = newIntent(Intent.ACTION_VIEW, uri);
                                         startActivity(intent3);//跳转到外部activity
                                         HelloWorldActivity.this.finish();//结束这个activity
                                        break;
                                    }
                                 }
 
}
 
HelloChinaActivity.java
 
/**
 *
 */
package com.figo.helloworld;
 
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
/**
 * @authorAdministrator
 *
 */
public class HelloChinaActivity extends Activity implementsOnClickListener{
 
                                 privatefinal String Tag = "HelloChinaActivity";
                                 privateint requestCode=1;
                                 privateButton btna, btnb;
                                 @Override
                                 protectedvoid onCreate(Bundle savedInstanceState) {
                                    //TODO Auto-generated method stub
                                    super.onCreate(savedInstanceState);
                                    setContentView(R.layout.hellochina);
                                    Log.i(Tag,"HelloChinaActivity onCreate");
                                    btna= (Button) findViewById(R.id.buttona);
                                    btnb= (Button) findViewById(R.id.buttonb);
                                    btna.setOnClickListener(this);
                                    btnb.setOnClickListener(this);
        Bundlebundle=this.getIntent().getExtras();
        Log.i(Tag,"获取到传过来的数据"+bundle.getString("world"));
                                 }
 
                                 @Override
                                 protectedvoid onStart() {
                                    //TODO Auto-generated method stub
                                    super.onStart();
                                    Log.i(Tag,"HelloChinaActivity onStart");
                                 }
 
                                 @Override
                                 protectedvoid onRestart() {
                                    //TODO Auto-generated method stub
                                    super.onRestart();
                                    Log.i(Tag,"HelloChinaActivity onRestart");
                                 }
 
                                 @Override
                                 protectedvoid onResume() {
                                    //TODO Auto-generated method stub
                                    super.onResume();
                                    Log.i(Tag,"HelloChinaActivity onResume");
                                 }
 
                                 @Override
                                 protectedvoid onPause() {
                                    //TODO Auto-generated method stub
                                    super.onPause();
                                    Log.i(Tag,"HelloChinaActivity onPause");
                                 }
 
                                 @Override
                                 protectedvoid onStop() {
                                    //TODO Auto-generated method stub
                                    super.onStop();
                                    Log.i(Tag,"HelloChinaActivity onStop");
                                 }
 
                                 @Override
                                 protectedvoid onDestroy() {
                                    //TODO Auto-generated method stub
                                    super.onDestroy();
                                    Log.i(Tag,"HelloChinaActivity onDestroy");
                                 }
 
                                 @Override
                                 protectedvoid onActivityResult(int requestCode, int resultCode, Intent data) {
                                    //TODO Auto-generated method stub
                                    super.onActivityResult(requestCode,resultCode, data);
                                    Log.i(Tag,"HelloChinaActivity onActivityResult");
                                 }
 
                                 //按钮事件
                                 @Override
                                 publicvoid onClick(View v) {
                                    //TODO Auto-generated method stub
                                    switch(v.getId()) {
                                    caseR.id.buttona:
                                        Intentintent1=new Intent();
                                        intent1.setClass(HelloChinaActivity.this,HelloWorldActivity.class);//设置跳转到HelloChinaActivity          
                                        startActivity(intent1);//开始跳转
                                        HelloChinaActivity.this.finish();
                                        break;
                                    caseR.id.buttonb:
                                         //获取之前传过来的数据
                                        Stringworld=this.getIntent().getExtras().getString("world");
                                        if(world!=null)
                                        {
                                            world=world+"hello,china!";//修改后返回
                                        }
                                        Intentintent2=new Intent();
                                                                     //intent2.setClass(HelloChinaActivity.this,HelloWorldActivity.class);//这里可设置也可不设置
                                        Bundlebundle2=new Bundle();
                                        bundle2.putString("china",world);
                                        intent2.putExtras(bundle2);
                                        intresultCode=12;
                                        setResult(resultCode,intent2);//返回HelloWorldActivity
                                        HelloChinaActivity.this.finish();//这里不finish就不会返回HelloWorldActivity
                                        break;
                                  
                                    }
                                 }
 
}
 
 
第三步、AndroidManifest.xml注册Activity
<?xml version="1.0"encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.figo.helloworld"android:versionCode="1"
    android:versionName="1.0">
    <uses-sdkandroid:minSdkVersion="8" />
 
    <applicationandroid:icon="@drawable/icon" android:label="@string/app_name">
        <activityandroid:name=".HelloWorldActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <activityandroid:name=".HelloChinaActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>
 
第四步、运行效果
从logcat里我们可以清晰看到日志,
Activity的启动流程是onCreate()->onStart()->onResume(),
销毁是onPause()->onStop()->onDestroy()。
 
Helloworldactivity
 
 
Hellochinaactivity
 

 

程序刚启动时生命周期:
 

 

普通跳转startActivity:
 

 

普通跳转返回startActivity:
 

 

要求带有返回值的跳转startActivityForResult:
 

 

 
要求带有返回值的跳转返回setResult:
 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。