java攻城狮之路(Android篇)--Activity生命

一:Activity的激活

1、写一个类 extends Activity
Activity是android的四大组件之一。
Activity的激活分为显式意图激活和隐式意图激活。
如果一个activity希望别人隐式意图激活,则要配置过滤器
1 action = "com.shellway.itentab.*"
2 有一个缺省的category,(可以有多个category),若不配置该类型会发生这样的一个错误:Caused by: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=cn.itcast.action.main3 }
设置scheme标识如: http:// content:// tel:

隐式意图激活:就是看要要激活的组件里面的intent-filter,看它是如何编写要有action,category,data。

配置意图过滤器就相当于给一个activity取了一个别名。一个activity可以配置多个intent-filter

练习:

package com.shellway.itentab;

import android.support.v7.app.ActionBarActivity;
import android.content.ClipData.Item;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void open(View view){
        switch (view.getId()) {
        case R.id.bt_open1:
            //4种显式意图激活方式
            Intent intent1 = new Intent(this,Main2Activity.class);
            //    intent.setClass(this, Main2Activity.class);
            //     intent.setClassName(this, "com.shellway.itentab.Main2Activity");
            //    intent.setClassName("com.shellway.itentab", "com.shellway.itentab.Main2Activity");
            startActivity(intent1);
            break;
        case R.id.bt_open2:
            Intent intent2 = new Intent();
            //设置动作
            intent2.setAction("com.shellway.itent.Main3Activity");
            //设置数据
    //        intent2.setData(Uri.parse("shellway:"));
            //设置类型
    //        intent2.setType("image/jpeg");
            //若设置了类型,它就必须和数据一起设置,分开设置不行
            intent2.setDataAndType(Uri.parse("shellway:"), "image/jpeg");
            startActivity(intent2);
            break;
        case R.id.bt_open3:
            Intent intent3 = new Intent();
            intent3.setAction("android.intent.action.VIEW");
            intent3.setData(Uri.parse("http://www.baidu.com"));
            startActivity(intent3);
            break;
        default:
            break;
        }
        
    }
}
MainActivity.java
package com.shellway.itentab;

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

public class Main2Activity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
}
Main2Activity.java
package com.shellway.itentab;

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

public class Main3Activity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
    }
}
Main3Activity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是第一个activity" />
    <Button 
        android:id="@+id/bt_open1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="open"
        android:text="显示意图激活"
        />
    <Button android:id="@+id/bt_open2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="open"
        android:text="隐式意图激活"
        />
    <Button android:id="@+id/bt_open3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="open"
        android:text="打开浏览器"
        />

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
         android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:text="显式意图激活"
        />

</LinearLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="隐式意图激活"
        />
    

</LinearLayout>
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.itentab"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- 第一个activity  -->
        <activity
            android:name=".MainActivity"
            android:label="第一个activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 第二个activity 显式激活-->
        <activity android:name=".Main2Activity" android:label="第二个activity" />
        <!-- 第三个activity 隐式激活 -->
        <activity android:name=".Main3Activity" android:label="第三个activity">
            <intent-filter >
                <action android:name="com.shellway.itent.Main3Activity" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="shellway"  android:mimeType="image/jpeg" />
            </intent-filter>
        </activity>
        
    </application>

</manifest>
AndroidMainfest.xml

运行结果截图:

 二:Activity之间的数据传输(通过Intent)

1、Bundle 其实是对应HashMap的封装。该类本身实现了Parceleable接口。
同样,我们这里写一个Person类实现Parcelable接口,然后用intent.putExtra(String name, Parcelable value)
和intent.getParcelableExtra(String name)方法来分别存、取对象。

练习(三种数据传输方式):

package com.shellway.domain;

import android.os.Parcel;
import android.os.Parcelable;

public class Person implements Parcelable {

    private int id;
    private String name;
    private int age;
    
