使用Intent

Intent

Intent是Android程序組件之間交互的一種重要方式弄慰,可以指明當(dāng)前組件要執(zhí)行的動(dòng)作,還可以在組件間傳遞數(shù)據(jù)。
他被用于啟動(dòng)活動(dòng)胃碾,啟動(dòng)服務(wù)和發(fā)送廣播等場景,Intent有多個(gè)構(gòu)造函數(shù)的重載筋搏。

使用方式

  • 顯示Intent
  • 隱式Intent

使用顯示的Intent

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);

Intent(Context context, Class<?>cls):是構(gòu)造函數(shù)其中的一個(gè)重載仆百。
第一個(gè)參數(shù)是啟動(dòng)活動(dòng)的上下文,第二個(gè)是想要啟動(dòng)的目標(biāo)活動(dòng)奔脐。
startActivity(Intent intent):是啟動(dòng)活動(dòng)的方法俄周。
此種方式啟動(dòng)活動(dòng)的吁讨、,意圖非常明顯峦朗,所以稱顯示Intent建丧。

使用隱式的Intent

隱式intent通過在AndroidManifest.xml中的<activity>標(biāo)簽配置<action>標(biāo)簽和<category>標(biāo)簽等信息,然后系統(tǒng)自動(dòng)分析使用波势。

<activity android:name=".chapter02.IntentImplicitActivity">
    <intent-filter>
        <action android:name="com.bl.blandroidpro.ACTION_START" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="com.bl.blandroidpro.MY_CATEGORY" />
    </intent-filter>
</activity>
Intent intent = new Intent("com.bl.blandroidpro.ACTION_START");
intent.addCategory("com.bl.blandroidpro.MY_CATEGORY");

Intent(String action):是構(gòu)造函數(shù)的另一個(gè)重載翎朱,以一個(gè)action字符串作為參數(shù)。
intent.addCategory(String category):通過此函數(shù)添加新的類別尺铣,別忘了在activity 標(biāo)簽中進(jìn)行配置拴曲,否則程序崩潰。

使用Intent打開網(wǎng)頁

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.baidu.com"));
startActivity(intent);

Intent.ACTION_VIEW:是安卓系統(tǒng)的內(nèi)置動(dòng)作凛忿,其常量值為android.intent.action.VIEW澈灼。
intent.setData(Uri uri):將字符串解析成Uri,再通過setData方法傳遞進(jìn)去侄非。
<data>標(biāo)簽:用于更精確的指定當(dāng)前活動(dòng)能夠響應(yīng)什么類型的數(shù)據(jù)蕉汪。

  • android:scheme 指定協(xié)議。
  • android:host 指定主機(jī)名逞怨。
  • android:port 指定端口者疤。
  • android:path 指定路徑。
  • android:mimeType 指定可以處理的數(shù)據(jù)類型叠赦。
<activity android:name=".chapter02.IntentOpenWebActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <data android:scheme="https" />
    </intent-filter>
</activity>

使用Intent打電話

Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);

使用Intent傳遞數(shù)據(jù)給下一個(gè)活動(dòng)

putExtra(String key, Object value):通過使用此方法進(jìn)行設(shè)置

// 第一個(gè)活動(dòng)
Intent intent = new Intent(FristActivity.this, SecondActivity.class);
intent.putExtra("transmit_data_1", "Hello");
intent.putExtra("transmit_data_2", new String[]{"World!"});
intent.putExtra("transmit_data_3", 333});
startActivity(intent);

從Intent中獲取數(shù)據(jù)

// 第二個(gè)活動(dòng)
Intent intent = getIntent();
String data_1 = intent.getStringExtra("transmit_data_1");
String[] data_2 = intent.getStringArrayExtra("transmit_data_2");
int data_3 = intent.getIntExtra("transmit_data_3");

getIntent():獲取當(dāng)前intent驹马。
getXXXExtra():獲取對應(yīng)類型的數(shù)據(jù)。

返回?cái)?shù)據(jù)給上一個(gè)活動(dòng)

// 第一個(gè)Activity
Intent intent = new Intent(FristActivity.this, SecondActivity.class);
startActivityForResult(intent, 1);

