1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.nfc.beam;
18 
19 import android.content.ContentResolver;
20 import android.content.Context;
21 import android.net.Uri;
22 import android.util.Log;
23 import android.webkit.MimeTypeMap;
24 
25 public final class MimeTypeUtil {
26 
27     private static final String TAG = "MimeTypeUtil";
28 
MimeTypeUtil()29     private MimeTypeUtil() {}
30 
getMimeTypeForUri(Context context, Uri uri)31     public static String getMimeTypeForUri(Context context, Uri uri) {
32         if (uri.getScheme() == null) return null;
33 
34         if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
35             ContentResolver cr = context.getContentResolver();
36             return cr.getType(uri);
37         } else if (uri.getScheme().equals(ContentResolver.SCHEME_FILE)) {
38             String extension = null;
39             String filePath = uri.getPath().toLowerCase();
40             int index = filePath.lastIndexOf(".");
41             if (index > 0 && index + 1 < filePath.length()) {
42                 extension = filePath.substring(index + 1);
43             }
44             if (extension != null) {
45                 return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
46             } else {
47                 return null;
48             }
49         } else {
50             Log.d(TAG, "Could not determine mime type for Uri " + uri);
51             return null;
52         }
53     }
54 }
55