    @Override
    public int describeContents() {
        return 0;
    }
    
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        //这里的数据的读取顺序要与声明时的一直
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeInt(age);
    }
    public static final Parcelable.Creator<Person> CREATOR
       = new Parcelable.Creator<Person>() {
        public Person createFromParcel(Parcel in) {
          //这里返回的是下面带参的出事化后的Person类
          return new Person(in);
    }

    public Person[] newArray(int size) {
      return new Person[size];
    }
  };
    //这里的数据的初始化顺序要与声明时的一直
    public Person(Parcel in){
       id = in.readInt();
       name = in.readString();
       age = in.readInt();
 }

    public Person(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
Person.java
package com.shellway.passdata;

import com.shellway.domain.Person;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends ActionBarActivity {

    private EditText et_username;
    private EditText et_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获得用户输入的数据
        et_username = (EditText) findViewById(R.id.et_username);
        et_password = (EditText) findViewById(R.id.et_password);
    }
    public void enter(View view){
        String username = et_username.getText().toString();
        String password = et_password.getText().toString();
        //应用内部的数据传输是通过intent来传输的,它相当于网页中的request对象。
        Intent intent = new Intent(this,ReceiveDataActivity.class);
    //  1、传输数据的第一种方式
    //    intent.putExtra("username", username);
    //    intent.putExtra("password", password);
    //  2、传输数据第二种方式        
        Bundle bundle = new Bundle();
        bundle.putString("username", username);
        bundle.putString("password", password);
        intent.putExtras(bundle);
    //    3、传输数据第三种方式,传输对象类型数据.
        Person person = new Person(100,"shellway",25);
        intent.putExtra("person", person);
        //这里是显式激活ReceiveDataActivity
        startActivity(intent);
    }
}
MainActivity.java
package com.shellway.passdata;

import com.shellway.domain.Person;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class ReceiveDataActivity extends Activity {
     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.receive_data);
        TextView tv_receive = (TextView) findViewById(R.id.tv_receive);
      //获得从上一个activity传过来的数据,谁激活我这个activity就从那个activity传过来。
        Intent intent = getIntent();
      //从intent对象中拿到数据    
    //    String username = intent.getStringExtra("username");
    //    String password = intent.getStringExtra("password");
        
        Bundle bundle = intent.getExtras();
        String username = bundle.getString("username");
        String password = bundle.getString("password");
        
        Person person = intent.getParcelableExtra("person");
        
      //把数据设置到界面上
        tv_receive.setText("用户名:"+username+",密    码:"+password 
                                  +"   \n对象:"+person.toString());
    }
}
ReceiveDataActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="用户名" />
    <EditText 
        android:id="@+id/et_username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入用户名"
        />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="密码" />
    <EditText 
        android:id="@+id/et_password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="enter"
        android:text="进入"
        />

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView 
         android:id="@+id/tv_receive"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
        />

</LinearLayout>
receive_data.xml

运行结果截图:

2、打开一个Activity返回结果:

分析:

package com.shellway.getdataforresult;

import android.support.v7.app.ActionBarActivity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    private EditText data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        data = (EditText) findViewById(R.id.et_data);
    }

   public void get(View view){
       Intent intent = new Intent(this,MainActivity2.class);
       //参数100为请求码,标识请求数据来源
       startActivityForResult(intent, 100);
   }
   @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        String name = intent.getStringExtra("name");
        if (requestCode==100) {
            if (intent!=null) {
                data.setText(name);
            }
        }else{
            Toast.makeText(this, "获取数据失败", Toast.LENGTH_SHORT).show();
        }
    }
   //若用户在此activity点击返回键,就finish()
   @Override  
   public boolean onKeyDown(int keyCode, KeyEvent event)  
   {  
       if (keyCode == KeyEvent.KEYCODE_BACK )  
       {  
           // 创建退出对话框  
           AlertDialog isExit = new AlertDialog.Builder(this).create();  
           // 设置对话框标题  
           isExit.setTitle("系统提示");  
           // 设置对话框消息  
           isExit.setMessage("确定要退出吗");  
           // 添加选择按钮并注册监听  
           isExit.setButton2("取消", listener);  
           isExit.setButton("确定", listener);  
           // 显示对话框  
           isExit.show();  
       }  
       return false;  
   }  
   /**监听对话框里面的button点击事件*/  
   DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()  
   {  
       public void onClick(DialogInterface dialog, int which)  
       {  
           switch (which)  
           {  
           case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序  
               android.os.Process.killProcess(android.os.Process.myPid());    //获取PID 
               System.exit(0); 
               break;  
           case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框  
               break;  
           default:  
               break;  
           }  
       }  
   }; 
}
MainActivity.java
package com.shellway.getdataforresult;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity2 extends Activity {
    private ListView lv;
    private MyBaseAdapter myBaseAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        
        myBaseAdapter = new MyBaseAdapter();
        
        lv = (ListView) findViewById(R.id.lv_data);
        lv.setAdapter(myBaseAdapter);
        lv.setOnItemClickListener(new MyOnItemClickListener());
    }
    private class MyOnItemClickListener implements OnItemClickListener{

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            String name =  (String) myBaseAdapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("name", name);
            //参数200为结果码,标识返回结果数据来源
            setResult(200, intent);
            finish();
        }
    }
    
    private class MyBaseAdapter extends BaseAdapter{
        String[] data = new String[]{"赵高","刘邦","项羽","楚南公","葛聂"};
        @Override
        public int getCount() {
            return data.length;
        }

        @Override
        public Object getItem(int position) {
            return data[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView tv = new TextView(getApplicationContext());
            tv.setTextSize(25);
            tv.setTextColor(Color.BLUE);
            tv.setText(data[position]);
            return tv;
        }
    }
    //若用户在此界面直接按返回键,则结束自己 重新开启上一个界面
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            Intent myIntent = new Intent();
            myIntent = new Intent(MainActivity2.this, MainActivity.class);
            startActivity(myIntent);
            this.finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}
