主頁 > 移動端開發 > 【Android】安卓四大組件之Activity(一)

【Android】安卓四大組件之Activity(一)

2022-01-18 08:42:32 移動端開發

【Android】安卓四大組件之Activity(一)

前言

Activity是Android學習中的一個重要組件,想要對其進行系統的了解可以分為幾塊內容,這一大章節的內容是有關于activity之間的頁面跳轉和資料傳遞,之后還有activity中的生命周期講解,

1、認識AndroidManifest.xml

一個Manifest.xml最外層用manifest標簽包裹,下面可以是application,當然我們之前也學過uses-permission,可以與application同級

application中設定屬性,allowBackup是允許備份,icon是app圖示,label是app的名字,roundIcon是圓角app圖示,supportsRtl是宣告你的application是否愿意支持從右到左(原來RTL就是right-to-left 的縮寫…)的布局,theme當然就是主題啦!

Rtl到底是個啥玩意?有沒有在QQ中見過使用阿拉伯語的,使用這些語言都是從右向左讀的,所以需要從右向左適配,就是這樣!

activity就是這次學習的重點,是一個活動,也可以當作不同的活躍頁面(大致理解),我們app中不同的界面就可以通過activity之間的跳轉實作!

至于intent-filter,就是一個意圖過濾器,其中的action就是activity進行的一個action,而category可以理解為這個意圖的類別,我們APP的主界面的category就是LAUNCHER

image-20220115211002836

2、如何實作activity之間的跳轉?

我們可以使用startActivity()方法或者startActivityForResult()方法來跳轉頁面,這一小節就只講startActivityintent配合使用進行資料單項傳遞,在第4小節回講到如何使用startActivityForResult進行資料回傳

2.1 通過顯式Intent來跳轉同一個APP中的activity

顯式Intent:按照名稱(完全限定了類名)來指定要啟動的組件,

可以看到下面的xml中注冊了兩個activity分別對應兩個activity類

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Hello">
        <activity
            android:name=".QQLoginActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".QQLoginSuccessActivity"/>
    </application>

需要注意的是,創建顯式Intent啟動Activity,系統將立刻啟動Intent物件中指定的應用組件,

那么我來實際操作一個例子看看顯式Intent如何跳轉!

我們寫一個登錄頁面的跳轉測驗用例,如果登錄成功,就跳轉到另一個activity頁面中顯示登錄的資訊!

第一個頁面:登錄界面xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@mipmap/bk">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="70dp"
        android:padding="30dp"
        android:orientation="vertical">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:drawableLeft="@mipmap/ic_launcher_round"
            android:text="QQ"
            android:textSize="40sp"/>
        <EditText
            android:id="@+id/et_account"
            android:layout_marginTop="25dp"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:textColor="@color/white"
            android:hint="QQ號/手機號/郵箱"/>

        <EditText
            android:password="true"
            android:id="@+id/et_pwd"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="密碼"
            android:textColor="@color/white"
            tools:ignore="Deprecated" />

        <Button
            android:id="@+id/bt_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="登陸"
            android:textSize="20sp"/>

        <RelativeLayout
            android:layout_marginTop="15dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="忘記密碼"
                android:textSize="16dp"
                android:textColor="#87C6F8"/>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:text="新用戶注冊"
                android:textSize="16dp"

                android:textColor="#87C6F8"/>

        </RelativeLayout>

    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:text="登錄即代表閱讀并同意服務條款"
        android:textColor="#CCCFCF"
        android:textSize="20sp" />

</RelativeLayout>

對應的activity java類

package top.woodwhale.hello;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;

public class QQLoginActivity extends Activity implements View.OnClickListener {

    private EditText account;
    private EditText passwd;
    private Button login;

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

    private void initViews() {
        account = this.findViewById(R.id.et_account);
        passwd = this.findViewById(R.id.et_pwd);
        login = this.findViewById(R.id.bt_login);
        // 添加監聽器
        login.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v == login && login != null) {
            String ac = account.getText().toString();
            String pwd = passwd.getText().toString();
            if (TextUtils.isEmpty(ac)) {
                Toast.makeText(this, "賬號不能為空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(pwd)) {
                Toast.makeText(this,"密碼不能為空", Toast.LENGTH_SHORT).show();
                return;
            }
            // 如果都填寫正確,那么跳轉
            Intent intent = new Intent(this,QQLoginSuccessActivity.class);
            intent.putExtra("ac",ac);
            intent.putExtra("pwd",pwd);
            // 當前act跳轉到目的act中,也就是登錄成功界面
            this.startActivity(intent);
        }
    }
}

