ChessAndComputer
爱人者人恒爱之是一个假命题

导航

 

Activity可以说是Android世界最重要的类之一,是android四大核心组件之一,顾名思义,Activity就是活动的意思,在android 程序中Activity提供了用户可视界面,是用户与程序交互的接口,每个App至少都要有一个Activity。下面我们来看看Activity是如何使用的。

打开Android studio ,创建一个新的Android project,我这里命名为ActivityTest。此外使用安装了SDK 的Eclipse也可以创建新的android 工程,相信有兴趣学习android 的同学都已经搞的比较清楚了,这里就不说IDE的细节了。

如下图,Android studio会自动为我们创建一个继承于Activity的MainActivity类,

package test.xans.com.activitytest;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
      
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    
}

我们可以点击Activity进去打开Activity的源码,从注释上可以知道这个类的作用

/**
An activity is a single, focused thing that the user can do. Almost all
activities interact with the user, so the Activity class takes care of
creating a window for you in which you can place your UI with
{@link #setContentView}. While activities are often presented to the user
as full-screen windows, they can also be used in other ways: as floating
windows (via a theme with {@link android.R.attr#windowIsFloating} set)
or embedded inside of another activity (using {@link ActivityGroup}).
 There are two methods almost all subclasses of Activity will implement:

<ul>
<li> {@link #onCreate} is where you initialize your activity. Most
importantly, here you will usually call {@link #setContentView(int)}
with a layout resource defining your UI, and using {@link #findViewById}
to retrieve the widgets in that UI that you need to interact with
programmatically.

<li> {@link #onPause} is where you deal with the user leaving your
activity. Most importantly, any changes made by the user should at this
point be committed (usually to the
{@link android.content.ContentProvider} holding the data).
</ul>
*/

 Activity是一个用户可以做的单一且专注的事物,几乎所有的activities都关系着用户,所以Activity类关心着为你创建一个摆放UI(User interface 用户界面)的窗口通过使用setContentView()的方法,虽然Activity经常作为满屏窗口呈现给用户,他们也可以使用不同的方式:例如浮动的窗口(通过设置主题)或者嵌入其他的activity内部(使用ActivityGroup)。

有两个方法基本所有Activity的子类都会实现的,onCreate()方法,初始化activity和调用setContentView(int resId)设置UI。onPause()方法,当用户离开activity的时候应该做何种处理,最重要的是任何用户制造的变化都应该在这个地方去做提交处理。

也就说Activity会通过这个方法setContentView(R.layout.activity_main)设置一个呈现给用户的UI界面,activity通常是以满屏的方式呈现给大家,当然也可以有不同的方式,例如使用activity主题设为浮动的窗口或者使用ActivityGroup把一个Activity嵌入到另一个activity的内部(这种方式几乎已经绝种了,现在大多数使用Fragment来做这方面的需求了)。两个很重要的方法onCreate()和onPause(),其实android还有几个十分常见的方法让我们一一认识。

下面我们看看Activity的那些常见的方法,此外想告诉大家的是养成打印log的习惯,这是一个跟踪调式程序走向和检测程序数据的方法。我先贴出源代码

MainActivity.java

public class MainActivity extends Activity {

