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");
    }
}

  

时间: 2025-01-30 09:29:18

Android Assert工具类的相关文章

19个Android常用工具类汇总

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

Android常用工具类

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

优化-Android中工具类的设计

问题描述 Android中工具类的设计 两种方案: 1.工具类的方法设置为静态方法 2.工具类设置成单例模式,获取实例调用 哪一种方案相对好一点呢?求大神指点 解决方案 单例模式,实例是application是同级的,只要在application销毁的情况下才会销毁,再者如果你的单例如果持有一些context的引用的话,会导致该context 无法释放,有内存泄露的风险.反之静态方法会比单例好很多!提醒你,人家回答你,要先说谢谢,不要什么都不说就直接追问,最基本的尊重还是要有的 解决方案二: A

android 一些工具类汇总_Android

一 Paint ,Canvas public class drawView extends View{ private Paint paint1; public drawView(Context context,AttributeSet set ){ super(context,set); } public void onDraw(Canvas canvas){ super.onDraw(canvas); //new 一个画笔对象 paint1= new Paint(); canvas.draw

Android 在工具类里面将数据传到notification

问题描述 Android 在工具类里面将数据传到notification 这方法是在一个工具类里面的,现在我想把每个循环得到的数据放在notification 中实现动态更新进度条 .要怎么做? 解决方案 http://www.oschina.net/question/169169_79209

19个Android常用工具类汇总_php实例

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

Android Joda-time工具类

  Joda-Time提供了一组Java类包用于处理包括ISO8601标准在内的date和time.可以利用它把JDK Date和Calendar类完全替换掉,而且仍然能够提供很好的集成.   Joda-Time主要的特点包括:    1. 易于使用:Calendar让获取"正常的"的日期变得很困难,使它没办法提供简单的方法,而Joda-Time能够 直接进行访问域并且索引值1就是代表January.    2. 易于扩展:JDK支持多日历系统是通过Calendar的子类来实现,这样就

android自动工具类TextUtils使用详解

今天,简单讲讲如何使用android自动的工具类TextUtils. 简单列举部分用法: Log.d(TAG, "---------------------------------"); //字符串拼接 Log.d(TAG, TextUtils.concat("Hello", " ", "world!").toString()); //判断是否为空字符串 Log.d(TAG, TextUtils.isEmpty("H

Android Log工具类

import java.text.SimpleDateFormat; import java.util.Date; import android.util.Log; public class LogUtil { private static final boolean DEBUG = true; public static void d(String TAG, String method, String msg) { Log.d(TAG, "[" + method + "]&