BluetoothOppUtility.java revision ce4d93666275df294cb073fe41de5b85932570a8
1/*
2 * Copyright (c) 2008-2009, Motorola, Inc.
3 *
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * - Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 *
12 * - Redistributions in binary form must reproduce the above copyright notice,
13 * this list of conditions and the following disclaimer in the documentation
14 * and/or other materials provided with the distribution.
15 *
16 * - Neither the name of the Motorola, Inc. nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33package com.android.bluetooth.opp;
34
35import com.android.bluetooth.R;
36import com.google.android.collect.Lists;
37
38
39import android.bluetooth.BluetoothAdapter;
40import android.bluetooth.BluetoothDevice;
41import android.net.Uri;
42import android.content.ContentValues;
43import android.content.Context;
44import android.content.ActivityNotFoundException;
45import android.content.Intent;
46import android.content.pm.PackageManager;
47import android.content.pm.ResolveInfo;
48import android.database.Cursor;
49import android.util.Log;
50
51import java.io.File;
52import java.util.ArrayList;
53import java.util.List;
54
55/**
56 * This class has some utilities for Opp application;
57 */
58public class BluetoothOppUtility {
59    private static final String TAG = "BluetoothOppUtility";
60    private static final boolean D = Constants.DEBUG;
61    private static final boolean V = Constants.VERBOSE;
62
63    public static BluetoothOppTransferInfo queryRecord(Context context, Uri uri) {
64        BluetoothAdapter adapter =
65                (BluetoothAdapter) context.getSystemService(Context.BLUETOOTH_SERVICE);
66        BluetoothOppTransferInfo info = new BluetoothOppTransferInfo();
67        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
68        if (cursor != null) {
69            if (cursor.moveToFirst()) {
70                info.mID = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare._ID));
71                info.mStatus = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.STATUS));
72                info.mDirection = cursor.getInt(cursor
73                        .getColumnIndexOrThrow(BluetoothShare.DIRECTION));
74                info.mTotalBytes = cursor.getInt(cursor
75                        .getColumnIndexOrThrow(BluetoothShare.TOTAL_BYTES));
76                info.mCurrentBytes = cursor.getInt(cursor
77                        .getColumnIndexOrThrow(BluetoothShare.CURRENT_BYTES));
78                info.mTimeStamp = cursor.getLong(cursor
79                        .getColumnIndexOrThrow(BluetoothShare.TIMESTAMP));
80                info.mDestAddr = cursor.getString(cursor
81                        .getColumnIndexOrThrow(BluetoothShare.DESTINATION));
82
83                info.mFileName = cursor.getString(cursor
84                        .getColumnIndexOrThrow(BluetoothShare._DATA));
85                if (info.mFileName == null) {
86                    info.mFileName = cursor.getString(cursor
87                            .getColumnIndexOrThrow(BluetoothShare.FILENAME_HINT));
88                }
89                if (info.mFileName == null) {
90                    info.mFileName = context.getString(R.string.unknown_file);
91                }
92
93                info.mFileUri = cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.URI));
94
95                if (info.mFileUri != null) {
96                    Uri u = Uri.parse(info.mFileUri);
97                    info.mFileType = context.getContentResolver().getType(u);
98                } else {
99                    Uri u = Uri.parse(info.mFileName);
100                    info.mFileType = context.getContentResolver().getType(u);
101                }
102                if (info.mFileType == null) {
103                    info.mFileType = cursor.getString(cursor
104                            .getColumnIndexOrThrow(BluetoothShare.MIMETYPE));
105                }
106
107                BluetoothDevice remoteDevice = adapter.getRemoteDevice(info.mDestAddr);
108                info.mDeviceName =
109                        BluetoothOppManager.getInstance(context).getDeviceName(remoteDevice);
110
111                if (V) Log.v(TAG, "Get data from db:" + info.mFileName + info.mFileType
112                            + info.mDestAddr);
113            }
114            cursor.close();
115        } else {
116            info = null;
117            if (V) Log.v(TAG, "BluetoothOppManager Error: not got data from db for uri:" + uri);
118        }
119        return info;
120    }
121
122    /**
123     * Organize Array list for transfers in one batch
124     */
125    public static ArrayList<String> queryTransfersInBatch(Context context, Long timeStamp) {
126        ArrayList<String> uris = Lists.newArrayList();
127        final String WHERE = BluetoothShare.TIMESTAMP + " == " + timeStamp;
128
129        Cursor metadataCursor = context.getContentResolver().query(BluetoothShare.CONTENT_URI,
130                new String[] {
131                    BluetoothShare._DATA
132                }, WHERE, null, BluetoothShare._ID);
133
134        if (metadataCursor == null) {
135            return null;
136        }
137
138        for (metadataCursor.moveToFirst(); !metadataCursor.isAfterLast(); metadataCursor
139                .moveToNext()) {
140            String fileName = metadataCursor.getString(0);
141            Uri path = Uri.parse(fileName);
142            // If there is no scheme, then it must be a file
143            if (path.getScheme() == null) {
144                path = Uri.fromFile(new File(fileName));
145            }
146            uris.add(path.toString());
147            if (V) Log.d(TAG, "Uri in this batch: " + path.toString());
148        }
149        metadataCursor.close();
150        return uris;
151    }
152
153    /**
154     * Open the received file with appropriate application, if can not find
155     * application to handle, display error dialog.
156     */
157    public static void openReceivedFile(Context context, String fileName, String mimetype,
158            Long timeStamp) {
159        if (fileName == null || mimetype == null) {
160            Log.e(TAG, "ERROR: Para fileName ==null, or mimetype == null");
161            return;
162        }
163
164        File f = new File(fileName);
165        if (!f.exists()) {
166            Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
167            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
168            in.putExtra("title", context.getString(R.string.not_exist_file));
169            in.putExtra("content", context.getString(R.string.not_exist_file_desc));
170            context.startActivity(in);
171            return;
172        }
173
174        Uri path = Uri.parse(fileName);
175        // If there is no scheme, then it must be a file
176        if (path.getScheme() == null) {
177            path = Uri.fromFile(new File(fileName));
178        }
179
180        if (isRecognizedFileType(context, path, mimetype)) {
181            Intent activityIntent = new Intent(Intent.ACTION_VIEW);
182            activityIntent.setDataAndType(path, mimetype);
183
184            activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
185            try {
186                if (V) Log.d(TAG, "ACTION_VIEW intent sent out: " + path + " / " + mimetype);
187                context.startActivity(activityIntent);
188            } catch (ActivityNotFoundException ex) {
189                if (V) Log.d(TAG, "no activity for handling ACTION_VIEW intent:  " + mimetype, ex);
190            }
191        } else {
192            Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
193            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
194            in.putExtra("title", context.getString(R.string.unknown_file));
195            in.putExtra("content", context.getString(R.string.unknown_file_desc));
196            context.startActivity(in);
197        }
198    }
199
200    /**
201     * To judge if the file type supported (can be handled by some app) by phone
202     * system.
203     */
204    public static boolean isRecognizedFileType(Context context, Uri fileUri, String mimetype) {
205        boolean ret = true;
206
207        if (D) Log.d(TAG, "RecognizedFileType() fileUri: " + fileUri + " mimetype: " + mimetype);
208
209        Intent mimetypeIntent = new Intent(Intent.ACTION_VIEW);
210        mimetypeIntent.setDataAndType(fileUri, mimetype);
211        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(mimetypeIntent,
212                PackageManager.MATCH_DEFAULT_ONLY);
213
214        if (list.size() == 0) {
215            if (D) Log.d(TAG, "NO application to handle MIME type " + mimetype);
216            ret = false;
217        }
218        return ret;
219    }
220
221    /**
222     * update visibility to Hidden
223     */
224    public static void updateVisibilityToHidden(Context context, Uri uri) {
225        ContentValues updateValues = new ContentValues();
226        updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
227        context.getContentResolver().update(uri, updateValues, null, null);
228    }
229
230    /**
231     * Helper function to build the progress text.
232     */
233    public static String formatProgressText(long totalBytes, long currentBytes) {
234        if (totalBytes <= 0) {
235            return "0%";
236        }
237        long progress = currentBytes * 100 / totalBytes;
238        StringBuilder sb = new StringBuilder();
239        sb.append(progress);
240        sb.append('%');
241        return sb.toString();
242    }
243
244    /**
245     * Get status description according to status code.
246     */
247    public static String getStatusDescription(Context context, int statusCode) {
248        String ret;
249        if (statusCode == BluetoothShare.STATUS_PENDING) {
250            ret = context.getString(R.string.status_pending);
251        } else if (statusCode == BluetoothShare.STATUS_RUNNING) {
252            ret = context.getString(R.string.status_running);
253        } else if (statusCode == BluetoothShare.STATUS_SUCCESS) {
254            ret = context.getString(R.string.status_success);
255        } else if (statusCode == BluetoothShare.STATUS_NOT_ACCEPTABLE) {
256            ret = context.getString(R.string.status_not_accept);
257        } else if (statusCode == BluetoothShare.STATUS_FORBIDDEN) {
258            ret = context.getString(R.string.status_forbidden);
259        } else if (statusCode == BluetoothShare.STATUS_CANCELED) {
260            ret = context.getString(R.string.status_canceled);
261        } else if (statusCode == BluetoothShare.STATUS_FILE_ERROR) {
262            ret = context.getString(R.string.status_file_error);
263        } else if (statusCode == BluetoothShare.STATUS_ERROR_NO_SDCARD) {
264            ret = context.getString(R.string.status_no_sd_card);
265        } else if (statusCode == BluetoothShare.STATUS_CONNECTION_ERROR) {
266            ret = context.getString(R.string.status_connection_error);
267        } else if (statusCode == BluetoothShare.STATUS_ERROR_SDCARD_FULL) {
268            ret = context.getString(R.string.bt_sm_2_1);
269        } else if ((statusCode == BluetoothShare.STATUS_BAD_REQUEST)
270                || (statusCode == BluetoothShare.STATUS_LENGTH_REQUIRED)
271                || (statusCode == BluetoothShare.STATUS_PRECONDITION_FAILED)
272                || (statusCode == BluetoothShare.STATUS_UNHANDLED_OBEX_CODE)
273                || (statusCode == BluetoothShare.STATUS_OBEX_DATA_ERROR)) {
274            ret = context.getString(R.string.status_protocol_error);
275        } else {
276            ret = context.getString(R.string.status_unknown_error);
277        }
278        return ret;
279    }
280
281    /**
282     * Retry the failed transfer: Will insert a new transfer session to db
283     */
284    public static void retryTransfer(Context context, BluetoothOppTransferInfo transInfo) {
285        ContentValues values = new ContentValues();
286        values.put(BluetoothShare.URI, transInfo.mFileUri);
287        values.put(BluetoothShare.MIMETYPE, transInfo.mFileType);
288        values.put(BluetoothShare.DESTINATION, transInfo.mDestAddr);
289
290        final Uri contentUri = context.getContentResolver().insert(BluetoothShare.CONTENT_URI,
291                values);
292        if (V) Log.v(TAG, "Insert contentUri: " + contentUri + "  to device: " +
293                transInfo.mDeviceName);
294    }
295
296}
297