/**
  * 避免壁纸很小出现黑屏的情况发生
  *
  * @param wallPaper
  * @return
  */
 private BitmapDrawable preventBlackScreen(Drawable wallPaper) {
   Resources resources = GOLauncherApp.getContext().getResources();
   int screenW = resources.getDisplayMetrics().widthPixels;
   int screenH = resources.getDisplayMetrics().heightPixels;
   if (resources.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
     if (screenW > screenH) {
       int temp = screenW;
       screenW = screenH;
       screenH = temp;
     }
   } else {
     if (screenW < screenH) {
       int temp = screenW;
       screenW = screenH;
       screenH = temp;
     }
   }
   boolean isWallpaperScroll =
       GOLauncherApp.getSettingControler().getScreenSettingInfo().mWallpaperScroll;
   final int screenSpan =
       isWallpaperScroll
           ? WallpaperDensityUtil.WALLPAPER_SCREENS_SPAN_WIDTH_2
           : WallpaperDensityUtil.WALLPAPER_SCREENS_SPAN_WIDTH_1;
   BitmapDrawable newWallDrawable =
       WindowControl.prepareWallpaper(
           (BitmapDrawable) wallPaper, screenW * screenSpan, screenH, resources);
   return newWallDrawable;
 }
 /**
  * 打开APK文件进行安装的方法
  *
  * @param file
  */
 private void openFile(final String filepath) {
   File file = new File(filepath);
   if (!file.exists()) {
     return;
   }
   String[] token = file.getName().split("\\.");
   String pf = token[token.length - 1];
   if (!pf.equals("apk")) {
     return;
   }
   //		// DefaultDownloadListener是通过ClassName在DownloadService的进程实例化的对象
   //		// 所以这里可以直接取得下载控制接口
   //		IDownloadService mDownloadController = IDownloadService.Stub.asInterface(DownloadService
   //				.getContext().getBinder());
   //		try {
   //			if (mDownloadController != null) {
   //				mDownloadController.addInstallPath(filepath);
   //			}
   //		} catch (RemoteException e) {
   //			// TODO Auto-generated catch block
   //			e.printStackTrace();
   //		}
   InstallManager mInstallManager = InstallManager.getInstance(GOLauncherApp.getContext());
   if (filepath != null) {
     mInstallManager.addPkgToArray(filepath);
   }
 }
 /** 终止服务 */
 public static void stopService(/* Context context */ ) {
   if (true) {
     Context context = GOLauncherApp.getContext();
     Intent i = new Intent(context, FloatWindowsService.class);
     context.stopService(i);
   }
 }
 /** 启动服务 */
 public static void beginService(/* Context context */ ) {
   if (true) {
     Log.v("TestSpeed", "FloatWindowsService beginService 1");
     Context context = GOLauncherApp.getContext();
     Intent i = new Intent(context, FloatWindowsService.class);
     context.startService(i);
   }
 }
 public static AppFuncUtils getInstance(Context context) {
   if (context == null) {
     context = GOLauncherApp.getContext();
   }
   if (sInstance == null) {
     sInstance = new AppFuncUtils(context);
   }
   return sInstance;
 }
  private void initMemory() {
    try {
      Context context = GOLauncherApp.getContext();
      mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
      mPid = new int[] {android.os.Process.myPid()};

      Class<?> activityClass = Class.forName("android.app.ActivityManager");
      mMethod = activityClass.getDeclaredMethod("getProcessMemoryInfo", int[].class);

    } catch (Exception e) {
    }
  }
 // 设置超级主题的壁纸
 private void setSuperThemeWallpaper(Context context, String resName) {
   try {
     ThemeInfoBean infoBean = ThemeManager.getInstance(context).getCurThemeInfoBean();
     if (infoBean != null) {
       final String pgkName = infoBean.getPackageName();
       Resources resources =
           GOLauncherApp.getContext().getPackageManager().getResourcesForApplication(pgkName);
       final int resId = resources.getIdentifier(resName, "drawable", pgkName);
       setWallpaperInBackground(context, resources, resId);
     }
   } catch (Exception e) {
     // e.printStackTrace();
   }
 } // end setSuperThemeWallpaper
  @Override
  public void onCreate() {
    super.onCreate();
    mContext = GOLauncherApp.getContext();
    initView();
    initMemory();

    HandlerThread thread = new HandlerThread(TAG, Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
    mRect = new RectF();
    mPaint = new Paint();
    mPaint.setColor(0xffff0000);
  }
    @Override
    public void run() {
      boolean needPrepare = false;
      if (mTsbSupport) {
        mWallpaperDrawable = null; // 动态壁纸
        mSysDrawSuport = true;
      } else {
        synchronized (mSupperWallpaperLock) {
          try {
            mWallpaperDrawable = null;
            mWallpaperDrawable = mWallPaperManager.getDrawable();
            Resources resources = GOLauncherApp.getContext().getResources();
            int screenWidth = resources.getDisplayMetrics().widthPixels;
            int screenHeight = resources.getDisplayMetrics().heightPixels;
            boolean needReturen = preventAmplifyWallpaper(resources, screenWidth);
            if (needReturen) {
              mSettingSupperWallpaper = false;
              return;
            }
            if (mWallpaperDrawable != null) {
              int bmpWidth = mWallpaperDrawable.getIntrinsicWidth();
              int bmpHeight = mWallpaperDrawable.getIntrinsicHeight();
              if (bmpHeight < screenHeight || bmpWidth < screenWidth) {
                mWallpaperDrawable = preventBlackScreen(mWallpaperDrawable);
              }
            }
            needPrepare = true;
          } catch (OutOfMemoryError e) {
            Log.e(TAG, "outOfMemory in updateWallpaper(boolean)" + e.getMessage());
            OutOfMemoryHandler.handle();
            resetData(); // 交由系统去处理
          } catch (Exception e) {
            mSettingSupperWallpaper = false;
            Log.e(TAG, "updateWallPaper()" + e.getMessage());
          }
          mSysDrawSuport = false;
          if (null == mWallpaperDrawable) { // 当获取壁纸失败时,交由系统自己处理
            mSysDrawSuport = true;
          }
          mHandler.sendEmptyMessage(MSG_UPDATE_WALLPAPER_TYPE);

          if (needPrepare && null != mWallpaperDrawable) { // 逻辑预处理
            mWallpaperDrawable = prepareOrientationChange(mWallpaperDrawable);
          }
          mHandler.sendEmptyMessage(MSG_UPDATE_WALLPAPER);
        } // end synchronized
      } // end else
    } // end run
  /**
   * 调整壁纸尺寸的方法,只要是针对壁纸放大的问题(用户当前是可滚,但是选择壁纸时却是单屏,这时候设回为单屏)
   *
   * @param wallpaperManager
   * @return
   */
  public static boolean adjustWallpaperDimension(WallpaperManager wallpaperManager) {
    // 是否进行调整的结果
    boolean result = false;
    if (wallpaperManager == null) {
      wallpaperManager = WallpaperManager.getInstance(GOLauncherApp.getContext());
    }
    try {
      Method method = wallpaperManager.getClass().getMethod("getIWallpaperManager");
      Object iWallpaperManager = method.invoke(wallpaperManager);
      // Class IWallpaperManager = iWallpaperManager.getClass();
      Class iWallpaperManagerClass = Class.forName("android.app.IWallpaperManager");

      Field field = wallpaperManager.getClass().getDeclaredField("sGlobals");
      field.setAccessible(true);
      Object globals = field.get(wallpaperManager);

      Class[] arrayOfClass =
          new Class[] {Class.forName("android.app.IWallpaperManagerCallback"), Bundle.class};
      method = iWallpaperManagerClass.getDeclaredMethod("getWallpaper", arrayOfClass);
      method.setAccessible(true);

      Bundle params = new Bundle();
      ParcelFileDescriptor fd =
          (ParcelFileDescriptor) method.invoke(iWallpaperManager, new Object[] {globals, params});

      if (fd != null) {
        final int width = params.getInt("width", 0);
        final int height = params.getInt("height", 0);
        try {
          BitmapFactory.Options options = new BitmapFactory.Options();
          Bitmap bm = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, options);
          final int bitWidth = bm.getWidth();
          final int bitHeight = bm.getHeight();
          GoSettingControler settingControler = GOLauncherApp.getSettingControler();
          ScreenSettingInfo screenSettingInfo =
              GOLauncherApp.getSettingControler().getScreenSettingInfo();

          if (bitWidth == width / 2 && screenSettingInfo.mWallpaperScroll) {
            screenSettingInfo.mWallpaperScroll = false;
            result = true;
          }
          // else if(bitWidth == width * 2 &&
          // !screenSettingInfo.mWallpaperScroll){
          // screenSettingInfo.mWallpaperScroll = true;
          // result = true;
          // }
          if (result) {
            // 把屏幕是否可滚写进数据库
            settingControler.updateScreenSettingInfo(screenSettingInfo, false);
            WallpaperDensityUtil.setWallpaperDimension(GoLauncher.getContext());
          }
        } catch (OutOfMemoryError e) {
          result = false;
        } finally {
          try {
            fd.close();
          } catch (IOException e) {
            result = false;
          }
        }
      }
    } catch (Throwable e) {
      Log.v("System.out.print", e.toString());
      result = false;
    }
    return result;
  } // end adjustWallpaperDimension
 public void updateWallpaper(boolean fromIntentReceiver) {
   boolean needPrepare = false;
   boolean hasException = false;
   Object wallpaperInfo = null;
   try {
     Method getWallpaperInfo = mWallPaperManager.getClass().getMethod("getWallpaperInfo");
     wallpaperInfo = getWallpaperInfo.invoke(mWallPaperManager);
   } catch (Throwable e) {
     hasException = true;
   }
   final boolean isLiveWallpaper = !hasException && wallpaperInfo != null ? true : false;
   boolean livecChange = false;
   if (isLiveWallpaper && wallpaperInfo instanceof WallpaperInfo) {
     String newPkgName = ((WallpaperInfo) wallpaperInfo).getPackageName();
     if (!newPkgName.equals(mLwpPkgName)) {
       mLwpPkgName = newPkgName;
       livecChange = true;
     }
   }
   if (isLiveWallpaper != mLwpSupport || livecChange) { // 壁纸动/静切换或者是动态壁纸切换动态壁纸,均需要通知更新
     mLwpSupport = isLiveWallpaper;
     if (Workspace.getLayoutScale() < 1.0f) { // 如果壁纸发生(动/静)变更并且桌面是添加状态
       // 通知添加模块添加壁纸设置选项发生变更
       GoLauncher.sendMessage(
           this,
           IDiyFrameIds.SCREEN_EDIT_BOX_FRAME,
           IDiyMsgIds.SCREEN_EDIT_UPDATE_WALLPAPER_ITEMS,
           0,
           null,
           null);
     }
   }
   synchronized (mSupperWallpaperLock) {
     if (mTsbSupport || isLiveWallpaper) {
       mWallpaperDrawable = null; // 动态壁纸
       mSysDrawSuport = true;
     } else {
       if (fromIntentReceiver || mWallpaperDrawable == null) {
         try {
           mWallpaperDrawable = null;
           mWallpaperDrawable = mWallPaperManager.getDrawable();
           Resources resources = GOLauncherApp.getContext().getResources();
           int screenWidth = resources.getDisplayMetrics().widthPixels;
           int screenHeight = resources.getDisplayMetrics().heightPixels;
           boolean needReturen = preventAmplifyWallpaper(resources, screenWidth);
           if (needReturen) {
             return;
           }
           if (mWallpaperDrawable != null) {
             int bmpWidth = mWallpaperDrawable.getIntrinsicWidth();
             int bmpHeight = mWallpaperDrawable.getIntrinsicHeight();
             if (bmpHeight < screenHeight || bmpWidth < screenWidth) {
               mWallpaperDrawable = preventBlackScreen(mWallpaperDrawable);
             }
           }
           needPrepare = true;
         } catch (OutOfMemoryError e) {
           Log.e(TAG, "outOfMemory in updateWallpaper(boolean)" + e.getMessage());
           OutOfMemoryHandler.handle();
           resetData(); // 交由系统去处理
         } catch (Exception e) {
           Log.e(TAG, "updateWallPaper()" + e.getMessage());
         }
       }
       // mLwpSupport = false;
       mSysDrawSuport = false;
       if (null == mWallpaperDrawable) { // 当获取壁纸失败时,交由系统自己处理
         // mLwpSupport = true;
         mSysDrawSuport = true;
       }
     }
     setWindowBackground(mSysDrawSuport); // 更新壁纸
     if (needPrepare && null != mWallpaperDrawable) { // 逻辑预处理
       mWallpaperDrawable = prepareOrientationChange(mWallpaperDrawable);
     }
     invokeWallPaperChange(); // 通知
     if (needPrepare && mWallpaperDrawable != null && sIsWallpaperSetting) { // 调整壁纸宽度
       sIsWallpaperSetting = false;
       adjustWallpaperDimension(mWallPaperManager);
     }
   } // end synchronized
 }