多媒体【通知,拍摄及相册】

1.通知

private void notification() {
        // 构建意图
        Intent intent = new Intent(this, LoginActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        // 获取系统通知管理服务
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // 构建Notification
        Notification.Builder notification = new Notification.Builder(this)
                .setContentTitle("你好啊,Title")   // 设置标题
                .setContentText("独爱空城梦")   // 设置内容
                .setWhen(System.currentTimeMillis())   // 指定通知被创建时间
                .setSmallIcon(R.drawable.ic_small)   // 设置小图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_biggest))  // 设置大图标
                .setContentIntent(pendingIntent)   // 跳转
                .setAutoCancel(true)  // 取消通知
                .setVibrate(new long[]{0, 1000, 1000, 1000})  // 通知时震动
                .setLights(Color.GREEN, 1000, 1000);  // 取消通知

        // 兼容  API 26,Android 8.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("AppTestNotificationId", "AppTestNotificationName", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(notificationChannel);
            notification.setChannelId("AppTestNotificationId");
        }
        manager.notify(1, notification.build());
    }

运行结果,pass
2、调用摄像头拍照
创建File对象,用于存储摄像头拍下的照片,如命名为test_image.jpg,将它存放在手机SD卡的应用关联缓存目录(指SD卡中专门用于存放当前应用缓存数据的位置,调用getExternalCacheDir()方法可以得到这个目录,/sdcard/Android/data/< package name >/cache)下。
其次,做一些判断,若运行设备的系统版本低于Android7.0,调用Uri的formFile()方法将File对象转换为Uri对象,Uri对象标识这张图片的本地真实路径;否则就调用getUriForFile()方法(3个参数,参数1-context,参数2-任意字符串,参数3-File对象)将File对象转换成一个封装的Uri对象,提高安全性。
操作如下:
1】设置布局

<Button
        android:id="@+id/photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="take photo"
        android:textAllCaps="false" />

    <ImageView
        android:id="@+id/picture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />

2】修改配置文件,添加权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
........
<!-- 为application添加属性值 -->
android:requestLegacyExternalStorage="true"
........
<!-- 为调用相机拍照设置内容提供者 -->
        <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="com.example.android.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>

3】在res中新建文件夹xml并创建file_paths布局文件
4】activity实现
第一种:

private void takePhoto() {
        // 创建File对象,用于存储拍照后的照片
        File outputImage = new File(getExternalCacheDir(), "test_image.jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (IOException exception) {
            exception.printStackTrace();
        }
        if (Build.VERSION.SDK_INT >= 24) {
            mImgUri = FileProvider.getUriForFile(this, "com.example.android.fileprovider", outputImage);
        } else {
            mImgUri = Uri.fromFile(outputImage);
        }
        // 启用相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputImage);
        startActivityForResult(intent, TAKE_PHOTO);
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拍摄
        switch (requestCode) {
            case TAKE_PHOTO:
                if (requestCode == RESULT_OK) {
                    try {
                        // 将图片解析成Bitmap对象,并把它显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImgUri));
                        mPicture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException exception) {
                        exception.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

第二种:

@Override
    protected void onCreate(Bundle savedInstanceState) {
    ..........
mPicture = findViewById(R.id.picture);
mPhoto = findViewById(R.id.photo);
mPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  若用户给予权限则请求相机拍照
                requestPermission();
            }
        });
        // 设置默认图片
        setDefaultImage();
}

// 动态请求权限
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
                    , Manifest.permission.CAMERA}, 1);
        } else {
            // 调用
            requestCamera();
        }

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 拍照
         if (grantResults != null && grantResults.length != 0 && grantResults[0]
                == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case 1: {
                    requestCamera();
                }
                break;
            }
        }
     }

