android基础学习5————隐式意图intent开启系统照相机

来源:互联网 发布:mac版inode如何上网 编辑:程序博客网 时间:2024/06/06 02:24

显式意图开启组件时必须要指定组件的名称,一般只在本应用程序切换组件时使用。而隐式意图的功能要比显式意图更加强大,不仅可以开启本应用的组件,还可以开启其他应用的组件,例如系统自带的照相机、浏览器等。

首先,设计用户交互界面

<?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和系统照相机一样。

最后运行程序,点击按钮即可看见成效。


0 0
原创粉丝点击