    public static String TAG = "MainActivity -> " ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG,TAG+"onCreate");
        setContentView(R.layout.activity_main);

        if(savedInstanceState != null)
        {
            Log.i(TAG,TAG+savedInstanceState.get("key"));
        }

        Button btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this,AnotherActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     *onCreate()方法或者onRestart()方法之后调用此方法,此方法执行过后调用onResume()方法,
     * 记住不能屏蔽调用super.onStart(),否则会产生异常。
     */
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,TAG+"onStart");
    }


    /**
     * 当activity调用onStop()之后,如果界面再次重现给用户的时候就会调用onRestart()方法,
     * 再调用onStart()然后onResume()。
     * 记住不能屏蔽调用super.onRestart(),否则会产生异常。
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG,TAG+"onRestart");
    }


    /**
     * onRestoreInstanceState()或onRestart()或onPause()之后调用
     * 这里可以做一些完善或者恢复activity的操作
     * 记住不能屏蔽调用super.onResume(),否则会产生异常。
     */
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,TAG+"onResume");
    }

    /**
     *取回activity被杀死之前保留的状态
     * 或者在杀死activity的时候存储一些需要恢复的数据
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG,TAG+"onSaveInstanceState");
        outState.putString("key","myData");
    }


    /**
     * 如果activity是从之前保存状态重新初始化的时候就会在onStart()调用之后调用
     */
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG,TAG+"onRestoreInstanceState");
    }

    /**
     * 调用这个方法之后activity被放到后台但没有被杀死,界面还可视
     */
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,TAG+"onPause");
    }

    /**
     * 调用这个方法之后界面就不可视了
     * 如果系统内存过低activity将可能被杀死
     */
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,TAG+"onStop");
    }

    /**
     * activity实例被销毁
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,TAG+"onDestroy");
    }
}

 AnotherActivity.java

public class AnotherActivity extends Activity {

    public static String TAG = "AnotherActivity -> ";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        Log.i(TAG, TAG+"onCreate");

    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG,TAG+"onStart");
    }
    
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG,TAG+"onRestart");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG,TAG+"onResume");
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.i(TAG,TAG+"onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.i(TAG,TAG+"onRestoreInstanceState");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG,TAG+"onPause");
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG,TAG+"onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG,TAG+"onDestroy");
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
   >

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="52dp" />

</RelativeLayout>

content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

AndroidManifest.xml文件加入一行

 

 <activity android:name=".AnotherActivity"></activity>

 

下面介绍Activity的生命周期,先看下图给大家一个感性的认识。

接下来我们设置各位使用场景去了解Activity的生命周期

1.打开Activity的时候Activity方法的调用情况

Activity启动的时候会依次回调onCreate()-> onStart()-> onResume()。

2.退出Activity的时候Activity方法的调用情况(这里是点击手机上的返回键也就是home键)

Activity调用了onPause()-> onStop()-> onDestroy()。

3.长按Home键退回桌面的时候Activity方法的调用情况

Activity调用了onPause()-> onSaveInstanceState()-> onStop()。

4.长按Home键退回桌面再点击进去的时候Activity方法的调用情况

Activity调用了onRestart()-> onStart()-> onResume()。

5.Activity转屏幕的时候Activity方法的调用情况

这里可以看出activity转屏幕其实是销毁一个activity实例到新建一个activity的过程,当转屏幕的时候先调用onPause(),然后调用onSaveInstanceSate()来存储一些数据,下图是onSaveInstanceState()的方法体

,之后调用onStop()和onDestroy停止销毁activity,接着就是新建一个activity了,调用onCreate(),onCreate(Bundle saveInstanceState)的参数saveInstanceState保存着onSaveInstanceState(Bundle outState)

的参数outState保存的参数,从这里可以取出保存的数据,这个有什么用呢?例如看视频转屏幕的时候可以存储视频的当前进度,游戏进度等。再下来就是正常的开启一个activity的步骤了。只是多了那个onRestartInstanceState()

方法,这个方法是如果一个activity是从之前保存状态重新初始化的时候就会在onStart()调用之后调用。这些操作大多数都在onCreate()方法做了。

onPause() ->onSaveInstanceState() -> onStop() ->onDestroy() -> onCreate() -> onStart() -> onRestoreInstanceState()。

6.开启着Activity然后系统锁屏待机之后的方法调用

onPause() -> onSaveInstanceState() -> onStop()。

7.重新解锁进入Activity的方法调用

8.从一个Activity跳转到另一个Activity的方法调用情况

(MainActivity)onPause() -> (AnotherActivity) onCreate() -> (AnotherActivity)onStart() -> (AnotherActivity)onResume() -> (MainActivity)onSaveInstanceState() -> (MainActivity)onStop()。

9.从一个Activity返回的时候方法的调用情况

 (AnotherActivity)onPause() -> (MainActivity)onRestart() -> (MainActivity)onStart() -> (MainActivity)onResume() -> (AnotherActivity)onStop() -> (AnotherActivity)onDestroy()。

由此我们基本上可以整理出Activity生命周期的大概情况了,就是上面已经贴出的那幅Activity生命周期方法调用图,这里再贴一次。

 

 

关键是多练习多调试,相信大家都可以轻松了解到了Activity的基本使用以及它的方法调用了。这些方法都是回调方法由系统去调用的,我们需要做什么只要在对应的方法里面实现自己的逻辑就可以了!希望大家能从中学习到一点东西!我的下一篇文章将介绍Activity的四种启动模式,谢谢大家的支持!

 

posted on 2017-09-01 23:44  ChessAndComputer  阅读(182)  评论(0)    收藏  举报