Android Assert工具类

/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.example.android.justforus;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.OpenableColumns;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.IOException;

import static java.net.URLConnection.guessContentTypeFromName;

/**
 * Generic content provider, which makes any files available in this app‘s "assets" directory
 * available publicly.
 *
 * <p>To use, add the following to your AndroidManifest.xml:
 *
 * <code><pre>
 * <provider
 *   android:name=".AssetProvider"
 *   android:authorities="[YOUR CONTENT PROVIDER DOMAIN HERE]"
 *   android:grantUriPermissions="true"
 *   android:exported="true"/>
 * </pre></code>
 */
public class AssetProvider extends ContentProvider {

    /**
     * Content provider authority that identifies data that is offered by this
     * {@link AssetProvider}.
     */
    public static String CONTENT_URI = "com.example.android.justforus";

    private static final String TAG = "AssetProvider";

    AssetManager mAssets;

    @Override
    public boolean onCreate() {
        Context ctx = getContext();
        if (ctx == null) {
            // Context not available. Give up.
            return false;
        }
        mAssets = ctx.getAssets();
        return true;
    }

    @Override
    public String getType(Uri uri){
        // Returns the MIME type for the selected URI, in conformance with the ContentProvider
        // interface. Looks up the file indicated by /res/assets/{uri.path}, and returns the MIME
        // type for that file as guessed by the URLConnection class.

        // Setup
        String path = uri.getLastPathSegment();

        // Check if file exists
        if (!fileExists(path)) {
            return null;
        }

        // Determine MIME-type based on filename
        return guessContentTypeFromName(uri.toString());
    }

    @Override
    public AssetFileDescriptor openAssetFile (Uri uri, String mode)
            throws FileNotFoundException, SecurityException {
        // ContentProvider interface for opening a file descriptor by URI. This content provider
        // maps all URIs to the contents of the APK‘s assets folder, so a file handle to
        // /res/assets/{uri.path} will be returned.

        // Security check. This content provider only supports read-only access. (Also, the contents
        // of an APKs assets folder are immutable, so read-write access doesn‘t make sense here.)
        if (!"r".equals(mode)) {
            throw new SecurityException("Only read-only access is supported, mode must be [r]");
        }

        // Open asset from within APK and return file descriptor
        String path = uri.getLastPathSegment();
        try {
            return mAssets.openFd(path);
        } catch (IOException e) {
            throw new FileNotFoundException();
        }
    }

    /**
     * Check if file exists inside APK assets.
     *
     * @param path Fully qualified path to file.
     * @return true if exists, false otherwise.
     */
    private boolean fileExists(String path) {
        try {
            // Check to see if file can be opened. If so, file exists.
            mAssets.openFd(path).close();
            return true;
        } catch (IOException e) {
            // Unable to open file descriptor for specified path; file doesn‘t exist.
            return false;
        }
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        String path = uri.getLastPathSegment();
        if (!fileExists(path)) {
            Log.e(TAG, "Requested file doesn‘t exist at " + path);
            return null;
        }

        // Create matrix cursor
        if (projection == null) {
            projection = new String[]{
                    OpenableColumns.DISPLAY_NAME,
                    OpenableColumns.SIZE,
            };
        }

        MatrixCursor matrixCursor = new MatrixCursor(projection, 1);
        Object[] row = new Object[projection.length];
        for (int col = 0; col < projection.length; col++) {
            if (OpenableColumns.DISPLAY_NAME.equals(projection[col])) {
                row[col] = path;
            } else if (OpenableColumns.SIZE.equals(projection[col])) {
                try {
                    AssetFileDescriptor afd = openAssetFile(uri, "r");
                    if (afd != null) {
                        row[col] = Long.valueOf(afd.getLength());
                    }
                    afd.close();
                } catch (IOException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
        matrixCursor.addRow(row);
        return matrixCursor;
    }

    // Required/unused ContentProvider methods below.
    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        throw new RuntimeException("Operation not supported");
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        throw new RuntimeException("Operation not supported");
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        throw new RuntimeException("Operation not supported");
    }
}

  

时间: 2024-10-12 23:46:06

Android Assert工具类的相关文章

Android常用工具类

主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.SerializeUtils.S

Android基础工具类重构系列一Toast

前言: 一直在考虑写一下Android实际项目中的一些总结,翻看CSDN博客,上一篇已经是一年多曾经. 本系列定位Android基础工具类重构.旨在记录实际项目中经经常使用到的一些工具类,比方Toast.Dialog.动画类,ImageLoader类等等.正在梳理,但发现梳理完再写预计黄花菜都凉了.所以改变策略,边写边梳理. 首先要写的就是这个Toast. 一.说明 作为Android系统提供的基类,Toast是最简单的提示消息类.特点悬浮.跨界面(Activity)特定时间内自己主动销毁. 二

Android常用工具类(收藏)

Android常用工具类 主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java. 目前包括(HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.S

Android常用工具类 (转)

主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.SerializeUtils.S

53. Android常用工具类

主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.SerializeUtils.S

Android 系统工具类SystemUtils收集整理(持续更新)

最近做的功能中涉及到了一些关于系统方面的东西,自己摸索以及网上搜集整理出来了一个工具类方便调用 包含的功能有: 获取系统中所有APP应用.获取用户安装的APP应用.根据包名和Activity启动类查询应用信息.跳转到WIFI设置.WIFI网络开关.移动网络开关.GPS开关 当前若关则打开 当前若开则关闭.调节系统音量.设置亮度.获取屏幕的亮度.跳转到系统设置.获取文件夹下所有文件.获取视频的缩略图 .打开视频文件... 工具类会持续更新,与大家共同学习进步. SystemUtils.java p

Spring的Assert工具类的用法

简介 今天在看spring mvc源码时看到下面代码,感觉蛮有意思的,在这里记录下 Assert断言工具类,通常用于数据合法性检查,在JAVA编程中,通常会编写如下代码: if (name == null || name.equls("")) {      throw new IllegalArgumentException("参数错误!");  }        在所有方法中都使用手工检测合法性的方式并不是太好,因为这样影响了代码的可读性,若使用Assert工具类

Android 常用工具类之SPUtil,可以修改默认sp文件的路径

参考: 1. 利用Java反射机制改变SharedPreferences存储路径    Singleton1900 2. Android快速开发系列 10个常用工具类 Hongyang import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.content.SharedPreferences; import java.io.

Android自定义工具类获取按钮并绑定事件(利用暴力反射和注解)

Android中为按钮绑定事件的有几种常见方式,你可以在布局文件中为按钮设置id,然后在MainActivity中通过findViewById方法获取按钮对象实例,再通过setOnClickListener为按钮绑定事件,如下所示: //1.获取控件 btn = (Button)findViewById(R.id.button1); //2.绑定事件 btn.setOnClickListener(new OnClickListener() { @Override public void onCl