編輯:關於 Android 程式設計
Intent(意圖)是 Android 中極為關鍵的一塊拼圖,在 Activity 與 Service 之間的跳轉、資料傳遞都有大量應用。本文從最基礎的用法開始,逐步示範 Intent 的三種典型場景。
先備課一下幾個常用 API:
startActivity(Intent intent):啟動一個 Activity,並可透過 Intent 傳遞資料。startActivityForResult(Intent intent, int requestCode):啟動另一個 Activity 並接收其回傳結果,只有 requestCode 大於 0 時才會觸發 onActivityResult()。getIntent():取得啟動當前 Activity 的 Intent 物件。onActivityResult(int requestCode, int resultCode, Intent data):需要接收回傳資料時覆寫此方法。finish():結束當前 Activity 並返回上一個,同時會觸發 onActivityResult()。managedQuery(...):查詢並管理返回的 Cursor 結果集。主介面配置:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="141dp"
android:text="轉跳" />
</RelativeLayout>
目標頁面配置:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是第二屏界面" />
</RelativeLayout>
MainActivity:
package com.example.intent1;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 建立 Intent 物件
Intent intent = new Intent(MainActivity.this, Other.class);
startActivity(intent);
MainActivity.this.finish(); // 結束當前 Activity
}
});
}
}
Other.java:
package com.example.intent1;
import android.app.Activity;
import android.os.Bundle;
public class Other extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
}
}
執行結果:


記得別忘了到 AndroidManifest.xml 註冊 Other,否則啟動時會直接拋出 ActivityNotFoundException。
主介面配置加上一個輸入框:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="傳遞" />
<EditText
android:id="@+id/edit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:ems="10" />
</RelativeLayout>
Other.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="@+id/button2"
android:gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="獲取數據" />
</LinearLayout>
MainActivity:
package com.example.intent2;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private Button button;
private EditText info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) this.findViewById(R.id.button1);
info = (EditText) this.findViewById(R.id.edit);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Other.class);
intent.putExtra("info", info.getText().toString()); // 附加資料
startActivity(intent);
MainActivity.this.finish();
}
});
}
}
Other.java:
package com.example.intent2;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Other extends Activity {
Intent intent;
private Button button;
private TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.other);
button = (Button) this.findViewById(R.id.button2);
text = (TextView) this.findViewById(R.id.textView1);
intent = super.getIntent(); // 取得意圖物件
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String info = intent.getStringExtra("info"); // 取出傳來的資料
text.setText(info);
}
});
}
}


這裡有個小細節:接收端用 getIntent() 拿到 Intent,再用 getStringExtra() 取值,key 必須與發送端 putExtra 時完全一致。
最後做個完整一點的例子:成人身高體重測試(BMI)。判定標準採用常見的 BMI 公式:
體重指數 = 體重(公斤) ÷ 身高(米)的平方 kg/m² 正常體重:18 – 25 超重 :25 – 30 輕度肥胖:> 30 中度肥胖:> 35 重度肥胖:> 40
MainActivity:
package com.example.inten3;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button resetInfo, getInfo;
private EditText height, weight;
private TextView detail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
resetInfo = (Button) this.findViewById(R.id.button1);
getInfo = (Button) this.findViewById(R.id.button2);
height = (EditText) this.findViewById(R.id.editText1);
weight = (EditText) this.findViewById(R.id.editText2);
detail = (TextView) this.findViewById(R.id.textView3);
// 重置按鈕
resetInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
weight.setText("");
height.setText("");
detail.setText("");
}
});
// 獲取信息按鈕
getInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Other.class);
intent.putExtra("weight", Double.valueOf(weight.getText().toString()));
intent.putExtra("height", Double.valueOf(height.getText().toString()));
// 以 requestCode = 1 啟動並等待回傳
startActivityForResult(intent, 1);
}
});
}
// 處理返回的資料
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case RESULT_OK:
MainActivity.this.detail.setText(data.getStringExtra("endMsg"));
break;
default:
break;
}
}
}
Other.java:
package com.example.inten3;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Other extends Activity {
private Button returnMsg, resetbut;
private TextView weightMsg, heightMsg;
private Double weight, height;
private String endMsg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.other);
returnMsg = (Button) this.findViewById(R.id.Otherbutton1);
resetbut = (Button) this.findViewById(R.id.Otherbutton2);
weightMsg = (TextView) this.findViewById(R.id.OthertextView1);
heightMsg = (TextView) this.findViewById(R.id.OthertextView2);
Intent intent = super.getIntent();
weight = intent.getDoubleExtra("weight", 0);
height = intent.getDoubleExtra("height", 0);
weightMsg.setText("您的體重:" + weight + "KG");
heightMsg.setText("您的身高:" + height + "CM");
returnMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Double heightNum = height / 100;
double endNum = weight / (heightNum * heightNum);
if (endNum >= 18 && endNum <= 25) {
endMsg = "您的身體很正常哦,繼續保持親。";
} else if (endNum < 18) {
endMsg = "親啊,不能總是減肥啊,您現在可是偏瘦哦,當心身體";
} else if (endNum > 25 && endNum <= 30) {
endMsg = "您現在有一點胖哦,不過不要緊,要注意飲食哦";
} else if (endNum > 30 && endNum <= 35) {
endMsg = "親,您已經進入肥胖人群了哦,注意鍛煉哦";
} else if (endNum > 35) {
endMsg = "額,你,你。。你怎麼可以這樣,還不趕快減肥,當心找不到對象哦";
}
// 把結果塞回 Intent
Other.this.getIntent().putExtra("endMsg", endMsg);
// 設定回傳結果與結果碼
Other.this.setResult(RESULT_OK, Other.this.getIntent());
Other.this.finish();
}
});
// 重新輸入
resetbut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Other.this.setResult(RESULT_CANCELED, Other.this.getIntent());
Other.this.finish();
}
});
}
}



這裡的三個關鍵環節是:出發前用 startActivityForResult(intent, requestCode);在目標頁面用 setResult(resultCode, intent) 把資料掛回 Intent;回到原頁面後在 onActivityResult() 中依 resultCode 取出資料。三者缺一,資料就傳不回來。
下節預告:Intent 進階用法,包括系統指令與隱含 Intent 的應用。
Android 緩存機制深度解析:LruCache、DiskLruCache 與二級緩存實踐
一、先推薦一個輕量級方案:ACache ACache(ASimpleCache)的用法與 SharedPreferences 類似,但容量更強。SharedPrefere
Android 逆向工程常用工具入門指南(apktool 與 dex2jar)
寫在前面 整理這份筆記時,我偶爾也會自嘲是不是太無聊了,但既然項目告一段落,趁著手邊的鏈接還新鮮,乾脆一口氣寫完,省得日後再翻箱倒櫃。於是就有了這篇 Android 逆向
Android 自訂 Dialog 樣式與進度更新實作
客製化 Dialog 常用於提示、載入或進度回饋。下圖為本文要呈現的效果。 核心思路 自訂 Dialog 繼承 android.app.Dialog,透過建構子傳入 l
RxLifecycle 實踐:優雅管理 Activity 與 Fragment 的生命周期
為什麼需要 RxLifecycle 在使用 RxJava 時,如果訂閱(Subscription)沒有被及時取消,而它又恰好綁定在有生命周期的 Activity 或 Fr