调用摄像头和相册,音乐控制,视频控制

注意:android7.0与7.0以下版本获取相机拍照后的照片的路径的方式不同,具体代码在给我的github上,地址为https://github.com/liang1075963999/android7.0

例一:启动相机拍一张照片,然后将照片显示在imageview上,代码如下:
public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private Uri imageuri;
    public static final int TAKE_PHOTO=1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file=new File(getExternalCacheDir(),"1.jpg");
                Log.i("xinxi",getExternalCacheDir()+"");//输出内容为:/storage/emulated/0/Android/data/com.example.liang.myapplication/cache
                if(file.exists()){//exists的中文意思是存在
                    file.delete();
                }
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(Build.VERSION.SDK_INT>=24)
                {
                    imageuri= FileProvider.getUriForFile(MainActivity.this,"com.example.liang.myapplication",file);//得到文件的uri
                    Log.i("xinxi",imageuri.toString());
                }
                else {
                    imageuri=Uri.fromFile(file);//我的手机只会执行else里面的语句,说明我的手机的sdk的版本小于24,因为我的手机是android6.0,api是23,只有android7.0及以上版本才会执行以上的语句
                    Log.i("xinxi",imageuri.toString());//输出结果为:file:///storage/emulated/0/Android/data/com.example.liang.myapplication/cache/1.jpg
                }
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");//启动相机的action是android.media.action.IMAGE_CAPTURE
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageuri);//将照片的uri路径写入,照片就会保存在该路径下
                startActivityForResult(intent,TAKE_PHOTO);//使用startActivityForResult启动的活动,在活动启动之后会给原来的活动返回一个结果码,这个结果码在onActivityResult方法中接收,来判断是否正常启动了
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode==RESULT_OK){
                    try {
                        Bitmap bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageuri));//读出路径下图片的流,然后转换为bitmap
                        imageView.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
        }
    }
}

因为android7.0中得到一个文件的uri涉及到了content provider,所以需要在androidmanifest中进行配置,内容如下:


调用摄像头和相册,音乐控制,视频控制_第1张图片
device-2017-11-14-182630.png
例二:从相册中选择图片
public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private static final int CHOOSE_PHOTO = 2;//这里之所以是2,是因为这个例子和例一其实是一起的,但是我给分开了,因为例一中的TAKE_PHOTO=1,所以这里要用2,加以区分

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        imageView = (ImageView) findViewById(R.id.imageView);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                } else {
                    qidong();
                }
            }
        });
    }

    private void qidong() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");//启动手机内容的action是android.intent.action.GET_CONTENT
        intent.setType("image/*");//设置所需手机内容为图片
        startActivityForResult(intent, CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4.及以上版本使用这个方法处理图片
                        one(data);
                    } else {
                        //4.4.以下版本使用这个方法处理图片
                        another(data);
                    }
                }
        }
    }

    @TargetApi(19)
    private void one(Intent intent) {
        String imagepath = null;
        Uri uri = intent.getData();
        Log.i("xinxi", "intent.getData().toString()为:" + intent.getData().toString());
        Log.i("xinxi", "uri.getAuthority()为:" + uri.getAuthority());
        Log.i("xinxi", "uri.getScheme()为:" + uri.getScheme());
      //Log日志如下:
       /* 11-14 20:27:13.775 6291-6291/com.example.liang.myapplication I/xinxi: intent.getData().toString()为:content://com.android.providers.media.documents/document/image%3A756326
        11-14 20:27:13.775 6291-6291/com.example.liang.myapplication I/xinxi: uri.getAuthority()为:com.android.providers.media.documents
        11-14 20:27:13.775 6291-6291/com.example.liang.myapplication I/xinxi: uri.getScheme()为:content
        11-14 20:27:13.785 6291-6291/com.example.liang.myapplication I/xinxi: DocumentsContract.getDocumentId(uri)为:image:756326
        11-14 20:27:31.925 6291-6291/com.example.liang.myapplication I/xinxi: intent.getData().toString()为:content://com.android.providers.media.documents/document/image%3A730538
        11-14 20:27:31.925 6291-6291/com.example.liang.myapplication I/xinxi: uri.getAuthority()为:com.android.providers.media.documents
        11-14 20:27:31.925 6291-6291/com.example.liang.myapplication I/xinxi: uri.getScheme()为:content
        11-14 20:27:31.925 6291-6291/com.example.liang.myapplication I/xinxi: DocumentsContract.getDocumentId(uri)为:image:730538
        11-14 20:28:07.195 6291-6291/com.example.liang.myapplication I/xinxi: intent.getData().toString()为:content://com.android.providers.media.documents/document/image%3A124644
        11-14 20:28:07.195 6291-6291/com.example.liang.myapplication I/xinxi: uri.getAuthority()为:com.android.providers.media.documents
        11-14 20:28:07.195 6291-6291/com.example.liang.myapplication I/xinxi: uri.getScheme()为:content
        11-14 20:28:07.195 6291-6291/com.example.liang.myapplication I/xinxi: DocumentsContract.getDocumentId(uri)为:image:124644*/
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String docid = DocumentsContract.getDocumentId(uri);
            Log.i("xinxi", "DocumentsContract.getDocumentId(uri)为:" + DocumentsContract.getDocumentId(uri));
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                String id = docid.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagepath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())) {
                Uri contenturi = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.parseLong(docid));
                imagepath = getImagePath(contenturi, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagepath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagepath = uri.getPath();
        }
        showImage(imagepath);
    }

    private void another(Intent intent) {
        Uri uri = intent.getData();
        String imagepath = getImagePath(uri, null);
        showImage(imagepath);
    }

    private void showImage(String imagepath) {
        if (imagepath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagepath);
            imageView.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this, "没有得到图片", Toast.LENGTH_SHORT).show();
        }
    }

    private String getImagePath(Uri externalContentUri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(externalContentUri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToNext()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

记得在androidmanifest中申明

例三:简单的音乐播放器
调用摄像头和相册,音乐控制,视频控制_第2张图片
device-2017-11-14-211121.png
public class MainActivity extends AppCompatActivity {
    private Button button;
    private Button button1;
    private Button button2;
    private MediaPlayer mediaplayer = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        quanxian();
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mediaplayer.isPlaying()) {
                    mediaplayer.start();
                }
            }
        });
        button1.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                if (mediaplayer.isPlaying()) {
                    mediaplayer.pause();
                }
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaplayer.isPlaying()) {
                    mediaplayer.reset();
                    chushihua();
                }
            }
        });
    }

    private void quanxian() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            chushihua();
        }
    }

    private void chushihua() {
        File file = new File(Environment.getExternalStorageDirectory(), "1.mp3");//要想得到手机存储中任意文件的路径就需要用到Environment,如果是app的关联缓存路径的话直接getExternalCacheDir()
        Log.i("xinxi", "Environment.getExternalStorageDirectory()为:" + Environment.getExternalStorageDirectory() + "");
        Log.i("xinxi", "file.getPath()为" + file.getPath());
       /* Log日志输出如下:
        11-14 21:14:21.265 22529-22529/com.example.liang.myapplication I/xinxi: Environment.getExternalStorageDirectory()为:/storage/emulated/0
        11-14 21:14:21.265 22529-22529/com.example.liang.myapplication I/xinxi: file.getPath()为/storage/emulated/0/1.mp3*/
        try {
            mediaplayer.setDataSource(file.getPath());
            mediaplayer.prepare();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {//这个方法是当系统提示用户是否开启权限的时,当用户选择开启或者是禁止时触发的
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case (1):
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)//grant是同意的意思,grantResults这个参数中放的是0或者是1,0表示同意,1表示禁止
                {
                    Toast.makeText(MainActivity.this, "已经有权限了", Toast.LENGTH_SHORT).show();
                    chushihua();
                } else {
                    Toast.makeText(MainActivity.this, "请先申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaplayer!=null){
            mediaplayer.stop();
            mediaplayer.release();
        }
    }
}

记得在androidmanifest中申明

例四:简单的视频播放器
调用摄像头和相册,音乐控制,视频控制_第3张图片
device-2017-11-14-212720.png
public class MainActivity extends AppCompatActivity {
    private Button button;
    private Button button1;
    private Button button2;
    private VideoView videoview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button) findViewById(R.id.button);
        button1 = (Button) findViewById(R.id.button1);
        button2 = (Button) findViewById(R.id.button2);
        videoview= (VideoView) findViewById(R.id.videoView);
        quanxian();
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!videoview.isPlaying()) {
                    videoview.start();//开始播放
                }
            }
        });
        button1.setOnClickListener(new View.OnClickListener()

        {
            @Override
            public void onClick(View v) {
                if (videoview.isPlaying()) {
                    videoview.pause();//暂停播放
                }
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (videoview.isPlaying()) {
                    videoview.resume();//重新播放
                }
            }
        });
    }

    private void quanxian() {
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        } else {
            chushihua();
        }
    }

    private void chushihua() {
        File file = new File(Environment.getExternalStorageDirectory(), "mo.mp4");//要想得到手机存储中任意文件的路径就需要用到Environment,如果是app的关联缓存路径的话直接getExternalCacheDir()
        Log.i("xinxi", "Environment.getExternalStorageDirectory()为:" + Environment.getExternalStorageDirectory() + "");
        Log.i("xinxi", "file.getPath()为" + file.getPath());
       /* Log日志输出如下:
        11-14 21:14:21.265 22529-22529/com.example.liang.myapplication I/xinxi: Environment.getExternalStorageDirectory()为:/storage/emulated/0
        11-14 21:14:21.265 22529-22529/com.example.liang.myapplication I/xinxi: file.getPath()为/storage/emulated/0/mo.mp4*/
        videoview.setVideoPath(file.getPath());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {//这个方法是当系统提示用户是否开启权限的时,当用户选择开启或者是禁止时触发的
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case (1):
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)//grant是同意的意思,grantResults这个参数中放的是0或者是1,0表示同意,1表示禁止
                {
                    Toast.makeText(MainActivity.this, "已经有权限了", Toast.LENGTH_SHORT).show();
                    chushihua();
                } else {
                    Toast.makeText(MainActivity.this, "请先申请权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(videoview!=null){
            videoview.suspend();
        }
    }
}

记得在androidmanifest中申明

你可能感兴趣的:(调用摄像头和相册,音乐控制,视频控制)