private void requestCamera() {
        // 创建File对象,用于存储拍照后的照片
        File outputImage = new File(getExternalCacheDir(), "test_image.jpg");
        try {
            if (!outputImage.getParentFile().exists()) {
                outputImage.getParentFile().mkdir();
            }
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();

            if (Build.VERSION.SDK_INT >= 24) {
                mImgUri = FileProvider.getUriForFile(this, "com.example.android.fileprovider"
                        , outputImage);
            } else {
                mImgUri = Uri.fromFile(outputImage);
            }
            // 使用隐式Intent,系统会找到与它对应的活动,即调用摄像头,并把它存储
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputImage);
            startActivityForResult(intent, TAKE_PHOTO);
            // 调用会返回结果的开启方式,返回成功的话,则把它显示出来
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 拍摄
        switch (requestCode) {
            case TAKE_PHOTO:
                if (requestCode == RESULT_OK) {
                    try {
                        // 将图片解析成Bitmap对象,并把它显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mImgUri));
                        mPicture.setImageBitmap(bitmap);
                    } catch (FileNotFoundException exception) {
                        exception.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
     }

// 设置保存拍照图片,再次关闭app重新打开显示上次拍照照片
    private void setDefaultImage() {
        File outputImage = new File(filePath);
        if (!outputImage.exists()) {
            return;
        }
        mPicture.setImageBitmap(BitmapFactory.decodeFile(filePath));
    }

错误1:

java.lang.RuntimeException: Unable to get provider android.support.v4.content.FileProvider: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.FileProvider" on path: DexPathList[[zip file "/data/app/~~4q40YQIoxIYDn3lioWTd1g==/com.example.android-Ny4Bbqw7fPUXasO3ssa89g==/base.apk"]

解决方法
AndroidManifest中 android.support.v4.content.FileProvider 替换成 androidx.core.content.FileProvider
错误2:

W/Bundle: Key output expected Parcelable but value was a java.io.File.  The default value <null> was returned.
W/Bundle: Attempt to cast generated internal exception:
    java.lang.ClassCastException: java.io.File cannot be cast to android.os.Parcelable
        at android.os.Bundle.getParcelable(Bundle.java:957)......

在这里插入图片描述
运行结果,failed,后续解决…
3.从相册中选择图片
1】Activity实现

@Override
    protected void onCreate(Bundle savedInstanceState) {
    ..........
    // 从相册中选择照片
        mImgPicture = findViewById(R.id.selectImg);
        mBtnPicture = findViewById(R.id.chosePicture);
        mBtnPicture.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 {
                    // 调用
                    openAlbum();
                }
            }
        });
}

private void openAlbum() {
        Intent intent = new Intent();
        // 第一种
        // intent.setAction(Intent.ACTION_PICK);
        // 第二种
        // intent.setAction(Intent.ACTION_GET_CONTENT);
        // 第三种
        intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
       
        // 相册
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    openAlbum();
                } else {
                    Log.i(TAG, "you denied the permission");
                }
                break;
            default:
                break;
        }
     }

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    // 相册
        switch (requestCode) {
            case CHOOSE_PHOTO:
                if (requestCode == RESULT_OK) {
                    // 判断手机系统版本号
                    if (Build.VERSION.SDK_INT >= 19) {
                        // 4.4及以上系统使用这个方法处理图片
                        handleImageOnKitKat(data);
                    } else {
                        // 4.4以下系统使用这个方法处理图片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
     }

@RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            // 如果是document类型的Uri,则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())) {
                // 解析出数字格式的id
                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.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是document类型的Uri,则使用普通方法处理
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            // 如果是file类型的Uri,直接获取图片路径即可
            imagePath = uri.getPath();
        }
        // 根据图片路径显示图片
        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri和selection来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            mImgPicture.setImageBitmap(bitmap);
        } else {
            Log.i(TAG, "failed to get image");
        }
    }

运行结果,failed,后续解决…
错误3:

I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time
V/AudioManager: querySoundEffectsEnabled...
D/HwFrameworkSecurityPartsFactory: HwFrameworkSecurityPartsFactory in.
I/HwFrameworkSecurityPartsFactory: add HwFrameworkSecurityPartsFactory to memory.
W/libEGL: EGLNativeWindowType 0x78bc45a310 disconnect failed
D/mali_winsys: EGLint new_window_surface(egl_winsys_display *, void *, EGLSurface, EGLConfig, egl_winsys_surface **, EGLBoolean) returns 0x3000
W/libEGL: EGLNativeWindowType 0x78bc45a310 disconnect failed

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值