android基礎學習5————隱式意圖intent開啓系統照相機

顯式意圖開啓組件時必須要指定組件的名稱,一般只在本應用程序切換組件時使用。而隱式意圖的功能要比顯式意圖更加強大,不僅可以開啓本應用的組件,還可以開啓其他應用的組件,例如系統自帶的照相機、瀏覽器等。

首先,設計用戶交互界面

<?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"
    tools:context="com.example.lenovo.opencamera.MainActivity">

    <Button
        android:id="@+id/opencamera"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="打開照相機" />

</RelativeLayout>

然後在MainActivity中通過隱式意圖開啓系統中的照相機

package com.example.lenovo.opencamera;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲取界面上的按鈕
        Button button=(Button)findViewById(R.id.opencamera);
        //給Button按鈕添加點擊事件
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setAction("android.media.action.IMAGE_CAPTURE");
                intent.addCategory("android.intent.category.DEFAULT");
                startActivity(intent);
            }
        });
    }
}

這裏配置的action和category和系統照相機一樣。

最後運行程序,點擊按鈕即可看見成效。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章