@Override
  public void onCreate() {
    Log.d(TAG, "onCreate");
    super.onCreate();
    // register broadcast
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_PACKAGE_ADDED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addDataScheme("package");

    IntentFilter filter2 = new IntentFilter(DreamConstant.SEND_FILE_ACTION);

    registerReceiver(transferReceiver, filter);
    registerReceiver(transferReceiver, filter2);

    mNotice = new Notice(this);
    mFileInfoManager = new FileInfoManager(this);
    mHistoryManager = new HistoryManager(this);
    mSocketMgr = SocketCommunicationManager.getInstance(this);
    mAppId = AppUtil.getAppID(this);
    Log.d(TAG, "mappid=" + mAppId);
    mSocketMgr.registerOnFileTransportListener(this, mAppId);

    mUserManager = UserManager.getInstance();
    pm = getPackageManager();
  }
 public void sendFile(File file, List<User> list) {
   Log.d(TAG, "sendFile.name:" + file.getName());
   for (int i = 0; i < list.size(); i++) {
     User receiverUser = list.get(i);
     Log.d(TAG, "receiverUser[" + i + "]=" + receiverUser.getUserName());
     SendFileThread sendFileThread = new SendFileThread(file, receiverUser);
     mSendQueue.offer(sendFileThread);
   }
 }
  @Override
  public void onReceiveFile(FileReceiver fileReceiver) {
    String fileName = fileReceiver.getFileTransferInfo().getFileName();
    String sendUserName = fileReceiver.getSendUser().getUserName();
    File file = null;
    long fileSize = fileReceiver.getFileTransferInfo().getFileSize();
    Log.d(TAG, "onReceiveFile:" + fileName + "," + sendUserName + ",size=" + fileSize);
    // define a file to save the receive file
    File fileDir = new File(DreamConstant.DREAMLINK_FOLDER);
    if (!fileDir.exists()) {
      fileDir.mkdirs();
    }

    String filePath = DreamConstant.DREAMLINK_FOLDER + File.separator + fileName;
    file = new File(filePath);
    if (!file.exists()) {
      try {
        file.createNewFile();
      } catch (IOException e) {
        Log.e(TAG, "create file error:" + e.toString());
        mNotice.showToast("can not create the file:" + fileName);
        return;
      }
    } else {
      // if file is exist,auto rename
      fileName = FileInfoManager.autoRename(fileName);
      while (new File(DreamConstant.DREAMLINK_FOLDER + File.separator + fileName).exists()) {
        fileName = FileInfoManager.autoRename(fileName);
      }
      filePath = DreamConstant.DREAMLINK_FOLDER + File.separator + fileName;
      file = new File(filePath);
    }

    HistoryInfo historyInfo = new HistoryInfo();
    historyInfo.setFile(file);
    historyInfo.setFileSize(fileSize);
    historyInfo.setSendUserName(sendUserName);
    historyInfo.setReceiveUser(mUserManager.getLocalUser());
    historyInfo.setMsgType(HistoryManager.TYPE_RECEIVE);
    historyInfo.setDate(System.currentTimeMillis());
    historyInfo.setStatus(HistoryManager.STATUS_PRE_RECEIVE);
    historyInfo = mFileInfoManager.getHistoryInfo(historyInfo);

    ContentValues values = mHistoryManager.getInsertValues(historyInfo);
    Uri uri = getContentResolver().insert(MetaData.History.CONTENT_URI, values);
    Object key = new Object();
    mTransferMap.put(key, uri);
    Log.d(TAG, "onReceiveFile.mTransferMap.size=" + mTransferMap.size());

    fileReceiver.receiveFile(file, FileTransferService.this, key);
  }
 @Override
 public void onResume() {
   super.onResume();
   Log.d(TAG, "onResume");
   mFragmentActivity.addObject(MainFragmentActivity.ZY_TIANDI, (BaseFragment) this);
   mFragmentActivity.setTitleName(MainFragmentActivity.ZY_TIANDI);
 }
 private void unbindService(ServiceConnection connection) {
   try {
     mContext.unbindService(connection);
   } catch (Exception e) {
     Log.e(TAG, "unbindServer error. " + e);
   }
   connection = null;
 }
 public void connenctToServer(ServerInfo info) {
   Log.d(TAG, "connenctToServer");
   if (info.getServerType().equals("wifi-direct")) {
     if (mDirectService != null) mDirectService.connectToServer(info);
   } else if (info.getServerType().equals("wifi") || info.getServerType().equals("wifi-ap")) {
     if (mWifiOrAPService != null) mWifiOrAPService.connectToServer(info);
   }
 }
  @Override
  public void onDestroy() {
    Log.d(TAG, "onDestroy");
    super.onDestroy();
    mSocketMgr.unregisterOnFileTransportListener(this);
    unregisterReceiver(transferReceiver);

    mSendingFileThreadMap.clear();
    mSendQueue.clear();
  }
  /** get images form {@link MediaStore.Images.Media.EXTERNAL_CONTENT_URI} */
  public List<ImageInfo> getImageInfo() {
    Log.d(TAG, "getImageInfo.start:" + System.currentTimeMillis());
    List<ImageInfo> imageInfos = new ArrayList<ImageInfo>();
    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor =
        contentResolver.query(
            DreamConstant.IMAGE_URI, null, null, null, MediaStore.MediaColumns.DATE_MODIFIED);

    if (null == cursor) {

    } else {
      if (cursor.moveToFirst()) {
        ImageInfo imageInfo = null;
        do {
          long id = cursor.getLong(cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID));
          String path = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
          // 图片所在文件夹名
          String folder =
              cursor.getString(
                  cursor.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME));
          long width = 0;
          long height = 0;
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            width = cursor.getLong(cursor.getColumnIndex("width"));
            height = cursor.getLong(cursor.getColumnIndex("height"));
          }
          if (new File(path).exists()) {
            imageInfo = new ImageInfo(id);
            imageInfo.setPath(path);
            imageInfo.setBucketDisplayName(folder);
            imageInfo.setWidth(width);
            imageInfo.setHeight(height);

            imageInfos.add(imageInfo);
          }

        } while (cursor.moveToNext());
      }
      cursor.close();
    }
    Log.d(TAG, "getImageInfo.end:" + System.currentTimeMillis());
    return imageInfos;
  }
 @Override
 protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
   // super.onQueryComplete(token, cookie, cursor);
   mLoadingBar.setVisibility(View.INVISIBLE);
   if (null != cursor && cursor.getCount() > 0) {
     mCursor = cursor;
     Log.d(TAG, "onQueryComplete.count=" + cursor.getCount());
     mAdapter = new AppCursorAdapter(mContext);
     mAdapter.changeCursor(cursor);
     mGridView.setAdapter(mAdapter);
   }
 }
 /**
  * create server
  *
  * @param type just like: "wifi", "wifi-ap", "wifi-direct" case insensitive
  * @param searchListener {@link OnSearchListener}
  */
 public void createServer(String type, OnSearchListener searchListener) {
   if (type == null) {
     // default ap server
     type = SERVER_TYPE_WIFI_AP;
   }
   if (type.equals(SERVER_TYPE_WIFI)) {
     startWifiServer(searchListener);
   } else if (type.equals(SERVER_TYPE_WIFI_AP)) {
     startWifiAPserver(searchListener);
   } else if (type.equals(SERVER_TYPE_WIFI_DIRECT)) {
     startWifiDirectServer(null, searchListener);
   } else {
     Log.e(TAG, "Unknow type!");
   }
 }
  @Override
  public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    mCursor.moveToPosition(position);
    String packagename = mCursor.getString(mCursor.getColumnIndex(AppData.App.PKG_NAME));
    ApplicationInfo applicationInfo = null;
    AppInfo appInfo = null;
    try {
      applicationInfo = pm.getApplicationInfo(packagename, 0);
      appInfo = new AppInfo(getActivity(), applicationInfo);
      appInfo.setPackageName(packagename);
      appInfo.setAppIcon(applicationInfo.loadIcon(pm));
      appInfo.loadLabel();
      appInfo.loadVersion();

      showMenuDialog(appInfo, arg1);
    } catch (NameNotFoundException e) {
      Log.e(TAG, e.toString());
      e.printStackTrace();
    }
    return true;
  }
        @Override
        public void onReceive(Context context, Intent intent) {
          String action = intent.getAction();
          Log.i(TAG, "action = " + action);
          if (DreamConstant.SEND_FILE_ACTION.equals(action)) {
            handleSendFileRequest(intent);
          } else if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
            AppManager appManager = new AppManager(FileTransferService.this);
            // get install or uninstall app package name
            String packageName = intent.getData().getSchemeSpecificPart();

            // get installed app
            AppInfo appInfo = null;
            try {
              ApplicationInfo info = pm.getApplicationInfo(packageName, 0);
              appInfo = new AppInfo(FileTransferService.this, info);
              appInfo.setPackageName(packageName);
              appInfo.setAppIcon(info.loadIcon(pm));
              appInfo.loadLabel();
              appInfo.loadVersion();
              if (appManager.isMyApp(packageName)) {
                appInfo.setType(AppManager.ZHAOYAN_APP);
              } else if (appManager.isGameApp(packageName)) {
                appInfo.setType(AppManager.GAME_APP);
              } else {
                appInfo.setType(AppManager.NORMAL_APP);
              }
              ContentValues values = appManager.getValuesByAppInfo(appInfo);
              getContentResolver().insert(AppData.App.CONTENT_URI, values);
            } catch (NameNotFoundException e) {
              e.printStackTrace();
            }

          } else if (Intent.ACTION_PACKAGE_REMOVED.equals(action)) {
            // get install or uninstall app package name
            String packageName = intent.getData().getSchemeSpecificPart();
            Uri uri = Uri.parse(AppData.App.CONTENT_URI + "/" + packageName);
            getContentResolver().delete(uri, null, null);
          }
        }
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   Log.d(TAG, "FileTransferService.onStartCommand()");
   return super.onStartCommand(intent, flags, startId);
 }