// 接收返回的數(shù)據(jù)
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    switch (requestCode) {
        case 1:
            if (resultCode == RESULT_OK) {
                String[] res = data.getStringArrayExtra("feedback_data");
                tv_intent_res.setText(res[0] + res[1]);
            }
            break;
        default:
            break;    
    }
}
// 第二個(gè)Activity
Intent intent = new Intent();
intent.putExtra("key1", "測試數(shù)據(jù)");
setResult(RESULT_OK, 1);
finish();

@Override
public void onBackPressed() {
    Intent intent = new Intent();
    intent.putExtra("feedback_data", new String[]{"Yes, I", " konw!"});
    setResult(RESULT_OK, intent);
    finish();
}

startActivityForResult():使用此方法啟動(dòng)activity表示此活動(dòng)要接收返回的數(shù)據(jù)除秀。
onActivityResult():重寫此方法接收返回的Intent中的數(shù)據(jù)糯累。

  • requestCode:啟動(dòng)活動(dòng)時(shí)的請求碼。
  • resultCode:返回?cái)?shù)據(jù)時(shí)的處理結(jié)果册踩。
  • data:返回?cái)?shù)據(jù)的intent泳姐。

setResult():將intent設(shè)置到result中。
onBackPressed():重寫此方法暂吉,用戶點(diǎn)返回鍵時(shí)調(diào)用此方法胖秒。

代碼示例


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.bl.blandroidpro">

    <application
        android:name=".chapter13.BLApplication"
        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/AppTheme.NoActionBar">

        <activity android:name=".chapter02.FirstActivity" />
        <activity android:name=".chapter02.SecondActivity">
            <intent-filter>
                <action android:name="com.bl.blandroidpro.ACTION_START" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="com.bl.blandroidpro.MY_CATEGORY" />
            </intent-filter>
        </activity>
        <activity android:name=".chapter02.IntentOpenWebActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:scheme="https" />
            </intent-filter>
        </activity>
    </application>

activity_first.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">

    <include layout="@layout/my_nav" />

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <Button
                android:id="@+id/btn_intent_explicit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="使用顯示Intent" />

            <Button
                android:id="@+id/btn_intent_implicit"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="使用隱式Intent" />

            <Button
                android:id="@+id/btn_intent_web"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="打開網(wǎng)頁 百度" />

            <Button
                android:id="@+id/btn_intent_tel"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="打電話 10086" />

            <Button
                android:id="@+id/btn_intent_transmit_data"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="使用 Intent 傳遞數(shù)據(jù)" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="反饋回來的數(shù)據(jù)"/>
            <TextView
                android:id="@+id/tv_intent_res"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <WebView
                android:id="@+id/wv_intent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="1dp"
                android:padding="0dp"
                android:background="#666"></WebView>

        </LinearLayout>
    </ScrollView>

</LinearLayout>

FirstActivity.java

public class FirstActivity extends MyBaseActivity {

    TextView tv_intent_res;

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