MainActivity2.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="获取的数据:" />
    <EditText 
        android:id="@+id/et_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="get"
        android:text="获取"
        />

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <ListView 
        android:id="@+id/lv_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        ></ListView>

</LinearLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.getdataforresult"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.RESTART_PACKAGES"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity2" android:label="数据列表"/>
    </application>

</manifest>
AndroidManifest.xml

点击获取后的结果截图:

三、Activity的作用:
起显示作用,他是用来和用户交互的。也是一个view的容器
1 完整的生命周期:
onCreate() --> onStart() --> onResume() activiyt已经正常显示
点击回退键
onPause() --> onStop() --> onDetroy()

2、可视的生命周期
onCreate() --> onStart() --> onResume() activiyt已经正常显示
打开一个activity。该activity完全覆盖上一个activity
onPause() ---> onStop()
点击回退键
onRestart() --> onStart() ---> onResume()
点击回退键
onPause() --> onStop() --> onDetroy()

3、前台生命周期
首先把第二个Activity配置:android:theme="@android:style/Theme.Dialog"
就可以把activity变成对话框的效果,注意:如果在一个Activity中弹出对话框,则不会执行任何一个方法。
onCreate() --> onStart() --> onResume() activiyt已经正常显示
打开一个activity。该activity没有完全覆盖上一个activity
onPause()
点击回退键
onResume()

横竖屏切换的时候:
竖屏到横屏:activity首先被销毁,在创建一个新的activity
横屏到竖屏:activity首先被销毁,再创建一个新的activity,再把该activity销毁,再创建一个新的activity.(是由于输入法的影响)

生命周期代码:

package com.shellway.lifecycle;

import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends ActionBarActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Log.i(TAG, " onCreate ");
        
    }
    
    public void open1(View view){
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
    }
    public void open2(View view){
        Intent intent = new Intent(this,Main2Activity.class);
        startActivity(intent);
    }
    
    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, " onStart ");
    }
    
    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, " onRestart ");
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, " onResume ");
    }
    
    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, " onPause ");
    }
    
    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, " onStop ");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, " onDestroy ");
    }
    
}
MainActivity.java
package com.shellway.lifecycle;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class Main2Activity extends Activity {
     private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }
     
     public void open1(View view){
        Intent intent = new Intent(this,MainActivity.class);
        startActivity(intent);
    }
     
    public void open2(View view){
        Intent intent = new Intent(this,Main2Activity.class);
        startActivity(intent);
    }
}
Main2Activity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="open1"
       android:text="打开A界面"
       />
   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="open2"
       android:text="打开B界面"
       />

</LinearLayout>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >

   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="open1"
        android:text="打开A界面"
       />
   <Button 
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:onClick="open2"
        android:text="打开B界面"
       />

</LinearLayout>
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.lifecycle"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="第一个Activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Main2Activity" android:label="第二个Activity" 
                  android:theme="@android:style/Theme.Dialog"/>
    </application>

</manifest>
AndroidManifest.xml

4、任务栈task、进程Process 

task的作用:就是用来管理activity的进入,退出。记录了用户的行为。
位于任务栈栈顶的activity就是和用户交互的。
任务栈里面存放的是:activity的引用

下面详细介绍activity的四种启动模式:

1、standard
    standard模式是默认的启动模式,不用为<activity>配置android:launchMode属性即可,当然也可以指定值为standard。
    standard模式是所启动的Activity都是在同一个task容器栈下,不会重新创建新的task容器栈。先压入栈的Activity实例按顺序入栈底,后入栈在栈顶,处于栈的顶部Activity实例处于活动状态,其他处于非活动状态。按物理返回键,退出当前所处活动状态Activity窗口,这样就会从task容器栈中弹出,显示在手机主屏幕上,从而,有非活动状态转换成活动的状态。其次,standard容器栈可能会存在着相同的Activity实例,只有没调用一次startActivity方法,就会创建目标Activity实例对象压入task容器栈。

2、singleTop
    AndroidManifest.xml文件中<activity>launchmode属性配置singletop,那么启动实例化Activity,如果task容器栈顶存在已经激活的Activity实例,就会重用当前栈顶的Activity实例,不会再重新去实例化Activity对象。善于思考的朋友可能会问,如果要启动的目标Activity已经有实例化对象存在task容器栈里面,只是现在不处于栈顶,这样情况下,singletop启动模式会创建目标Activity实例吗?答案是肯定的。要启动的目标Activity实例正好处于栈顶,才能重用该实例,其他情况必须创建新实例。

 

3、singleTask
singletask模式,特别需要注意了。启动的目标Activity实例如果已经存在task容器栈中,不管当前实例处于栈的任何位置,是栈顶也好,栈底也好,还是处于栈中间,只要目标Activity实例处于task容器栈中,都可以重用该Activity实例对象,然后,把处于该Activity实例对象上面全部Activity实例清除掉,并且,task容器栈中永远只有唯一实例对象,不会存在两个相同的实例对象。所以,如果你想你的应用不管怎么启动目标Activity,都只有唯一一个实例对象,就使用这种启动模式。

 

4、singleInstance
singleInstance启动模式,简单说就是可以共享某个Activity。比如,应用1的任务容器栈中创建了MainActivity实例,应用2也要激活MainActivity,则不需要创建MainActivity实例,直接可以公用MainActivity实例。尤其值得注意:应用1启动MainActivity,按home键;打开应用2启动应用1的MainActivity实例。在按home键,打开应用1,这时候应用1的界面是应该是处于MainActivity界面实例。

5、理解一些概念
进程:是一个应用程序运行的空间。一个android应用就是一个进程。进程就有他自己的内存空间。
一个进程里面可以有多个线程。在两个进行之间进行切换是非常好性能。
线程:一个控件单元。
一个task可以对应多个进程。
每个activity的实例是运行在自己的进程里面。
activity程序默认是一个单独的线程里面来运行。onCreate() 按钮点击回调事件、对于显示的操作都是在主线程里面运行即:UI线程。对于那些耗时的操作不适宜放在主线程里面执行,比如
联网获取数据、大文件的拷贝,都需要放置在子线程来操作。
在子线程里执行耗时操作后获得数据后要更新主界面,可以通过消息机制来解决,因为只有主线程才能对显示进行操作。,否则会报一下错误:
08-29 08:07:41.200: E/AndroidRuntime(1327):
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Handler :用于子线程和主线程之前的通信。
采用是就消息模式,当子线程完成操作,给主线程发送消息。让主线程来处理显示的更新。
子线程和主线程之前的通信练习:

package com.shellway.changeview;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    protected static final int CHANGE_UI = 0;
    private TextView tv;
    
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case CHANGE_UI:
                int i = (Integer) msg.obj;
                tv.setText(i+"");//设置显示信息,注意是String类型
                break;
            default:
                break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv_number);
    }
    
    public void add(View view){
        new Thread(){
            public void run() {
                int i = 0;
                while (i<20) {
                    i = i + 1;
                    SystemClock.sleep(300);//每0.3秒执行一次
                    //创建一个消息对象来传递数据
                    Message msg = new Message();
                    //标识消息对象类型
                    msg.what = CHANGE_UI;
                    //封装数据到消息对象
                    msg.obj = i;
                    //发送消息对象
                    handler.sendMessage(msg);
                }
            };
        }.start();
    }
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="自动增加的数据:" />
    <TextView
        android:id="@+id/tv_number"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="0" />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="add"
        android:text="增加"
        />
    

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.changeview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="子线程通过消息更新界面数据" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
AndroidManifest.xml

运行结果截图:

6:五种对话框
对话框的创建采用的是构建器模式:

package com.shellway.mydialog;

import android.support.v7.app.ActionBarActivity;
import android.text.AlteredCharSequence;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    
    /**普通对话框
     * 步骤: 1、创建构建器
     *     2、给构建器设置属性: 标题 、内容、按钮
     *     3、创建dialog
     *     4、显示对话框
     */
    public void generalDialog(View view){
          //创建构建器
      AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(false);//使物理回退键失效
          builder.setTitle("shellway的博客");
          builder.setMessage("你会经常来看我的博客吗?");
          //设置按钮监听事件
          builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                
            }
          });
          //设置按钮监听事件
          builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            
            @Override
            public void onClick(DialogInterface dialog, int which) {
                
            }
          });
          
          //创建dialog,并显示
          Dialog dialog = builder.create();
          dialog.show();
    }
    
    //选择对话框
    public void selectedDialog(View view){
          final String[] items = new String[]{"公子扶苏","李斯","张良"};
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(false);//使物理回退键失效
          builder.setTitle("shellway的博客");
          //设置点击监听事件
          builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), items[which], 0).show();
            }
          });
          
          //创建dialog,并显示
          Dialog dialog = builder.create();
          dialog.show();
    }
    
    //单选对话框
    public void singleChoiceDialog(View view){
          final String[] items = new String[]{"公子扶苏","李斯","张良"};
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(false);//使物理回退键失效
          builder.setTitle("shellway的博客");
          //设置点击监听事件
          builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(getApplicationContext(), items[which], 0).show();
            }
          });
          //设置确定按钮监听事件
          builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
            }
          });
          
          //创建dialog,并显示
          Dialog dialog = builder.create();
          dialog.show();
    }
    
    //多选对话框
    public void multiChoiceDialog(View view){
          final String[] items = new String[]{"公子扶苏","李斯","张良"};
          final boolean[] flag = new boolean[]{true,false,false};
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(false);//使物理回退键失效
          builder.setTitle("shellway的博客");
          //设置点击监听事件
          builder.setMultiChoiceItems(items, flag, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                // TODO Auto-generated method stub
            
            }
          });
          //设置确定按钮监听事件
          builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                StringBuilder sb = new StringBuilder();
                
                for (int i = 0; i < items.length; i++) {
                    if(flag[i]){
                        sb.append(items[i]+" ");
                    }
                }
                String info =sb.toString();
                Toast.makeText(getApplicationContext(), info, 0).show();
            }
          });
          
          //创建dialog,并显示
          Dialog dialog = builder.create();
          dialog.show();
    }
    
    //自定义对话框
    public void customDialog(View view){
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setCancelable(false);//使物理回退键失效
          builder.setTitle("shellway的博客");
          //加载自定义布局文件
          LayoutInflater mInflater = LayoutInflater.from(this);
          View dialogView = mInflater.inflate(R.layout.custom, null);
          builder.setView(dialogView);
          //创建dialog
          final Dialog dialog = builder.create();
          dialog.show();
          Button bt_ok = (Button) dialogView.findViewById(R.id.bt_ok);
          Button bt_cancel = (Button) dialogView.findViewById(R.id.bt_cancel);
          //设置按钮监听事件
          bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();//让对话框消失
            }
          } );
          //设置按钮监听事件
          bt_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();//让对话框消失
                }
         } );
    }
}
MainActivity.java
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
     >
 
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="generalDialog"
        android:text="普通对话框"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="selectedDialog"
        android:text="选择对话框"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="singleChoiceDialog"
        android:text="单选对话框"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="multiChoiceDialog"
        android:text="多选对话框"
        />
    <Button 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="customDialog"
        android:text="自定义对话框"
        />

</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        />
    <EditText 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="请再次输入密码"
        />
    
    <LinearLayout 
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:orientation="horizontal" >
       <Button 
            android:id="@+id/bt_ok"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="ok"
            android:text="确定"
           />
       <Button 
            android:id="@+id/bt_cancel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="cancel"
            android:text="取消"
           />

   </LinearLayout>

</LinearLayout>
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.shellway.mydialog"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            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>
AndroidManifest.xml

运行结果截图:

 

 注意啦:本章复习笔记未完,后面会继续更新完善。。。。。。

 

posted @ 2014-12-15 21:27  骄阳08  阅读(3379)  评论(0编辑  收藏  举报