1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
|
/*
* Copyright (C) 2010 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.android.camerabrowser;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConstants;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.mtp.MtpDevice;
import android.mtp.MtpDeviceInfo;
import android.mtp.MtpObjectInfo;
import android.mtp.MtpStorageInfo;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* This class helps an application manage a list of connected MTP or PTP devices.
* It listens for MTP devices being attached and removed from the USB host bus
* and notifies the application when the MTP device list changes.
*/
public class MtpClient {
private static final String TAG = "MtpClient";
private static final String ACTION_USB_PERMISSION =
"android.mtp.MtpClient.action.USB_PERMISSION";
private final Context mContext;
private final UsbManager mUsbManager;
private final ArrayList<Listener> mListeners = new ArrayList<Listener>();
// mDevices contains all MtpDevices that have been seen by our client,
// so we can inform when the device has been detached.
// mDevices is also used for synchronization in this class.
private final HashMap<String, MtpDevice> mDevices = new HashMap<String, MtpDevice>();
private final PendingIntent mPermissionIntent;
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
UsbDevice usbDevice = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
String deviceName = usbDevice.getDeviceName();
synchronized (mDevices) {
MtpDevice mtpDevice = mDevices.get(deviceName);
if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
if (mtpDevice == null) {
mtpDevice = openDeviceLocked(usbDevice);
}
if (mtpDevice != null) {
for (Listener listener : mListeners) {
listener.deviceAdded(mtpDevice);
}
}
} else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
if (mtpDevice != null) {
mDevices.remove(deviceName);
for (Listener listener : mListeners) {
listener.deviceRemoved(mtpDevice);
}
}
} else if (ACTION_USB_PERMISSION.equals(action)) {
boolean permission = intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
false);
Log.d(TAG, "ACTION_USB_PERMISSION: " + permission);
if (permission) {
if (mtpDevice == null) {
mtpDevice = openDeviceLocked(usbDevice);
}
if (mtpDevice != null) {
for (Listener listener : mListeners) {
listener.deviceAdded(mtpDevice);
}
}
}
}
}
}
};
/**
* An interface for being notified when MTP or PTP devices are attached
* or removed. In the current implementation, only PTP devices are supported.
*/
public interface Listener {
/**
* Called when a new device has been added
*
* @param device the new device that was added
*/
public void deviceAdded(MtpDevice device);
/**
* Called when a new device has been removed
*
* @param device the device that was removed
*/
public void deviceRemoved(MtpDevice device);
}
/**
* Tests to see if a {@link android.hardware.usb.UsbDevice}
* supports the PTP protocol (typically used by digital cameras)
*
* @param device the device to test
* @return true if the device is a PTP device.
*/
static public boolean isCamera(UsbDevice device) {
int count = device.getInterfaceCount();
for (int i = 0; i < count; i++) {
UsbInterface intf = device.getInterface(i);
if (intf.getInterfaceClass() == UsbConstants.USB_CLASS_STILL_IMAGE &&
intf.getInterfaceSubclass() == 1 &&
intf.getInterfaceProtocol() == 1) {
return true;
}
}
return false;
}
/**
* MtpClient constructor
*
* @param context the {@link android.content.Context} to use for the MtpClient
*/
public MtpClient(Context context) {
mContext = context;
mUsbManager = (UsbManager)context.getSystemService(Context.USB_SERVICE);
mPermissionIntent = PendingIntent.getBroadcast(mContext, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
filter.addAction(ACTION_USB_PERMISSION);
context.registerReceiver(mUsbReceiver, filter);
}
/**
* Opens the {@link android.hardware.usb.UsbDevice} for an MTP or PTP
* device and return an {@link android.mtp.MtpDevice} for it.
*
* @param device the device to open
* @return an MtpDevice for the device.
*/
private MtpDevice openDeviceLocked(UsbDevice usbDevice) {
if (isCamera(usbDevice)) {
if (!mUsbManager.hasPermission(usbDevice)) {
mUsbManager.requestPermission(usbDevice, mPermissionIntent);
} else {
UsbDeviceConnection connection = mUsbManager.openDevice(usbDevice);
if (connection != null) {
MtpDevice mtpDevice = new MtpDevice(usbDevice);
if (mtpDevice.open(connection)) {
mDevices.put(usbDevice.getDeviceName(), mtpDevice);
return mtpDevice;
}
}
}
}
return null;
}
/**
* Closes all resources related to the MtpClient object
*/
public void close() {
mContext.unregisterReceiver(mUsbReceiver);
}
/**
* Registers a {@link android.mtp.MtpClient.Listener} interface to receive
* notifications when MTP or PTP devices are added or removed.
*
* @param listener the listener to register
*/
public void addListener(Listener listener) {
synchronized (mDevices) {
if (!mListeners.contains(listener)) {
mListeners.add(listener);
}
}
}
/**
* Unregisters a {@link android.mtp.MtpClient.Listener} interface.
*
* @param listener the listener to unregister
*/
public void removeListener(Listener listener) {
synchronized (mDevices) {
mListeners.remove(listener);
}
}
/**
* Retrieves an {@link android.mtp.MtpDevice} object for the USB device
* with the given name.
*
* @param deviceName the name of the USB device
* @return the MtpDevice, or null if it does not exist
*/
public MtpDevice getDevice(String deviceName) {
synchronized (mDevices) {
return mDevices.get(deviceName);
}
}
/**
* Retrieves an {@link android.mtp.MtpDevice} object for the USB device
* with the given ID.
*
* @param id the ID of the USB device
* @return the MtpDevice, or null if it does not exist
*/
public MtpDevice getDevice(int id) {
synchronized (mDevices) {
return mDevices.get(UsbDevice.getDeviceName(id));
}
}
/**
* Retrieves a list of all currently connected {@link android.mtp.MtpDevice}.
*
* @return the list of MtpDevices
*/
public List<MtpDevice> getDeviceList() {
synchronized (mDevices) {
// Query the USB manager since devices might have attached
// before we added our listener.
for (UsbDevice usbDevice : mUsbManager.getDeviceList().values()) {
if (mDevices.get(usbDevice.getDeviceName()) == null) {
openDeviceLocked(usbDevice);
}
}
return new ArrayList<MtpDevice>(mDevices.values());
}
}
/**
* Retrieves a list of all {@link android.mtp.MtpStorageInfo}
* for the MTP or PTP device with the given USB device name
*
* @param deviceName the name of the USB device
* @return the list of MtpStorageInfo
*/
public List<MtpStorageInfo> getStorageList(String deviceName) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return null;
}
int[] storageIds = device.getStorageIds();
if (storageIds == null) {
return null;
}
int length = storageIds.length;
ArrayList<MtpStorageInfo> storageList = new ArrayList<MtpStorageInfo>(length);
for (int i = 0; i < length; i++) {
MtpStorageInfo info = device.getStorageInfo(storageIds[i]);
if (info == null) {
Log.w(TAG, "getStorageInfo failed");
} else {
storageList.add(info);
}
}
return storageList;
}
/**
* Retrieves the {@link android.mtp.MtpObjectInfo} for an object on
* the MTP or PTP device with the given USB device name with the given
* object handle
*
* @param deviceName the name of the USB device
* @param objectHandle handle of the object to query
* @return the MtpObjectInfo
*/
public MtpObjectInfo getObjectInfo(String deviceName, int objectHandle) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return null;
}
return device.getObjectInfo(objectHandle);
}
/**
* Deletes an object on the MTP or PTP device with the given USB device name.
*
* @param deviceName the name of the USB device
* @param objectHandle handle of the object to delete
* @return true if the deletion succeeds
*/
public boolean deleteObject(String deviceName, int objectHandle) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return false;
}
return device.deleteObject(objectHandle);
}
/**
* Retrieves a list of {@link android.mtp.MtpObjectInfo} for all objects
* on the MTP or PTP device with the given USB device name and given storage ID
* and/or object handle.
* If the object handle is zero, then all objects in the root of the storage unit
* will be returned. Otherwise, all immediate children of the object will be returned.
* If the storage ID is also zero, then all objects on all storage units will be returned.
*
* @param deviceName the name of the USB device
* @param storageId the ID of the storage unit to query, or zero for all
* @param objectHandle the handle of the parent object to query, or zero for the storage root
* @return the list of MtpObjectInfo
*/
public List<MtpObjectInfo> getObjectList(String deviceName, int storageId, int objectHandle) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return null;
}
if (objectHandle == 0) {
// all objects in root of storage
objectHandle = 0xFFFFFFFF;
}
int[] handles = device.getObjectHandles(storageId, 0, objectHandle);
if (handles == null) {
return null;
}
int length = handles.length;
ArrayList<MtpObjectInfo> objectList = new ArrayList<MtpObjectInfo>(length);
for (int i = 0; i < length; i++) {
MtpObjectInfo info = device.getObjectInfo(handles[i]);
if (info == null) {
Log.w(TAG, "getObjectInfo failed");
} else {
objectList.add(info);
}
}
return objectList;
}
/**
* Returns the data for an object as a byte array.
*
* @param deviceName the name of the USB device containing the object
* @param objectHandle handle of the object to read
* @param objectSize the size of the object (this should match
* {@link android.mtp.MtpObjectInfo#getCompressedSize}
* @return the object's data, or null if reading fails
*/
public byte[] getObject(String deviceName, int objectHandle, int objectSize) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return null;
}
return device.getObject(objectHandle, objectSize);
}
/**
* Returns the thumbnail data for an object as a byte array.
*
* @param deviceName the name of the USB device containing the object
* @param objectHandle handle of the object to read
* @return the object's thumbnail, or null if reading fails
*/
public byte[] getThumbnail(String deviceName, int objectHandle) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return null;
}
return device.getThumbnail(objectHandle);
}
/**
* Copies the data for an object to a file in external storage.
*
* @param deviceName the name of the USB device containing the object
* @param objectHandle handle of the object to read
* @param destPath path to destination for the file transfer.
* This path should be in the external storage as defined by
* {@link android.os.Environment#getExternalStorageDirectory}
* @return true if the file transfer succeeds
*/
public boolean importFile(String deviceName, int objectHandle, String destPath) {
MtpDevice device = getDevice(deviceName);
if (device == null) {
return false;
}
return device.importFile(objectHandle, destPath);
}
}
|