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 17 package com.android.mtp; 18 19 import android.app.ActivityManager; 20 import android.content.BroadcastReceiver; 21 import android.content.Context; 22 import android.content.Intent; 23 import android.content.IntentFilter; 24 import android.hardware.usb.UsbManager; 25 import android.os.Bundle; 26 import android.os.UserHandle; 27 import android.util.Log; 28 29 public class MtpReceiver extends BroadcastReceiver { 30 private static final String TAG = MtpReceiver.class.getSimpleName(); 31 private static final boolean DEBUG = false; 32 33 @Override onReceive(Context context, Intent intent)34 public void onReceive(Context context, Intent intent) { 35 final String action = intent.getAction(); 36 if (Intent.ACTION_BOOT_COMPLETED.equals(action)) { 37 final Intent usbState = context.registerReceiver( 38 null, new IntentFilter(UsbManager.ACTION_USB_STATE)); 39 if (usbState != null) { 40 handleUsbState(context, usbState); 41 } 42 } else if (UsbManager.ACTION_USB_STATE.equals(action)) { 43 handleUsbState(context, intent); 44 } 45 } 46 handleUsbState(Context context, Intent intent)47 private void handleUsbState(Context context, Intent intent) { 48 Bundle extras = intent.getExtras(); 49 boolean configured = extras.getBoolean(UsbManager.USB_CONFIGURED); 50 boolean connected = extras.getBoolean(UsbManager.USB_CONNECTED); 51 boolean mtpEnabled = extras.getBoolean(UsbManager.USB_FUNCTION_MTP); 52 boolean ptpEnabled = extras.getBoolean(UsbManager.USB_FUNCTION_PTP); 53 boolean unlocked = extras.getBoolean(UsbManager.USB_DATA_UNLOCKED); 54 boolean isCurrentUser = UserHandle.myUserId() == ActivityManager.getCurrentUser(); 55 56 if (configured && (mtpEnabled || ptpEnabled)) { 57 if (!isCurrentUser) 58 return; 59 intent = new Intent(context, MtpService.class); 60 intent.putExtra(UsbManager.USB_DATA_UNLOCKED, unlocked); 61 if (ptpEnabled) { 62 intent.putExtra(UsbManager.USB_FUNCTION_PTP, true); 63 } 64 if (DEBUG) { Log.d(TAG, "handleUsbState startService"); } 65 context.startService(intent); 66 } else if (!connected || !(mtpEnabled || ptpEnabled)) { 67 // Only unbind if disconnected or disabled. 68 boolean status = context.stopService(new Intent(context, MtpService.class)); 69 if (DEBUG) { Log.d(TAG, "handleUsbState stopService status=" + status); } 70 } 71 } 72 } 73