這一部分是跳轉實作的代碼:

image-20220115211822948

new一個intent,然后如果需要設定鍵值對資訊,就使用putExtra()方法設定鍵值對,最后呼叫當前activity類中的startActivity()方法跳轉到下一個activity中!

第二個頁面:登錄成功xml

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

    <Button
        android:id="@+id/bt_ac_and_pwd"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="賬號:*** 密碼:###"/>

</FrameLayout>

對應的activity java類

package top.woodwhale.hello;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

public class QQLoginSuccessActivity extends Activity {

    private Button btn;

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

        Intent intent = getIntent();
        String ac = intent.getStringExtra("ac");
        String pwd = intent.getStringExtra("pwd");
        btn = findViewById(R.id.bt_ac_and_pwd);
        btn.setText(btn.getText().toString().replace("***",ac).replace("###",pwd));
    }
}

這里通過getStringExtra()方法獲取之前activity中我們設定的鍵值對

image-20220115212043256

測驗效果:

qemu-system-x86_64_jjg6cqDUAb

效果完成!

2.2 通過隱式Intent來跳轉同一個APP中的activity

隱式Intent:不會指定特定的組件,而是會宣告要執行的組件,從而允許其他應用中的組件來處理它,

舉個例子,我們現在要呼叫一個app中的另一個頁面,使用隱式意圖的方式,可以這樣:

// 隱式意圖進行跳轉
Intent intent = new Intent();
intent.setAction("top.woodwhale.qqlogin.LOGIN_INFO");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("ac",ac);
intent.putExtra("pwd",pwd);
this.startActivity(intent);

使用setAction()的方法,將action設定了,這里的action是什么呢?

我們看看最開始的manifest.xml

<activity
          android:name=".QQLoginActivity"
          android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

<activity android:name=".QQLoginSuccessActivity">
    <intent-filter>
        <action android:name="top.woodwhale.qqlogin.LOGIN_INFO"/>
        <category android:name="android.intent.category.DEFAULT"/>
    </intent-filter>
</activity>

這里我們與顯式意圖不同,我們變更了QQLoginSuccessActivity這個activity中的<intent-filter>,也就是意圖過濾器,我們在其中的action中設定了一個nametop.woodwhale.qqlogin.LOGIN_INFO,而與我們java代碼中的intent.setAction("top.woodwhale.qqlogin.LOGIN_INFO");對應!并且category也是一樣,使用的是DEFAULT,也與intent.addCategory(Intent.CATEGORY_DEFAULT);對應,

通過這樣的intent的設定方式,我們其實就是將這個Intent物件設定成為了QQLoginSuccessActivity這個activity!

2.3 通過顯式Intent跳轉到其他APP

我們在使用瀏覽器訪問知乎、csdn等網頁的時候,是不是會讓我們跳轉到APP內使用?其實這就是不同app之間的跳轉,也就是通過瀏覽器這個app跳轉到了csdn這個app

上述的跳轉操作也可以通過Intent實作,我們首先用顯式Intent實作:

比如我現在點擊登錄,需要跳轉到Chrome這個app中,那么顯式Intent需要知道Chrome這個app的packageName和一個activity的className,我們可以使用logcat來抓取這兩個String值,如下圖所示:

首先選擇system_process系統行程,在搜索cmp也就是ComponentName的縮寫,然后在avd上打開Chrome,logcat就可以抓取到啦

image-20220117103614993

那么我們跳轉的核心代碼就是:

Intent intent = new Intent();
intent.setClassName("com.android.chrome","com.google.android.apps.chrome.Main");
this.startActivity(intent);

當然,你也可以這樣,通過ComponentName作為中間件

Intent intent = new Intent();
ComponentName cmp = new ComponentName("com.android.chrome","com.google.android.apps.chrome.Main");
intent.setComponent(cmp);
this.startActivity(intent);

測驗一下

qemu-system-x86_64_60LuXo32z7

2.4 通過隱式Intent跳轉到其他APP

一般跳轉到其他APP都是使用隱式Intent來完成的,而Intent類中已經很多的常量給我們選擇APP

比如Intent.ACTION_DIAL就是電話撥號action,而我們使用setData()方法,給一個tel的值,那么就會撥號這個號碼,注意setData中傳遞的引數是Uri型別的,需要使用Uri.parse()方法轉化一下格式

