BluetoothOppUtility.java revision 888485a3f5fe991116c5536bb6d6903d47b63a70
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    // This function is used when UI show batch transfer. Currently only show single transfer.
126    public static ArrayList<String> queryTransfersInBatch(Context context, Long timeStamp) {
127        ArrayList<String> uris = Lists.newArrayList();
128        final String WHERE = BluetoothShare.TIMESTAMP + " == " + timeStamp;
129
130        Cursor metadataCursor = context.getContentResolver().query(BluetoothShare.CONTENT_URI,
131                new String[] {
132                    BluetoothShare._DATA
133                }, WHERE, null, BluetoothShare._ID);
134
135        if (metadataCursor == null) {
136            return null;
137        }
138
139        for (metadataCursor.moveToFirst(); !metadataCursor.isAfterLast(); metadataCursor
140                .moveToNext()) {
141            String fileName = metadataCursor.getString(0);
142            Uri path = Uri.parse(fileName);
143            // If there is no scheme, then it must be a file
144            if (path.getScheme() == null) {
145                path = Uri.fromFile(new File(fileName));
146            }
147            uris.add(path.toString());
148            if (V) Log.d(TAG, "Uri in this batch: " + path.toString());
149        }
150        metadataCursor.close();
151        return uris;
152    }
153
154    /**
155     * Open the received file with appropriate application, if can not find
156     * application to handle, display error dialog.
157     */
158    public static void openReceivedFile(Context context, String fileName, String mimetype,
159            Long timeStamp) {
160        if (fileName == null || mimetype == null) {
161            Log.e(TAG, "ERROR: Para fileName ==null, or mimetype == null");
162            return;
163        }
164
165        File f = new File(fileName);
166        if (!f.exists()) {
167            Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
168            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
169            in.putExtra("title", context.getString(R.string.not_exist_file));
170            in.putExtra("content", context.getString(R.string.not_exist_file_desc));
171            context.startActivity(in);
172            return;
173        }
174
175        Uri path = Uri.parse(fileName);
176        // If there is no scheme, then it must be a file
177        if (path.getScheme() == null) {
178            path = Uri.fromFile(new File(fileName));
179        }
180
181        if (isRecognizedFileType(context, path, mimetype)) {
182            Intent activityIntent = new Intent(Intent.ACTION_VIEW);
183            activityIntent.setDataAndType(path, mimetype);
184
185            activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
186            try {
187                if (V) Log.d(TAG, "ACTION_VIEW intent sent out: " + path + " / " + mimetype);
188                context.startActivity(activityIntent);
189            } catch (ActivityNotFoundException ex) {
190                if (V) Log.d(TAG, "no activity for handling ACTION_VIEW intent:  " + mimetype, ex);
191            }
192        } else {
193            Intent in = new Intent(context, BluetoothOppBtErrorActivity.class);
194            in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
195            in.putExtra("title", context.getString(R.string.unknown_file));
196            in.putExtra("content", context.getString(R.string.unknown_file_desc));
197            context.startActivity(in);
198        }
199    }
200
201    /**
202     * To judge if the file type supported (can be handled by some app) by phone
203     * system.
204     */
205    public static boolean isRecognizedFileType(Context context, Uri fileUri, String mimetype) {
206        boolean ret = true;
207
208        if (D) Log.d(TAG, "RecognizedFileType() fileUri: " + fileUri + " mimetype: " + mimetype);
209
210        Intent mimetypeIntent = new Intent(Intent.ACTION_VIEW);
211        mimetypeIntent.setDataAndType(fileUri, mimetype);
212        List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(mimetypeIntent,
213                PackageManager.MATCH_DEFAULT_ONLY);
214
215        if (list.size() == 0) {
216            if (D) Log.d(TAG, "NO application to handle MIME type " + mimetype);
217            ret = false;
218        }
219        return ret;
220    }
221
222    /**
223     * update visibility to Hidden
224     */
225    public static void updateVisibilityToHidden(Context context, Uri uri) {
226        ContentValues updateValues = new ContentValues();
227        updateValues.put(BluetoothShare.VISIBILITY, BluetoothShare.VISIBILITY_HIDDEN);
228        context.getContentResolver().update(uri, updateValues, null, null);
229    }
230
231    /**
232     * Helper function to build the progress text.
233     */
234    public static String formatProgressText(long totalBytes, long currentBytes) {
235        if (totalBytes <= 0) {
236            return "0%";
237        }
238        long progress = currentBytes * 100 / totalBytes;
239        StringBuilder sb = new StringBuilder();
240        sb.append(progress);
241        sb.append('%');
242        return sb.toString();
243    }
244
245    /**
246     * Get status description according to status code.
247     */
248    public static String getStatusDescription(Context context, int statusCode) {
249        String ret;
250        if (statusCode == BluetoothShare.STATUS_PENDING) {
251            ret = context.getString(R.string.status_pending);
252        } else if (statusCode == BluetoothShare.STATUS_RUNNING) {
253            ret = context.getString(R.string.status_running);
254        } else if (statusCode == BluetoothShare.STATUS_SUCCESS) {
255            ret = context.getString(R.string.status_success);
256        } else if (statusCode == BluetoothShare.STATUS_NOT_ACCEPTABLE) {
257            ret = context.getString(R.string.status_not_accept);
258        } else if (statusCode == BluetoothShare.STATUS_FORBIDDEN) {
259            ret = context.getString(R.string.status_forbidden);
260        } else if (statusCode == BluetoothShare.STATUS_CANCELED) {
261            ret = context.getString(R.string.status_canceled);
262        } else if (statusCode == BluetoothShare.STATUS_FILE_ERROR) {
263            ret = context.getString(R.string.status_file_error);
264        } else if (statusCode == BluetoothShare.STATUS_ERROR_NO_SDCARD) {
265            ret = context.getString(R.string.status_no_sd_card);
266        } else if (statusCode == BluetoothShare.STATUS_CONNECTION_ERROR) {
267            ret = context.getString(R.string.status_connection_error);
268        } else if (statusCode == BluetoothShare.STATUS_ERROR_SDCARD_FULL) {
269            ret = context.getString(R.string.bt_sm_2_1);
270        } else if ((statusCode == BluetoothShare.STATUS_BAD_REQUEST)
271                || (statusCode == BluetoothShare.STATUS_LENGTH_REQUIRED)
272                || (statusCode == BluetoothShare.STATUS_PRECONDITION_FAILED)
273                || (statusCode == BluetoothShare.STATUS_UNHANDLED_OBEX_CODE)
274                || (statusCode == BluetoothShare.STATUS_OBEX_DATA_ERROR)) {
275            ret = context.getString(R.string.status_protocol_error);
276        } else {
277            ret = context.getString(R.string.status_unknown_error);
278        }
279        return ret;
280    }
281
282    /**
283     * Retry the failed transfer: Will insert a new transfer session to db
284     */
285    public static void retryTransfer(Context context, BluetoothOppTransferInfo transInfo) {
286        ContentValues values = new ContentValues();
287        values.put(BluetoothShare.URI, transInfo.mFileUri);
288        values.put(BluetoothShare.MIMETYPE, transInfo.mFileType);
289        values.put(BluetoothShare.DESTINATION, transInfo.mDestAddr);
290
291        final Uri contentUri = context.getContentResolver().insert(BluetoothShare.CONTENT_URI,
292                values);
293        if (V) Log.v(TAG, "Insert contentUri: " + contentUri + "  to device: " +
294                transInfo.mDeviceName);
295    }
296
297}
298