1/* 2 * Copyright (C) 2010 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 17package com.android.providers.media; 18 19import android.content.BroadcastReceiver; 20import android.content.Context; 21import android.content.Intent; 22import android.content.IntentFilter; 23import android.hardware.usb.UsbManager; 24import android.net.Uri; 25import android.os.Bundle; 26 27public class MtpReceiver extends BroadcastReceiver { 28 private final static String TAG = "UsbReceiver"; 29 30 @Override 31 public void onReceive(Context context, Intent intent) { 32 final String action = intent.getAction(); 33 if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { 34 final Intent usbState = context.registerReceiver( 35 null, new IntentFilter(UsbManager.ACTION_USB_STATE)); 36 if (usbState != null) { 37 handleUsbState(context, usbState); 38 } 39 } else if (UsbManager.ACTION_USB_STATE.equals(action)) { 40 handleUsbState(context, intent); 41 } 42 } 43 44 private void handleUsbState(Context context, Intent intent) { 45 Bundle extras = intent.getExtras(); 46 boolean connected = extras.getBoolean(UsbManager.USB_CONFIGURED); 47 boolean mtpEnabled = extras.getBoolean(UsbManager.USB_FUNCTION_MTP); 48 boolean ptpEnabled = extras.getBoolean(UsbManager.USB_FUNCTION_PTP); 49 // Start MTP service if USB is connected and either the MTP or PTP function is enabled 50 if (connected && (mtpEnabled || ptpEnabled)) { 51 intent = new Intent(context, MtpService.class); 52 if (ptpEnabled) { 53 intent.putExtra(UsbManager.USB_FUNCTION_PTP, true); 54 } 55 context.startService(intent); 56 // tell MediaProvider MTP is connected so it can bind to the service 57 context.getContentResolver().insert(Uri.parse( 58 "content://media/none/mtp_connected"), null); 59 } else { 60 context.stopService(new Intent(context, MtpService.class)); 61 // tell MediaProvider MTP is disconnected so it can unbind from the service 62 context.getContentResolver().delete(Uri.parse( 63 "content://media/none/mtp_connected"), null, null); 64 } 65 } 66} 67