Intent intent = new Intent();
intent.setAction(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:"+ac));
this.startActivity(intent);

那么這樣的效果就是如下圖所示:

qemu-system-x86_64_8hKTRtcWxe

2.5 對Intent的總結:

顯式Intent的常見方法:

  • setClass( Context packageContext, Class ClassNmae.class), 此方法不能實作跨應用呼叫
  • setClass( String packageName, String classname ), 此方法能夠實作跨應用呼叫
  • setComponent(ComponentName component),此方法能夠實作跨應用呼叫

隱式Intent的常見方法:

  • setAction(String action)
  • addCategory(String category)
  • setData(Uri data)

當然,Intent用的最多的是putExtra()方法,可以傳遞Extra的資料!

總結一下,隱式Intent和顯式Intent的區別是什么呢?

  • 顯式Intent需要給出指定的class,也就是限定了類名
  • 隱式Intent需要給出action、category,可以隱式的呼叫其他activity

說的直白一點:隱式Intent通過給出的action和category來與特定的activity對應起來,而顯式Intent就是指定了一個activity.class

那么,什么情況用什么Intent呢?

  • 顯示Intent一般用來完成同一個APP之間的跳轉
  • 隱式Intent一般用來完成呼叫其他APP
  • 上述并非絕對,顯示Intent也能完成不同APP跳轉,隱式Intent也能完成同一個APP內的跳轉

3、activity之間的資料如何單向傳遞?

這里說的傳遞資料就是分為兩種,一種普通資料,另一種是物件資料

對于activity之間的資料傳遞,都是通過Intent中的putExtra()方法實作,或者setData()方法實作

putExtra其實就是將一個鍵值對放入了intent物件中,取出這個值就通過getXXXExtra()方法就可以實作

setData其實是給了在intent-filter中設定的data屬性一個資料

下面我們就來講講這兩種方式如何傳遞資料!

3.1 putExtra()方法傳遞

3.1.1 普通資料傳輸

對于普通的資料型別:

// 隱式意圖進行跳轉
String ac = account.getText().toString();
String pwd = passwd.getText().toString();
Intent intent = new Intent();
intent.setAction("top.woodwhale.qqlogin.LOGIN_INFO");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("ac",ac);
intent.putExtra("pwd",pwd);
this.startActivity(intent);

我們傳遞了兩個String的資料,在上述隱式intent的目標LOGIN_INFO的activity類中,可以這樣接收資料,通過getStringExtra()方法

Intent intent = getIntent();
String ac = intent.getStringExtra("ac");
String pwd = intent.getStringExtra("pwd");
btn = findViewById(R.id.bt_ac_and_pwd);
btn.setText(btn.getText().toString().replace("***",ac).replace("###",pwd));

同理,可以putExtra各種普通資料——int、boolean等等

3.1.2 物件資料傳輸

對于傳遞物件,在putExtra()方法中有兩個多載方法可以實作:

putExtra(String name, Parcelable value)

putExtra(String name, Serializable value)

image-20220117124133807

這兩個方法的第二個引數就有講究了,

首先,說說Serializable,這個是Java中的序列化類,它是JDK1.1就誕生的介面,用于標識可序列化,在非安卓程式中也是非常常見的存在,

所謂序列化就是一種壓縮,可以理解成一個物件壓縮成JSON的那種形式,只不過在JVM中處理肯定不是JSON的格式

序列化之后的物件可以通過反序列化得到原來的物件

我們對該介面的描述進行翻譯一下:

image-20220117124421949

image-20220117125119277

image-20220117124754987

其次,就是這個沒見過的Parcelable,這個類是Google自己實作的,也是用來進行壓縮記憶體的,效率方面比Serializable高,

我們對這個介面的描述進行翻譯:

image-20220117124950909

image-20220117125047574

所以如果我們需要對一個物件進行activity之間的傳遞,可以讓這個物件所屬的類使用上述兩種介面之一,就好啦!

我們這里使用Pracelable介面實作一個User類

package top.woodwhale.hello;

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

public class User implements Parcelable {
    String username;
    String password;

    public User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    protected User(Parcel in) {
        username = in.readString();
        password = in.readString();
    }
    
    public static final Creator<User> CREATOR = new Creator<User>() {
        @Override
        public User createFromParcel(Parcel in) {
            return new User(in);
        }

        @Override
        public User[] newArray(int size) {
            return new User[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(username);
        dest.writeString(password);
    }
}

我們對一個activity進行傳輸一個user物件:

// 隱式意圖進行跳轉
Intent intent = new Intent();
intent.setAction("top.woodwhale.qqlogin.LOGIN_INFO");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.putExtra("user1",new User("woodwhale","1234567"));
this.startActivity(intent);

我們需要傳遞的activity類如下:

public class QQLoginSuccessActivity extends Activity {

    private Button btn;

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

        Intent intent = getIntent();
        User user1 = intent.getParcelableExtra("user1");
        String ac = user1.getUsername();
        String pwd = user1.getPassword();
        btn = findViewById(R.id.bt_ac_and_pwd);
        btn.setText(btn.getText().toString().replace("***",ac).replace("###",pwd));
    }
}

效果如下:

qemu-system-x86_64_hMGARhJZwE

3.2 intent-filter中設定data

還記不記得,在上面的隱式Intent跳轉電話撥打電話例子中提到了——Intent物件有一個setData(Uri data)的方法呢?這里的set后的的data為什么可以設定和獲取到呢

其實,在manifest.xml中的activity的intent-filter中,除了常見的actioncategory,還有一個data標簽,可以用來設定intent物件中傳輸的data,還有不同的資料形式,我們這里就使用scheme就可以了

<activity android:name=".QQLoginSuccessActivity">
    <intent-filter>
        <action android:name="top.woodwhale.qqlogin.LOGIN_INFO"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <data android:scheme="ac"/>
    </intent-filter>
</activity>

只要設定了如上的data標簽,我們給指向QQLoginSuccessActivity的intent物件,使用**intent.setData(Uri.parse(“ac:1008611”));**這樣的方法,就可以給這個intent傳遞ac的資料,

那么在QQLoginSuccessActivity,如何接受ac的資料呢?

使用**intent.getData()**就可以回傳一個Uri物件,toString()一下就可以得到ac了

部分核心代碼:

登錄activity

 // 隱式意圖進行跳轉
Intent intent = new Intent();
intent.setAction("top.woodwhale.qqlogin.LOGIN_INFO");
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("ac:"+ac));
intent.putExtra("pwd",pwd);
this.startActivity(intent);
this.finish();

登錄成功activity

Intent intent = getIntent();
String pwd = intent.getData().toString();
btn = findViewById(R.id.bt_ac_and_pwd);
btn.setText(pwd);

效果如下:

qemu-system-x86_64_kFOa6L2L7d

4、activity之間的資料如何回傳(雙向傳遞)?

與單向傳遞資訊不同,雙向資訊的傳遞也很常見,這就好比我們訪問頁面,訪問之后頁面會回傳一個狀態碼,根據這個狀態碼我們可以知道訪問的結果是什么,例如200就是訪問成功,404就是找不到資源

而在不同的activity之間,我們也可以進行資料回傳,即——可以將第一個activity頁面的資料傳遞給第二個activity進行處理,而第二個activity處理完的結果可以回傳給第一個activity進行使用!

那么如何進行資料回傳呢?我們可以使用自己重寫的onActivityResult()方法,在其中判斷requestCode來判斷是哪個頁面的回傳,并且通過傳遞來的resultCode和intent物件,進行不同情況的資料讀取,

4.1 登錄資訊回傳的例子

舉個例子:

我們現在需要驗證自己登錄的賬號是否是管理員或賬號,管理員賬號密碼分別是root123456,如果登錄的賬號和密碼出現不匹配,就不是管理員,

如果登陸后是管理員,回傳界面會彈出一個Taost,顯示你是管理員!,否則彈出你不是管理員!

那么如何實作代碼呢?

我們的QQLoginActivity,也就是登錄頁面

public class QQLoginActivity extends Activity implements View.OnClickListener {

    private static final String TAG = "QQLoginActivity";
    private EditText account;
    private EditText passwd;
    private Button login;

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

    private void initViews() {
        account = this.findViewById(R.id.et_account);
        passwd = this.findViewById(R.id.et_pwd);
        login = this.findViewById(R.id.bt_login);
        // 添加監聽器
        login.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        if (v == login && login != null) {
            String ac = account.getText().toString();
            String pwd = passwd.getText().toString();
            if (TextUtils.isEmpty(ac)) {
                Toast.makeText(this, "賬號不能為空", Toast.LENGTH_SHORT).show();
                return;
            }
            if (TextUtils.isEmpty(pwd)) {
                Toast.makeText(this,"密碼不能為空", Toast.LENGTH_SHORT).show();
                return;
            }

            // 顯式Intent
            Intent intent = new Intent(this,QQLoginSuccessActivity.class);
            intent.putExtra("ac",ac);
            intent.putExtra("pwd",pwd);
            // 傳給 QQLoginSuccessActivity 這個activity的請求碼是 1
            this.startActivityForResult(intent,1);
            // ...
            // 我們可以給不同的activity設定不同的請求碼,最后通過請求碼判斷是哪個act傳回的資料
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 從當前activity跳轉到其他activity的請求碼
        if (requestCode == 1) {
            Log.i(TAG,"從QQLoginSuccessActivity回傳");
            if (resultCode == 0) {
                Log.i(TAG,"登錄失敗");
                Toast.makeText(this, data.getStringExtra("fail"), Toast.LENGTH_SHORT).show();
            } else if (resultCode == 1) {
                Log.i(TAG,"登錄成功");
                Toast.makeText(this, data.getStringExtra("success"), Toast.LENGTH_SHORT).show();
            }
        }
    }
}

我們的QQLoginSuccessActivity,也就是登錄成功頁面

public class QQLoginSuccessActivity extends Activity implements View.OnClickListener {

    private Button btn;
    private String ac;
    private String pwd;

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

    private void initButtonOnclick() {
        Intent intent = getIntent();
        ac = intent.getStringExtra("ac");
        pwd = intent.getStringExtra("pwd");
        btn = findViewById(R.id.bt_ac_and_pwd);
        btn.setText(btn.getText().toString().replace("***", ac).replace("###", pwd));

        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent retIntent = new Intent();
        if (ac.equals("root") && pwd.equals("123456")) {
            retIntent.putExtra("fail","你是管理員!");
            // 將資訊回傳
            setResult(0,retIntent);
        } else {
            retIntent.putExtra("success","你不是管理員!");
            // 將資訊回傳
            setResult(1,retIntent);
        }

        // 關閉當前頁面
        finish();
    }
}

核心代碼我們來分析一下:

首先是QQLoginActivity頁面的startActivityForResult,設定了一個傳遞過去的intent,又設定了一個requestCode為1,表明我們對QQLoginSuccessActivity的請求碼是1,我們傳遞了一個ac和pwd的String型別,

image-20220117160343839

跳轉到QQLoginSuccessActivity頁面后,我們點擊按鈕設定了回傳資訊,不同狀態回傳不同的資訊

image-20220117160739437

回傳后在QQLoginActivity執行我們重寫onActivityResult()方法,判斷requestCode,如果是1,那么就是給QQLoginSuccessActivity的請求回傳,而回傳結果是resultCode,如果是0,那么登陸失敗,反之成功,

image-20220117160504881

效果如下:

qemu-system-x86_64_xqq3MgCAR9

4.2 拍攝圖片回傳的例子

我們先帶入一個場景——使用QQ或者微信的時候,點擊“拍攝”選項,會調出一個相機進行拍照,然后將拍完的照片發送給好友,

那么這其實也是一個常見的資訊回傳,首先呼叫系統相冊拍攝相片,之后再將拍攝好的相片進行一個回傳發送

我們現在來模擬一下這樣的場景——點擊一個按鈕呼叫系統的相機,如果拍照成功,就回傳并且在原來的頁面顯示我們拍攝的相片,如果失敗就Taost一個取消或者失敗的反饋,

首先建立layout布局頁面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">

    <ImageView
        android:id="@+id/iv_pic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <TextView
        android:id="@+id/tv_photograph"
        android:layout_width="60dp"
        android:height="60dp"
        android:layout_centerInParent="true"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="40dp"
        android:layout_height="wrap_content"
        android:background="@drawable/selector_orange_bg"/>

</RelativeLayout>

我們的拍照按鈕使用了一個selector,效果就是按下按鈕會帶灰色,有明顯的按壓效果,這種效果的實作我在之前的《【Android】安卓中的布局與事件》中有寫過,

然后就是在manifest中注冊一個activity

<activity android:name=".study.test.CameraActivity" android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

然后就是CameraActivity類的代碼

import ...;

public class CameraActivity extends Activity implements View.OnClickListener {

    private static final int REQUEST_CODE_FOR_PIC = 1;
    private static final String TAG = "CameraActivity";
    private TextView photo;
    private ImageView pic;

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

        photo = this.findViewById(R.id.tv_photograph);
        pic = this.findViewById(R.id.iv_pic);
        photo.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 拍照的按鈕被點擊之后,需要跳轉到系統的相機APP,然后回傳圖片
        Intent intent = new Intent();
        // 設定action是系統相機
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        // 需要使用startActivityForResult()方法
        startActivityForResult(intent, REQUEST_CODE_FOR_PIC);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_FOR_PIC) {
            // 成功回傳
            if (resultCode == Activity.RESULT_OK && data != null) {
                Bitmap bitmap = data.getParcelableExtra("data");
                if (bitmap != null) {
                    pic.setImageBitmap(bitmap);
                    Toast.makeText(this, "拍照成功!", Toast.LENGTH_SHORT).show();
                }
            }
            // 取消或者失敗
            else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this, "您取消了拍照!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

效果如下:

取消拍照:

qemu-system-x86_64_LQYCi0KXQS

拍照成功:

qemu-system-x86_64_xpyetZwg1x

至于用以上方法為何拍攝出來的圖片是模糊的縮略圖,可以看這篇文章來理解:Android呼叫系統相機拍照,其中還給出了如何拍一張正常的圖片進行回顯,

后話

對于activity的初步認識到此結束了,其中涉及到的頁面跳轉和資料傳遞都是重點,看懂代碼和會寫代碼是兩碼事,在看完其中的例子之后,不妨自己動手寫一寫代碼,能給自己帶來新的認識!

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413940.html

標籤:其他

上一篇:【三端通用】微信即時通訊+視頻聊天(安卓、IOS、小程式)專案完整版

下一篇:移動應用程式設計基礎——資料庫實踐——簡單日記本

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【從零開始擼一個App】Dagger2

    Dagger2是一個IOC框架,一般用于Android平臺,第一次接觸的朋友,一定會被搞得暈頭轉向。它延續了Java平臺Spring框架代碼碎片化,注解滿天飛的傳統。嘗試將各處代碼片段串聯起來,理清思緒,真不是件容易的事。更不用說還有各版本細微的差別。 與Spring不同的是,Spring是通過反射 ......

    uj5u.com 2020-09-10 06:57:59 more
  • Flutter Weekly Issue 66

    新聞 Flutter 季度調研結果分享 教程 Flutter+FaaS一體化任務編排的思考與設計 詳解Dart中如何通過注解生成代碼 GitHub 用對了嗎?Flutter 團隊分享如何管理大型開源專案 插件 flutter-bubble-tab-indicator A Flutter librar ......

    uj5u.com 2020-09-10 06:58:52 more
  • Proguard 常用規則

    介紹 Proguard 入口,如何查看輸出,如何使用 keep 設定入口以及使用實體,如何配置壓縮,混淆,校驗等規則。

    ......

    uj5u.com 2020-09-10 06:59:00 more
  • Android 開發技術周報 Issue#292

    新聞 Android即將獲得類AirDrop功能:可向附近設備快速分享檔案 谷歌為安卓檔案管理應用引入可安全隱藏資料的Safe Folder功能 Android TV新主界面將顯示電影、電視節目和應用推薦內容 泄露的Android檔案暗示了傳說中的谷歌Pixel 5a與折疊屏新機 谷歌發布Andro ......

    uj5u.com 2020-09-10 07:00:37 more
  • AutoFitTextureView Error inflating class

    報錯: Binary XML file line #0: Binary XML file line #0: Error inflating class xxx.AutoFitTextureView 解決: <com.example.testy2.AutoFitTextureView android: ......

    uj5u.com 2020-09-10 07:00:41 more
  • 根據Uri,Cursor沒有獲取到對應的屬性

    Android: 背景:呼叫攝像頭,拍攝視頻,指定保存的地址,但是回傳的Cursor檔案,只有名稱和大小的屬性,沒有其他諸如時長,連ID屬性都沒有 使用 cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATIO ......

    uj5u.com 2020-09-10 07:00:44 more
  • Android連載29-持久化技術

    一、持久化技術 我們平時所使用的APP產生的資料,在記憶體中都是瞬時的,會隨著斷電、關機等丟失資料,因此android系統采用了持久化技術,用于存盤這些“瞬時”資料 持久化技術包括:檔案存盤、SharedPreference存盤以及資料庫存盤,還有更復雜的SD卡記憶體儲。 二、檔案存盤 最基本存盤方式, ......

    uj5u.com 2020-09-10 07:00:47 more
  • Android Camera2Video整合到自己專案里

    背景: Android專案里呼叫攝像頭拍攝視頻,原本使用的 MediaStore.ACTION_VIDEO_CAPTURE, 后來因專案需要,改成了camera2 1.Camera2Video 官方demo有點問題,下載后,不能直接整合到專案 問題1.多次拍攝視頻崩潰 問題2.雙擊record按鈕, ......

    uj5u.com 2020-09-10 07:00:50 more
  • Android 開發技術周報 Issue#293

    新聞 谷歌為Android TV開發者提供多種新功能 Android 11將自動填表功能整合到鍵盤輸入建議中 谷歌宣布Android Auto即將支持更多的導航和數字停車應用 谷歌Pixel 5只有XL版本 搭載驍龍765G且將比Pixel 4更便宜 [圖]Wear OS將迎來重磅更新:應用啟動時間 ......

    uj5u.com 2020-09-10 07:01:38 more
  • 海豚星空掃碼投屏 Android 接收端 SDK 集成 六步驟

    掃碼投屏,開放網路,獨占設備,不需要額外下載軟體,微信掃碼,發現設備。支持標準DLNA協議,支持倍速播放。視頻,音頻,圖片投屏。好點意思。還支持自定義基于 DLNA 擴展的操作動作。好像要收費,沒體驗。 這里簡單記錄一下集成程序。 一 跟目錄的build.gradle添加私有mevan倉庫 mave ......

    uj5u.com 2020-09-10 07:01:43 more
最新发布
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:40:31 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:40:11 more
  • 歡迎頁輪播影片

    如圖,引導開始,球從上落下,同時淡入文字,然后文字開始輪播,最后一頁時停止,點擊進入首頁。 在來看看效果圖。 重力球先不講,主要歡迎輪播簡單實作 首先新建一個類 TextTranslationXGuideView,用于影片展示 文本是類似的,最后會有個圖片箭頭影片,布局很簡單,就是一個 TextVi ......

    uj5u.com 2023-04-20 08:39:36 more
  • 【FAQ】關于華為推送服務因營銷訊息頻次管控導致服務通訊類訊息

    一. 問題描述 使用華為推送服務下發IM訊息時,下發訊息請求成功且code碼為80000000,但是手機總是收不到訊息; 在華為推送自助分析(Beta)平臺查看發現,訊息發送觸發了頻控。 二. 問題原因及背景 2023年1月05日起,華為推送服務對咨詢營銷類訊息做了單個設備每日推送數量上限管理,具體 ......

    uj5u.com 2023-04-20 08:39:13 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:16:23 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:16:15 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:15:46 more
  • iOS從UI記憶體地址到讀取成員變數(oc/swift)

    開發除錯時,我們發現bug時常首先是從UI顯示發現例外,下一步才會去定位UI相關連的資料的。XCode有給我們提供一系列debug工具,但是很多人可能還沒有形成一套穩定的除錯流程,因此本文嘗試解決這個問題,順便提出一個暴論:UI顯示例外問題只需要兩個步驟就能完成定位作業的80%: 定位例外 UI 組 ......

    uj5u.com 2023-04-19 09:14:53 more
  • FIDE重磅更新!性能飛躍!體驗有禮!

    FIDE 開發者工具重構升級啦!實作500%性能提升,誠邀體驗! 一直以來不少開發者朋友在社區反饋,在使用 FIDE 工具的程序中,時常會遇到諸如加載不及時、代碼預覽/渲染性能不如意的情況,十分影響開發體驗。 作為技術團隊,我們深知一件趁手的開發工具對開發者的重要性,因此,在2023年開年,FinC ......

    uj5u.com 2023-04-19 09:14:08 more
  • 游戲內嵌社區服務開放,助力開發者提升玩家互動與留存

    華為 HMS Core 游戲內嵌社區服務提供快速訪問華為游戲中心論壇能力,支持玩家直接在游戲內瀏覽帖子和交流互動,助力開發者擴展內容生產和觸達的場景。 一、為什么要游戲內嵌社區? 二、游戲內嵌社區的典型使用場景 1、游戲內打開論壇 您可以在游戲內繪制論壇入口,為玩家提供沉浸式發帖、瀏覽、點贊、回帖、 ......

    uj5u.com 2023-04-19 09:08:34 more