【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

2、如何實作activity之間的跳轉?
我們可以使用startActivity()方法或者startActivityForResult()方法來跳轉頁面,這一小節就只講startActivity與intent配合使用進行資料單項傳遞,在第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);
}
}
}
這一部分是跳轉實作的代碼:

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中我們設定的鍵值對

測驗效果:

效果完成!
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中設定了一個name為top.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就可以抓取到啦

那么我們跳轉的核心代碼就是:
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);
測驗一下

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);
那么這樣的效果就是如下圖所示:

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)

這兩個方法的第二個引數就有講究了,
首先,說說Serializable,這個是Java中的序列化類,它是JDK1.1就誕生的介面,用于標識可序列化,在非安卓程式中也是非常常見的存在,
所謂序列化就是一種壓縮,可以理解成一個物件壓縮成JSON的那種形式,只不過在JVM中處理肯定不是JSON的格式
序列化之后的物件可以通過反序列化得到原來的物件
我們對該介面的描述進行翻譯一下:



其次,就是這個沒見過的Parcelable,這個類是Google自己實作的,也是用來進行壓縮記憶體的,效率方面比Serializable高,
我們對這個介面的描述進行翻譯:


所以如果我們需要對一個物件進行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));
}
}
效果如下:

3.2 intent-filter中設定data
還記不記得,在上面的隱式Intent跳轉電話撥打電話例子中提到了——Intent物件有一個setData(Uri data)的方法呢?這里的set后的的data為什么可以設定和獲取到呢?
其實,在manifest.xml中的activity的intent-filter中,除了常見的action和category,還有一個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);
效果如下:

4、activity之間的資料如何回傳(雙向傳遞)?
與單向傳遞資訊不同,雙向資訊的傳遞也很常見,這就好比我們訪問頁面,訪問之后頁面會回傳一個狀態碼,根據這個狀態碼我們可以知道訪問的結果是什么,例如200就是訪問成功,404就是找不到資源…
而在不同的activity之間,我們也可以進行資料回傳,即——可以將第一個activity頁面的資料傳遞給第二個activity進行處理,而第二個activity處理完的結果可以回傳給第一個activity進行使用!
那么如何進行資料回傳呢?我們可以使用自己重寫的onActivityResult()方法,在其中判斷requestCode來判斷是哪個頁面的回傳,并且通過傳遞來的resultCode和intent物件,進行不同情況的資料讀取,
4.1 登錄資訊回傳的例子
舉個例子:
我們現在需要驗證自己登錄的賬號是否是管理員或賬號,管理員賬號密碼分別是root和123456,如果登錄的賬號和密碼出現不匹配,就不是管理員,
如果登陸后是管理員,回傳界面會彈出一個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型別,

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

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

效果如下:

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();
}
}
}
}
效果如下:
取消拍照:

拍照成功:

至于用以上方法為何拍攝出來的圖片是模糊的縮略圖,可以看這篇文章來理解:Android呼叫系統相機拍照,其中還給出了如何拍一張正常的圖片進行回顯,
后話
對于activity的初步認識到此結束了,其中涉及到的頁面跳轉和資料傳遞都是重點,看懂代碼和會寫代碼是兩碼事,在看完其中的例子之后,不妨自己動手寫一寫代碼,能給自己帶來新的認識!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/413940.html
標籤:其他
