BluetoothOppService.java revision 613bae227d65f61903e196944a9c718b4394f25a
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.google.android.collect.Lists; 36import javax.obex.ObexTransport; 37 38import android.app.Service; 39import android.bluetooth.BluetoothAdapter; 40import android.bluetooth.BluetoothDevice; 41import android.bluetooth.BluetoothIntent; 42import android.content.BroadcastReceiver; 43import android.content.ContentUris; 44import android.content.ContentValues; 45import android.content.Context; 46import android.content.Intent; 47import android.content.IntentFilter; 48import android.database.CharArrayBuffer; 49import android.database.ContentObserver; 50import android.database.Cursor; 51import android.media.MediaScannerConnection; 52import android.media.MediaScannerConnection.MediaScannerConnectionClient; 53import android.net.Uri; 54import android.os.Handler; 55import android.os.IBinder; 56import android.os.Message; 57import android.os.PowerManager; 58import android.util.Log; 59import android.os.Process; 60 61import java.io.FileNotFoundException; 62import java.io.IOException; 63import java.io.InputStream; 64import java.util.ArrayList; 65 66/** 67 * Performs the background Bluetooth OPP transfer. It also starts thread to 68 * accept incoming OPP connection. 69 */ 70 71public class BluetoothOppService extends Service { 72 private static final boolean D = Constants.DEBUG; 73 private static final boolean V = Constants.VERBOSE; 74 75 private boolean userAccepted = false; 76 77 private class BluetoothShareContentObserver extends ContentObserver { 78 79 public BluetoothShareContentObserver() { 80 super(new Handler()); 81 } 82 83 @Override 84 public void onChange(boolean selfChange) { 85 if (V) Log.v(TAG, "ContentObserver received notification"); 86 updateFromProvider(); 87 } 88 } 89 90 private static final String TAG = "BtOpp Service"; 91 92 /** Observer to get notified when the content observer's data changes */ 93 private BluetoothShareContentObserver mObserver; 94 95 /** Class to handle Notification Manager updates */ 96 private BluetoothOppNotification mNotifier; 97 98 private boolean mPendingUpdate; 99 100 private UpdateThread mUpdateThread; 101 102 private ArrayList<BluetoothOppShareInfo> mShares; 103 104 private ArrayList<BluetoothOppBatch> mBatchs; 105 106 private BluetoothOppTransfer mTransfer; 107 108 private BluetoothOppTransfer mServerTransfer; 109 110 private int mBatchId; 111 112 /** 113 * Array used when extracting strings from content provider 114 */ 115 private CharArrayBuffer mOldChars; 116 117 /** 118 * Array used when extracting strings from content provider 119 */ 120 private CharArrayBuffer mNewChars; 121 122 private BluetoothAdapter mAdapter; 123 124 private PowerManager mPowerManager; 125 126 private BluetoothOppRfcommListener mSocketListener; 127 128 private boolean mListenStarted = false; 129 130 private boolean mMediaScanInProgress; 131 132 private int mIncomingRetries = 0; 133 134 private ObexTransport mPendingConnection = null; 135 136 /* 137 * TODO No support for queue incoming from multiple devices. 138 * Make an array list of server session to support receiving queue from 139 * multiple devices 140 */ 141 private BluetoothOppObexServerSession mServerSession; 142 143 @Override 144 public IBinder onBind(Intent arg0) { 145 throw new UnsupportedOperationException("Cannot bind to Bluetooth OPP Service"); 146 } 147 148 @Override 149 public void onCreate() { 150 super.onCreate(); 151 if (V) Log.v(TAG, "Service onCreate"); 152 mAdapter = (BluetoothAdapter) getSystemService(Context.BLUETOOTH_SERVICE); 153 mSocketListener = new BluetoothOppRfcommListener(mAdapter); 154 mShares = Lists.newArrayList(); 155 mBatchs = Lists.newArrayList(); 156 mObserver = new BluetoothShareContentObserver(); 157 getContentResolver().registerContentObserver(BluetoothShare.CONTENT_URI, true, mObserver); 158 mBatchId = 1; 159 mNotifier = new BluetoothOppNotification(this); 160 mNotifier.mNotificationMgr.cancelAll(); 161 mNotifier.updateNotification(); 162 mNotifier.finishNotification(); 163 164 trimDatabase(); 165 166 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); 167 registerReceiver(mBluetoothReceiver, filter); 168 169 synchronized (BluetoothOppService.this) { 170 if (mAdapter == null) { 171 Log.w(TAG, "Local BT device is not enabled"); 172 } else { 173 startListenerDelayed(); 174 } 175 } 176 if (V) BluetoothOppPreference.getInstance(this).dump(); 177 updateFromProvider(); 178 } 179 180 @Override 181 public void onStart(Intent intent, int startId) { 182 super.onStart(intent, startId); 183 if (V) Log.v(TAG, "Service onStart"); 184 185 if (mAdapter == null) { 186 Log.w(TAG, "Local BT device is not enabled"); 187 } else { 188 startListenerDelayed(); 189 } 190 updateFromProvider(); 191 192 } 193 194 private void startListenerDelayed() { 195 if (!mListenStarted) { 196 if (mAdapter.isEnabled()) { 197 if (V) Log.v(TAG, "Starting RfcommListener in 9 seconds"); 198 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_LISTENER), 9000); 199 mListenStarted = true; 200 } 201 } 202 } 203 204 private static final int START_LISTENER = 1; 205 206 private static final int MEDIA_SCANNED = 2; 207 208 private static final int MEDIA_SCANNED_FAILED = 3; 209 210 private static final int MSG_INCOMING_CONNECTION_RETRY = 4; 211 212 private Handler mHandler = new Handler() { 213 @Override 214 public void handleMessage(Message msg) { 215 switch (msg.what) { 216 case START_LISTENER: 217 if (mAdapter.isEnabled()) { 218 startSocketListener(); 219 } 220 break; 221 case MEDIA_SCANNED: 222 if (V) Log.v(TAG, "Update mInfo.id " + msg.arg1 + " for data uri= " 223 + msg.obj.toString()); 224 ContentValues updateValues = new ContentValues(); 225 Uri contentUri = Uri.parse(BluetoothShare.CONTENT_URI + "/" + msg.arg1); 226 updateValues.put(Constants.MEDIA_SCANNED, Constants.MEDIA_SCANNED_SCANNED_OK); 227 updateValues.put(BluetoothShare.URI, msg.obj.toString()); // update 228 updateValues.put(BluetoothShare.MIMETYPE, getContentResolver().getType( 229 Uri.parse(msg.obj.toString()))); 230 getContentResolver().update(contentUri, updateValues, null, null); 231 synchronized (BluetoothOppService.this) { 232 mMediaScanInProgress = false; 233 } 234 break; 235 case MEDIA_SCANNED_FAILED: 236 Log.v(TAG, "Update mInfo.id " + msg.arg1 + " for MEDIA_SCANNED_FAILED"); 237 ContentValues updateValues1 = new ContentValues(); 238 Uri contentUri1 = Uri.parse(BluetoothShare.CONTENT_URI + "/" + msg.arg1); 239 updateValues1.put(Constants.MEDIA_SCANNED, 240 Constants.MEDIA_SCANNED_SCANNED_FAILED); 241 getContentResolver().update(contentUri1, updateValues1, null, null); 242 synchronized (BluetoothOppService.this) { 243 mMediaScanInProgress = false; 244 } 245 break; 246 case BluetoothOppRfcommListener.MSG_INCOMING_BTOPP_CONNECTION: 247 if (D) Log.d(TAG, "Get incoming connection"); 248 ObexTransport transport = (ObexTransport)msg.obj; 249 /* 250 * Strategy for incoming connections: 251 * 1. If there is no ongoing transfer, no on-hold connection, start it 252 * 2. If there is ongoing transfer, hold it for 20 seconds(1 seconds * 20 times) 253 * 3. If there is on-hold connection, reject directly 254 */ 255 if (mBatchs.size() == 0 && mPendingConnection == null) { 256 Log.i(TAG, "Start Obex Server"); 257 createServerSession(transport); 258 } else { 259 if (mPendingConnection != null) { 260 Log.w(TAG, "OPP busy! Reject connection"); 261 try { 262 transport.close(); 263 } catch (IOException e) { 264 Log.e(TAG, "close tranport error"); 265 } 266 } else if (Constants.USE_TCP_DEBUG && !Constants.USE_TCP_SIMPLE_SERVER){ 267 Log.i(TAG, "Start Obex Server in TCP DEBUG mode"); 268 createServerSession(transport); 269 } else { 270 Log.i(TAG, "OPP busy! Retry after 1 second"); 271 mIncomingRetries = mIncomingRetries + 1; 272 mPendingConnection = transport; 273 Message msg1 = Message.obtain(mHandler); 274 msg1.what = MSG_INCOMING_CONNECTION_RETRY; 275 mHandler.sendMessageDelayed(msg1, 1000); 276 } 277 } 278 break; 279 case MSG_INCOMING_CONNECTION_RETRY: 280 if (mBatchs.size() == 0) { 281 Log.i(TAG, "Start Obex Server"); 282 createServerSession(mPendingConnection); 283 mIncomingRetries = 0; 284 mPendingConnection = null; 285 } else { 286 if (mIncomingRetries == 20) { 287 Log.w(TAG, "Retried 20 seconds, reject connection"); 288 try { 289 mPendingConnection.close(); 290 } catch (IOException e) { 291 Log.e(TAG, "close tranport error"); 292 } 293 mIncomingRetries = 0; 294 mPendingConnection = null; 295 } else { 296 Log.i(TAG, "OPP busy! Retry after 1 second"); 297 mIncomingRetries = mIncomingRetries + 1; 298 Message msg2 = Message.obtain(mHandler); 299 msg2.what = MSG_INCOMING_CONNECTION_RETRY; 300 mHandler.sendMessageDelayed(msg2, 1000); 301 } 302 } 303 break; 304 } 305 } 306 }; 307 308 private void startSocketListener() { 309 310 if (V) Log.v(TAG, "start RfcommListener"); 311 mSocketListener.start(mHandler); 312 if (V) Log.v(TAG, "RfcommListener started"); 313 } 314 315 @Override 316 public void onDestroy() { 317 if (V) Log.v(TAG, "Service onDestroy"); 318 super.onDestroy(); 319 mNotifier.finishNotification(); 320 getContentResolver().unregisterContentObserver(mObserver); 321 unregisterReceiver(mBluetoothReceiver); 322 mSocketListener.stop(); 323 } 324 325 /* suppose we auto accept an incoming OPUSH connection */ 326 private void createServerSession(ObexTransport transport) { 327 mServerSession = new BluetoothOppObexServerSession(this, transport); 328 mServerSession.preStart(); 329 if (D) Log.d(TAG, "Get ServerSession " + mServerSession.toString() 330 + " for incoming connection" + transport.toString()); 331 } 332 333 private final BroadcastReceiver mBluetoothReceiver = new BroadcastReceiver() { 334 @Override 335 public void onReceive(Context context, Intent intent) { 336 String action = intent.getAction(); 337 338 if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { 339 switch (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR)) { 340 case BluetoothAdapter.STATE_ON: 341 if (V) Log.v(TAG, 342 "Receiver BLUETOOTH_STATE_CHANGED_ACTION, BLUETOOTH_STATE_ON"); 343 startSocketListener(); 344 break; 345 case BluetoothAdapter.STATE_TURNING_OFF: 346 if (V) Log.v(TAG, "Receiver DISABLED_ACTION "); 347 mSocketListener.stop(); 348 mListenStarted = false; 349 synchronized (BluetoothOppService.this) { 350 if (mUpdateThread == null) { 351 stopSelf(); 352 } 353 } 354 break; 355 } 356 } 357 } 358 }; 359 360 private void updateFromProvider() { 361 synchronized (BluetoothOppService.this) { 362 mPendingUpdate = true; 363 if (mUpdateThread == null) { 364 mUpdateThread = new UpdateThread(); 365 mUpdateThread.start(); 366 } 367 } 368 } 369 370 private class UpdateThread extends Thread { 371 public UpdateThread() { 372 super("Bluetooth Share Service"); 373 } 374 375 @Override 376 public void run() { 377 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 378 379 boolean keepService = false; 380 for (;;) { 381 synchronized (BluetoothOppService.this) { 382 if (mUpdateThread != this) { 383 throw new IllegalStateException( 384 "multiple UpdateThreads in BluetoothOppService"); 385 } 386 if (V) Log.v(TAG, "pendingUpdate is " + mPendingUpdate + " keepUpdateThread is " 387 + keepService + " sListenStarted is " + mListenStarted); 388 if (!mPendingUpdate) { 389 mUpdateThread = null; 390 if (!keepService && !mListenStarted) { 391 stopSelf(); 392 break; 393 } 394 mNotifier.updateNotification(); 395 mNotifier.finishNotification(); 396 return; 397 } 398 mPendingUpdate = false; 399 } 400 Cursor cursor = getContentResolver().query(BluetoothShare.CONTENT_URI, null, null, 401 null, BluetoothShare._ID); 402 403 if (cursor == null) { 404 return; 405 } 406 407 cursor.moveToFirst(); 408 409 int arrayPos = 0; 410 411 keepService = false; 412 boolean isAfterLast = cursor.isAfterLast(); 413 414 int idColumn = cursor.getColumnIndexOrThrow(BluetoothShare._ID); 415 /* 416 * Walk the cursor and the local array to keep them in sync. The 417 * key to the algorithm is that the ids are unique and sorted 418 * both in the cursor and in the array, so that they can be 419 * processed in order in both sources at the same time: at each 420 * step, both sources point to the lowest id that hasn't been 421 * processed from that source, and the algorithm processes the 422 * lowest id from those two possibilities. At each step: -If the 423 * array contains an entry that's not in the cursor, remove the 424 * entry, move to next entry in the array. -If the array 425 * contains an entry that's in the cursor, nothing to do, move 426 * to next cursor row and next array entry. -If the cursor 427 * contains an entry that's not in the array, insert a new entry 428 * in the array, move to next cursor row and next array entry. 429 */ 430 while (!isAfterLast || arrayPos < mShares.size()) { 431 if (isAfterLast) { 432 // We're beyond the end of the cursor but there's still 433 // some 434 // stuff in the local array, which can only be junk 435 if (V) Log.v(TAG, "Array update: trimming " + 436 mShares.get(arrayPos).mId + " @ " + arrayPos); 437 438 if (shouldScanFile(arrayPos)) { 439 scanFile(null, arrayPos); 440 } 441 deleteShare(arrayPos); // this advances in the array 442 } else { 443 int id = cursor.getInt(idColumn); 444 445 if (arrayPos == mShares.size()) { 446 insertShare(cursor, arrayPos); 447 if (V) Log.v(TAG, "Array update: inserting " + id + " @ " + arrayPos); 448 if (shouldScanFile(arrayPos) && (!scanFile(cursor, arrayPos))) { 449 keepService = true; 450 } 451 if (visibleNotification(arrayPos)) { 452 keepService = true; 453 } 454 if (needAction(arrayPos)) { 455 keepService = true; 456 } 457 458 ++arrayPos; 459 cursor.moveToNext(); 460 isAfterLast = cursor.isAfterLast(); 461 } else { 462 int arrayId = mShares.get(arrayPos).mId; 463 464 if (arrayId < id) { 465 if (V) Log.v(TAG, "Array update: removing " + arrayId + " @ " 466 + arrayPos); 467 if (shouldScanFile(arrayPos)) { 468 scanFile(null, arrayPos); 469 } 470 deleteShare(arrayPos); 471 } else if (arrayId == id) { 472 // This cursor row already exists in the stored 473 // array 474 updateShare(cursor, arrayPos, userAccepted); 475 if (shouldScanFile(arrayPos) && (!scanFile(cursor, arrayPos))) { 476 keepService = true; 477 } 478 if (visibleNotification(arrayPos)) { 479 keepService = true; 480 } 481 if (needAction(arrayPos)) { 482 keepService = true; 483 } 484 485 ++arrayPos; 486 cursor.moveToNext(); 487 isAfterLast = cursor.isAfterLast(); 488 } else { 489 // This cursor entry didn't exist in the stored 490 // array 491 if (V) Log.v(TAG, "Array update: appending " + id + " @ " + arrayPos); 492 insertShare(cursor, arrayPos); 493 494 if (shouldScanFile(arrayPos) && (!scanFile(cursor, arrayPos))) { 495 keepService = true; 496 } 497 if (visibleNotification(arrayPos)) { 498 keepService = true; 499 } 500 if (needAction(arrayPos)) { 501 keepService = true; 502 } 503 ++arrayPos; 504 cursor.moveToNext(); 505 isAfterLast = cursor.isAfterLast(); 506 } 507 } 508 } 509 } 510 511 mNotifier.updateNotification(); 512 513 cursor.close(); 514 } 515 } 516 517 } 518 519 private void insertShare(Cursor cursor, int arrayPos) { 520 BluetoothOppShareInfo info = new BluetoothOppShareInfo( 521 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare._ID)), 522 cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.URI)), 523 cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.FILENAME_HINT)), 524 cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare._DATA)), 525 cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.MIMETYPE)), 526 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.DIRECTION)), 527 cursor.getString(cursor.getColumnIndexOrThrow(BluetoothShare.DESTINATION)), 528 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.VISIBILITY)), 529 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION)), 530 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.STATUS)), 531 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.TOTAL_BYTES)), 532 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.CURRENT_BYTES)), 533 cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.TIMESTAMP)), 534 cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) != Constants.MEDIA_SCANNED_NOT_SCANNED); 535 536 if (V) { 537 Log.v(TAG, "Service adding new entry"); 538 Log.v(TAG, "ID : " + info.mId); 539 // Log.v(TAG, "URI : " + ((info.mUri != null) ? "yes" : "no")); 540 Log.v(TAG, "URI : " + info.mUri); 541 Log.v(TAG, "HINT : " + info.mHint); 542 Log.v(TAG, "FILENAME: " + info.mFilename); 543 Log.v(TAG, "MIMETYPE: " + info.mMimetype); 544 Log.v(TAG, "DIRECTION: " + info.mDirection); 545 Log.v(TAG, "DESTINAT: " + info.mDestination); 546 Log.v(TAG, "VISIBILI: " + info.mVisibility); 547 Log.v(TAG, "CONFIRM : " + info.mConfirm); 548 Log.v(TAG, "STATUS : " + info.mStatus); 549 Log.v(TAG, "TOTAL : " + info.mTotalBytes); 550 Log.v(TAG, "CURRENT : " + info.mCurrentBytes); 551 Log.v(TAG, "TIMESTAMP : " + info.mTimestamp); 552 Log.v(TAG, "SCANNED : " + info.mMediaScanned); 553 } 554 555 mShares.add(arrayPos, info); 556 557 /* Mark the info as failed if it's in invalid status */ 558 if (info.isObsolete()) { 559 Constants.updateShareStatus(this, info.mId, BluetoothShare.STATUS_UNKNOWN_ERROR); 560 } 561 /* 562 * Add info into a batch. The logic is 563 * 1) Only add valid and readyToStart info 564 * 2) If there is no batch, create a batch and insert this transfer into batch, 565 * then run the batch 566 * 3) If there is existing batch and timestamp match, insert transfer into batch 567 * 4) If there is existing batch and timestamp does not match, create a new batch and 568 * put in queue 569 */ 570 571 if (info.isReadyToStart()) { 572 if (info.mDirection == BluetoothShare.DIRECTION_OUTBOUND) { 573 /* check if the file exists */ 574 try { 575 InputStream i = getContentResolver().openInputStream(Uri.parse(info.mUri)); 576 i.close(); 577 } catch (FileNotFoundException e) { 578 Log.e(TAG, "Can't open file for OUTBOUND info " + info.mId); 579 Constants.updateShareStatus(this, info.mId, BluetoothShare.STATUS_BAD_REQUEST); 580 return; 581 } catch (IOException ex) { 582 Log.e(TAG, "IO error when close file for OUTBOUND info " + info.mId); 583 return; 584 } 585 } 586 if (mBatchs.size() == 0) { 587 BluetoothOppBatch newBatch = new BluetoothOppBatch(this, info); 588 newBatch.mId = mBatchId; 589 mBatchId++; 590 mBatchs.add(newBatch); 591 if (info.mDirection == BluetoothShare.DIRECTION_OUTBOUND) { 592 if (V) Log.v(TAG, "Service create new Batch " + newBatch.mId 593 + " for OUTBOUND info " + info.mId); 594 mTransfer = new BluetoothOppTransfer(this, mPowerManager, newBatch); 595 } else if (info.mDirection == BluetoothShare.DIRECTION_INBOUND) { 596 if (V) Log.v(TAG, "Service create new Batch " + newBatch.mId 597 + " for INBOUND info " + info.mId); 598 mServerTransfer = new BluetoothOppTransfer(this, mPowerManager, newBatch, 599 mServerSession); 600 } 601 602 if (info.mDirection == BluetoothShare.DIRECTION_OUTBOUND && mTransfer != null) { 603 if (V) Log.v(TAG, "Service start transfer new Batch " + newBatch.mId 604 + " for info " + info.mId); 605 mTransfer.start(); 606 } else if (info.mDirection == BluetoothShare.DIRECTION_INBOUND 607 && mServerTransfer != null) { 608 if (V) Log.v(TAG, "Service start server transfer new Batch " + newBatch.mId 609 + " for info " + info.mId); 610 mServerTransfer.start(); 611 } 612 613 } else { 614 int i = findBatchWithTimeStamp(info.mTimestamp); 615 if (i != -1) { 616 if (V) Log.v(TAG, "Service add info " + info.mId + " to existing batch " 617 + mBatchs.get(i).mId); 618 mBatchs.get(i).addShare(info); 619 } else { 620 // There is ongoing batch 621 BluetoothOppBatch newBatch = new BluetoothOppBatch(this, info); 622 newBatch.mId = mBatchId; 623 mBatchId++; 624 mBatchs.add(newBatch); 625 if (V) Log.v(TAG, "Service add new Batch " + newBatch.mId + " for info " + 626 info.mId); 627 if (Constants.USE_TCP_DEBUG && !Constants.USE_TCP_SIMPLE_SERVER) { 628 // only allow concurrent serverTransfer in debug mode 629 if (info.mDirection == BluetoothShare.DIRECTION_INBOUND) { 630 if (V) Log.v(TAG, "TCP_DEBUG start server transfer new Batch " + 631 newBatch.mId + " for info " + info.mId); 632 mServerTransfer = new BluetoothOppTransfer(this, mPowerManager, 633 newBatch, mServerSession); 634 mServerTransfer.start(); 635 } 636 } 637 } 638 } 639 } 640 } 641 642 private void updateShare(Cursor cursor, int arrayPos, boolean userAccepted) { 643 BluetoothOppShareInfo info = mShares.get(arrayPos); 644 int statusColumn = cursor.getColumnIndexOrThrow(BluetoothShare.STATUS); 645 646 info.mId = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare._ID)); 647 info.mUri = stringFromCursor(info.mUri, cursor, BluetoothShare.URI); 648 info.mHint = stringFromCursor(info.mHint, cursor, BluetoothShare.FILENAME_HINT); 649 info.mFilename = stringFromCursor(info.mFilename, cursor, BluetoothShare._DATA); 650 info.mMimetype = stringFromCursor(info.mMimetype, cursor, BluetoothShare.MIMETYPE); 651 info.mDirection = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.DIRECTION)); 652 info.mDestination = stringFromCursor(info.mDestination, cursor, BluetoothShare.DESTINATION); 653 int newVisibility = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.VISIBILITY)); 654 655 boolean confirmed = false; 656 int newConfirm = cursor.getInt(cursor 657 .getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION)); 658 659 if (info.mVisibility == BluetoothShare.VISIBILITY_VISIBLE 660 && newVisibility != BluetoothShare.VISIBILITY_VISIBLE 661 && (BluetoothShare.isStatusCompleted(info.mStatus) || newConfirm == BluetoothShare.USER_CONFIRMATION_PENDING)) { 662 mNotifier.mNotificationMgr.cancel(info.mId); 663 } 664 665 info.mVisibility = newVisibility; 666 667 if (info.mConfirm == BluetoothShare.USER_CONFIRMATION_PENDING 668 && newConfirm != BluetoothShare.USER_CONFIRMATION_PENDING) { 669 confirmed = true; 670 } 671 info.mConfirm = cursor.getInt(cursor 672 .getColumnIndexOrThrow(BluetoothShare.USER_CONFIRMATION)); 673 int newStatus = cursor.getInt(statusColumn); 674 675 if (!BluetoothShare.isStatusCompleted(info.mStatus) 676 && BluetoothShare.isStatusCompleted(newStatus)) { 677 mNotifier.mNotificationMgr.cancel(info.mId); 678 } 679 680 info.mStatus = newStatus; 681 info.mTotalBytes = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.TOTAL_BYTES)); 682 info.mCurrentBytes = cursor.getInt(cursor 683 .getColumnIndexOrThrow(BluetoothShare.CURRENT_BYTES)); 684 info.mTimestamp = cursor.getInt(cursor.getColumnIndexOrThrow(BluetoothShare.TIMESTAMP)); 685 info.mMediaScanned = (cursor.getInt(cursor.getColumnIndexOrThrow(Constants.MEDIA_SCANNED)) != Constants.MEDIA_SCANNED_NOT_SCANNED); 686 687 if (confirmed) { 688 if (V) Log.v(TAG, "Service handle info " + info.mId + " confirmed"); 689 /* Inbounds transfer get user confirmation, so we start it */ 690 int i = findBatchWithTimeStamp(info.mTimestamp); 691 BluetoothOppBatch batch = mBatchs.get(i); 692 if (batch.mId == mServerTransfer.getBatchId()) { 693 mServerTransfer.setConfirmed(); 694 } //TODO need to think about else 695 } 696 int i = findBatchWithTimeStamp(info.mTimestamp); 697 if (i != -1) { 698 BluetoothOppBatch batch = mBatchs.get(i); 699 if (batch.mStatus == Constants.BATCH_STATUS_FINISHED 700 || batch.mStatus == Constants.BATCH_STATUS_FAILED) { 701 if (V) Log.v(TAG, "Batch " + batch.mId + " is finished"); 702 if (batch.mDirection == BluetoothShare.DIRECTION_OUTBOUND) { 703 if (mTransfer == null) { 704 Log.e(TAG, "Unexpected error! mTransfer is null"); 705 } else if (batch.mId == mTransfer.getBatchId()) { 706 mTransfer.stop(); 707 } else { 708 Log.e(TAG, "Unexpected error! batch id " + batch.mId 709 + " doesn't match mTransfer id " + mTransfer.getBatchId()); 710 } 711 } else { 712 if (mServerTransfer == null) { 713 Log.e(TAG, "Unexpected error! mServerTransfer is null"); 714 } else if (batch.mId == mServerTransfer.getBatchId()) { 715 mServerTransfer.stop(); 716 } else { 717 Log.e(TAG, "Unexpected error! batch id " + batch.mId 718 + " doesn't match mServerTransfer id " 719 + mServerTransfer.getBatchId()); 720 } 721 } 722 removeBatch(batch); 723 } 724 } 725 } 726 727 /** 728 * Removes the local copy of the info about a share. 729 */ 730 private void deleteShare(int arrayPos) { 731 BluetoothOppShareInfo info = mShares.get(arrayPos); 732 733 /* 734 * Delete arrayPos from a batch. The logic is 735 * 1) Search existing batch for the info 736 * 2) cancel the batch 737 * 3) If the batch become empty delete the batch 738 */ 739 int i = findBatchWithTimeStamp(info.mTimestamp); 740 if (i != -1) { 741 BluetoothOppBatch batch = mBatchs.get(i); 742 if (batch.hasShare(info)) { 743 if (V) Log.v(TAG, "Service cancel batch for share " + info.mId); 744 batch.cancelBatch(); 745 } 746 if (batch.isEmpty()) { 747 if (V) Log.v(TAG, "Service remove batch " + batch.mId); 748 removeBatch(batch); 749 } 750 } 751 mShares.remove(arrayPos); 752 } 753 754 private String stringFromCursor(String old, Cursor cursor, String column) { 755 int index = cursor.getColumnIndexOrThrow(column); 756 if (old == null) { 757 return cursor.getString(index); 758 } 759 if (mNewChars == null) { 760 mNewChars = new CharArrayBuffer(128); 761 } 762 cursor.copyStringToBuffer(index, mNewChars); 763 int length = mNewChars.sizeCopied; 764 if (length != old.length()) { 765 return cursor.getString(index); 766 } 767 if (mOldChars == null || mOldChars.sizeCopied < length) { 768 mOldChars = new CharArrayBuffer(length); 769 } 770 char[] oldArray = mOldChars.data; 771 char[] newArray = mNewChars.data; 772 old.getChars(0, length, oldArray, 0); 773 for (int i = length - 1; i >= 0; --i) { 774 if (oldArray[i] != newArray[i]) { 775 return new String(newArray, 0, length); 776 } 777 } 778 return old; 779 } 780 781 private int findBatchWithTimeStamp(long timestamp) { 782 for (int i = mBatchs.size() - 1; i >= 0; i--) { 783 if (mBatchs.get(i).mTimestamp == timestamp) { 784 return i; 785 } 786 } 787 return -1; 788 } 789 790 private void removeBatch(BluetoothOppBatch batch) { 791 if (V) Log.v(TAG, "Remove batch " + batch.mId); 792 mBatchs.remove(batch); 793 if (mBatchs.size() > 0) { 794 for (int i = 0; i < mBatchs.size(); i++) { 795 // we have a running batch 796 if (mBatchs.get(i).mStatus == Constants.BATCH_STATUS_RUNNING) { 797 return; 798 } else { 799 // Pending batch for inbound transfer is not supported 800 // just finish a transfer, start pending outbound transfer 801 if (mBatchs.get(i).mDirection == BluetoothShare.DIRECTION_OUTBOUND) { 802 if (V) Log.v(TAG, "Start pending outbound batch " + mBatchs.get(i).mId); 803 mTransfer = new BluetoothOppTransfer(this, mPowerManager, mBatchs.get(i)); 804 mTransfer.start(); 805 return; 806 } else { 807 // have pending inbound transfer, should not happen 808 Log.e(TAG, "Should not happen"); 809 } 810 } 811 } 812 } 813 } 814 815 private boolean needAction(int arrayPos) { 816 BluetoothOppShareInfo info = mShares.get(arrayPos); 817 if (BluetoothShare.isStatusCompleted(info.mStatus)) { 818 return false; 819 } 820 return true; 821 } 822 823 private boolean visibleNotification(int arrayPos) { 824 BluetoothOppShareInfo info = mShares.get(arrayPos); 825 return info.hasCompletionNotification(); 826 } 827 828 private boolean scanFile(Cursor cursor, int arrayPos) { 829 BluetoothOppShareInfo info = mShares.get(arrayPos); 830 synchronized (BluetoothOppService.this) { 831 if (D) Log.d(TAG, "Scanning file " + info.mFilename); 832 if (!mMediaScanInProgress) { 833 mMediaScanInProgress = true; 834 new MediaScannerNotifier(this, info, mHandler); 835 return true; 836 } else { 837 return false; 838 } 839 } 840 } 841 842 private boolean shouldScanFile(int arrayPos) { 843 BluetoothOppShareInfo info = mShares.get(arrayPos); 844 return BluetoothShare.isStatusSuccess(info.mStatus) 845 && info.mDirection == BluetoothShare.DIRECTION_INBOUND && !info.mMediaScanned; 846 } 847 848 private void trimDatabase() { 849 Cursor cursor = getContentResolver().query(BluetoothShare.CONTENT_URI, new String[] { 850 BluetoothShare._ID 851 }, BluetoothShare.STATUS + " >= '200'", null, BluetoothShare._ID); 852 if (cursor == null) { 853 // This isn't good - if we can't do basic queries in our database, 854 // nothing's gonna work 855 Log.e(TAG, "null cursor in trimDatabase"); 856 return; 857 } 858 if (cursor.moveToFirst()) { 859 int numDelete = cursor.getCount() - Constants.MAX_RECORDS_IN_DATABASE; 860 int columnId = cursor.getColumnIndexOrThrow(BluetoothShare._ID); 861 while (numDelete > 0) { 862 getContentResolver().delete( 863 ContentUris.withAppendedId(BluetoothShare.CONTENT_URI, cursor 864 .getLong(columnId)), null, null); 865 if (!cursor.moveToNext()) { 866 break; 867 } 868 numDelete--; 869 } 870 } 871 cursor.close(); 872 } 873 874 private static class MediaScannerNotifier implements MediaScannerConnectionClient { 875 876 private MediaScannerConnection mConnection; 877 878 private BluetoothOppShareInfo mInfo; 879 880 private Context mContext; 881 882 private Handler mCallback; 883 884 public MediaScannerNotifier(Context context, BluetoothOppShareInfo info, Handler handler) { 885 mContext = context; 886 mInfo = info; 887 mCallback = handler; 888 mConnection = new MediaScannerConnection(mContext, this); 889 if (V) Log.v(TAG, "Connecting to MediaScannerConnection "); 890 mConnection.connect(); 891 } 892 893 public void onMediaScannerConnected() { 894 if (V) Log.v(TAG, "MediaScannerConnection onMediaScannerConnected"); 895 mConnection.scanFile(mInfo.mFilename, mInfo.mMimetype); 896 } 897 898 public void onScanCompleted(String path, Uri uri) { 899 try { 900 if (V) { 901 Log.v(TAG, "MediaScannerConnection onScanCompleted"); 902 Log.v(TAG, "MediaScannerConnection path is " + path); 903 Log.v(TAG, "MediaScannerConnection Uri is " + uri); 904 } 905 if (uri != null) { 906 Message msg = Message.obtain(); 907 msg.setTarget(mCallback); 908 msg.what = MEDIA_SCANNED; 909 msg.arg1 = mInfo.mId; 910 msg.obj = uri; 911 msg.sendToTarget(); 912 } else { 913 Message msg = Message.obtain(); 914 msg.setTarget(mCallback); 915 msg.what = MEDIA_SCANNED_FAILED; 916 msg.arg1 = mInfo.mId; 917 msg.sendToTarget(); 918 } 919 } catch (Exception ex) { 920 Log.v(TAG, "!!!MediaScannerConnection exception: " + ex); 921 } finally { 922 if (V) Log.v(TAG, "MediaScannerConnection disconnect"); 923 mConnection.disconnect(); 924 } 925 } 926 } 927} 928