        // 使用 顯示Intent
        Button btn_intent_show = findViewById(R.id.btn_intent_explicit);
        btn_intent_show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Intent 有很多構(gòu)造函數(shù),像這種意圖很明顯慕的,稱為顯示 Intent
                Intent intent = new Intent(IntentActivity.this, IntentExplicitActivity.class);
                startActivity(intent);
            }
        });

        // 使用 隱式Intent
        Button btn_intent_implicit = findViewById(R.id.btn_intent_implicit);
        btn_intent_implicit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 在 AndroidManifest.xml 中 activity 標(biāo)簽中設(shè)置 action 及 category
                // 在 action 和 category 同時(shí)匹配下才可執(zhí)行
                // 這種通過系統(tǒng)分析你要做什么的形式稱為 隱式 Intent
                // 此處添加 action 字符串
                Intent intent = new Intent("com.bl.blandroidpro.ACTION_START");
                // 此處添加自定義的 category阎肝,default 為默認(rèn)的,不需要添加
                intent.addCategory("com.bl.blandroidpro.MY_CATEGORY");
                startActivity(intent);
            }
        });

        // 打開 網(wǎng)頁
        Button btn_intent_web = findViewById(R.id.btn_intent_web);
        btn_intent_web.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("https://www.baidu.com"));
                startActivity(intent);
            }
        });

        // 打電話
        Button btn_intent_tel = findViewById(R.id.btn_intent_tel);
        btn_intent_tel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:10086"));
                startActivity(intent);
            }
        });

        // Activity 之間 使用 Intent 傳遞數(shù)據(jù)
        Button btn_intent_transmit_data = findViewById(R.id.btn_intent_transmit_data);
        btn_intent_transmit_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IntentActivity.this, IntentTransmitDataActivity.class);
                intent.putExtra("transmit_data_1", "Hello");
                intent.putExtra("transmit_data_2", new String[]{"World!"});
                startActivityForResult(intent, 1);
            }
        });
        
        // 顯示結(jié)果
        tv_intent_res = findViewById(R.id.tv_intent_res);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {
                    String[] res = data.getStringArrayExtra("feedback_data");
                    tv_intent_res.setText(res[0] + res[1]);
                }
                break;
                default:
        }
    }

}

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    TextView tv_transmit_data;

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

        Intent intent = getIntent();
        String data_1 = intent.getStringExtra("transmit_data_1");
        String[] data_2 = intent.getStringArrayExtra("transmit_data_2");

        tv_transmit_data = findViewById(R.id.tv_transmit_data);
        tv_transmit_data.setText(data_1 + " " + data_2[0]);

        Button btn_feedback = findViewById(R.id.btn_feedback);
        btn_feedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("feedback_data", new String[]{"Yes, I", " konw!"});
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    /**
     * 點(diǎn)擊返回按鈕時(shí) 反饋數(shù)據(jù)回去
     */
    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("feedback_data", new String[]{"Yes, I", " konw!"});
        setResult(RESULT_OK, intent);
        finish();
    }
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末肮街,一起剝皮案震驚了整個(gè)濱河市风题,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖沛硅,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件眼刃,死亡現(xiàn)場離奇詭異,居然都是意外死亡摇肌,警方通過查閱死者的電腦和手機(jī)鸟整,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來朦蕴,“玉大人,你說我怎么就攤上這事弟头》宰ィ” “怎么了?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵赴恨,是天一觀的道長疹娶。 經(jīng)常有香客問我,道長伦连,這世上最難降的妖魔是什么雨饺? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮惑淳,結(jié)果婚禮上额港,老公的妹妹穿的比我還像新娘。我一直安慰自己歧焦,他們只是感情好移斩,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著绢馍,像睡著了一般向瓷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上舰涌,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天猖任,我揣著相機(jī)與錄音,去河邊找鬼瓷耙。 笑死朱躺,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哺徊。 我是一名探鬼主播室琢,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼落追!你這毒婦竟也來了盈滴?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎巢钓,沒想到半個(gè)月后病苗,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡症汹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年硫朦,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片背镇。...
    茶點(diǎn)故事閱讀 39,919評論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡咬展,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出瞒斩,到底是詐尸還是另有隱情破婆,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布胸囱,位于F島的核電站祷舀,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏烹笔。R本人自食惡果不足惜裳扯,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谤职。 院中可真熱鬧饰豺,春花似錦、人聲如沸允蜈。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陷寝。三九已至锅很,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間凤跑,已是汗流浹背爆安。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留仔引,地道東北人扔仓。 一個(gè)月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像咖耘,于是被迫代替她去往敵國和親翘簇。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 一個(gè)應(yīng)用中總會存在多個(gè)活動(dòng)儿倒,通過這些活動(dòng)的相互跳轉(zhuǎn)版保,數(shù)據(jù)傳遞呜笑,邏輯處理,便可完成一個(gè)應(yīng)用的功能彻犁。在各個(gè)活動(dòng)的跳轉(zhuǎn)時(shí)...
    吸給007閱讀 550評論 0 2
  • ¥開啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個(gè)線程叫胁,因...
    小菜c閱讀 6,409評論 0 17
  • 1.Intent的用法: (1)Action跳轉(zhuǎn) 1、 使用Action跳轉(zhuǎn)汞幢,當(dāng)程序AndroidManifest...
    彭文波_4118閱讀 5,769評論 0 7
  • 顯示Intent的使用 首先再定義一個(gè)SecondActivity.java文件驼鹅, 在寫一個(gè)second_layo...
    何懼l閱讀 338評論 0 0
  • Bella,你你你森篷,認(rèn)識她感覺好丟人啊输钩。昨天突然發(fā)現(xiàn)真的萬事相通,我們也一樣仲智。不懂你有沒有入黨张足,你知道發(fā)展黨員的流...
    考拉小巫Daniel閱讀 281評論 11 0