private DefaultWallpaperInfo getDefaultWallpaper() {
    File defaultThumbFile = new File(getFilesDir(), DEFAULT_WALLPAPER_THUMBNAIL_FILENAME);
    Bitmap thumb = null;
    boolean defaultWallpaperExists = false;
    if (defaultThumbFile.exists()) {
      thumb = BitmapFactory.decodeFile(defaultThumbFile.getAbsolutePath());
      defaultWallpaperExists = true;
    } else {
      // Delete old thumbnail file, since we had a bug where the thumbnail wasn't being drawn
      // before
      new File(getFilesDir(), OLD_DEFAULT_WALLPAPER_THUMBNAIL_FILENAME).delete();

      Resources res = getResources();
      Point defaultThumbSize = getDefaultThumbnailSize(res);
      Drawable wallpaperDrawable =
          WallpaperManager.getInstance(this)
              .getBuiltInDrawable(defaultThumbSize.x, defaultThumbSize.y, true, 0.5f, 0.5f);
      if (wallpaperDrawable != null) {
        thumb =
            Bitmap.createBitmap(defaultThumbSize.x, defaultThumbSize.y, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(thumb);
        wallpaperDrawable.setBounds(0, 0, defaultThumbSize.x, defaultThumbSize.y);
        wallpaperDrawable.draw(c);
        c.setBitmap(null);
      }
      if (thumb != null) {
        defaultWallpaperExists = writeImageToFileAsJpeg(defaultThumbFile, thumb);
      }
    }
    if (defaultWallpaperExists) {
      return new DefaultWallpaperInfo(new BitmapDrawable(thumb));
    }
    return null;
  }
 private void onSetAsWallpaper() {
   WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
   if (wallpaperFile == null || !wallpaperFile.exists()) {
     Snackbar.make(rootLayout, R.string.fab_snack_bar_image_not_cached, Snackbar.LENGTH_LONG)
         .show();
   } else {
     if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
       Bitmap wallpaper = BitmapFactory.decodeFile(wallpaperFile.getAbsolutePath());
       if (wallpaper != null) {
         try {
           wallpaperManager.setBitmap(wallpaper);
           if (floatingActionMenu.isOpened()) floatingActionMenu.close(true);
           Toast.makeText(this, "Image set as Wallpaper", Toast.LENGTH_SHORT).show();
         } catch (IOException io) {
           io.printStackTrace();
         }
       }
     } else {
       Uri cropWallpaperUri =
           FileProvider.getUriForFile(this, "com.pddstudio.fileprovider", wallpaperFile);
       if (cropWallpaperUri != null) {
         Intent cropIntent = wallpaperManager.getCropAndSetWallpaperIntent(cropWallpaperUri);
         startActivity(cropIntent);
       }
     }
   }
 }
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
   if (requestCode == IMAGE_PICK && resultCode == RESULT_OK) {
     if (data != null && data.getData() != null) {
       Uri uri = data.getData();
       addTemporaryWallpaperTile(uri, false);
     }
   } else if (requestCode == PICK_WALLPAPER_THIRD_PARTY_ACTIVITY) {
     setResult(RESULT_OK);
     finish();
   } else if (requestCode == PICK_LIVE_WALLPAPER) {
     WallpaperManager wm = WallpaperManager.getInstance(this);
     final WallpaperInfo oldLiveWallpaper = mLiveWallpaperInfoOnPickerLaunch;
     final WallpaperInfo clickedWallpaper = mLastClickedLiveWallpaperInfo;
     WallpaperInfo newLiveWallpaper = wm.getWallpaperInfo();
     // Try to figure out if a live wallpaper was set;
     if (newLiveWallpaper != null
         && (oldLiveWallpaper == null
             || !oldLiveWallpaper.getComponent().equals(newLiveWallpaper.getComponent())
             || clickedWallpaper.getComponent().equals(oldLiveWallpaper.getComponent()))) {
       // Return if a live wallpaper was set
       setResult(RESULT_OK);
       finish();
     }
   }
 }
 public void onCreate(Bundle bundle) {
   super.onCreate(bundle);
   finish();
   try {
     WallpaperManager wm = WallpaperManager.getInstance(this);
     wm.setResource(R.drawable.black);
   } catch (java.io.IOException e) {
   }
 }
 @Override
 public void onSave(WallpaperPickerActivity a) {
   try {
     WallpaperManager.getInstance(a).clear();
     a.setResult(RESULT_OK);
   } catch (IOException e) {
     Log.w("Setting wallpaper to default threw exception", e);
   }
   a.finish();
 }
 @Override
 public void run() {
   try {
     WallpaperManager.getInstance(mContext).setBitmap(mBitmap);
   } catch (IOException e) {
     Log.e(LOG_TAG, "Failed to set wallpaper.", e);
   } finally {
     mHandler.sendEmptyMessage(FINISH);
     mFile.delete();
   }
 }
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    fa = super.getActivity();
    ll = (LinearLayout) inflater.inflate(R.layout.saturate_frag, container, false);
    prefs = fa.getSharedPreferences(C.PREF, Context.MODE_PRIVATE);
    mUtils = new Utils(fa);
    wm = WallpaperManager.getInstance(fa);
    image = (ImageView) ll.findViewById(R.id.main_image);
    try {
      WallpaperInfo info = wm.getWallpaperInfo();
      info.toString();
      mUtils.sendToast(getResources().getString(R.string.live_wallpaper));
    } catch (NullPointerException ignore) {
    }
    time_text = (TextView) ll.findViewById(R.id.time_text);
    seek = (SeekBar) ll.findViewById(R.id.seeker);
    seek.setMax(23);
    Calendar cal = Calendar.getInstance();
    hour = cal.get(Calendar.HOUR_OF_DAY);
    time_text.setText(mUtils.getHour(hour));
    seek.setOnSeekBarChangeListener(
        new SeekBar.OnSeekBarChangeListener() {

          @Override
          public void onProgressChanged(SeekBar v, int num, boolean isU) {
            if (!isRunning) {
              time_text.setText(mUtils.getHour(num));
              seekerFl = mUtils.getFloat(num);
              Drawable d = mUtils.convertToGrayscale(wm.getDrawable(), seekerFl);
              image.setImageDrawable(d);
            }
          }

          @Override
          public void onStartTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
          }

          @Override
          public void onStopTrackingTouch(SeekBar arg0) {
            // TODO Auto-generated method stub
          }
        });

    if (!prefs.getBoolean(C.PREF_SATURATE_FIRST_RUN_MAIN, false)) {
      prefs.edit().putBoolean(C.PREF_SATURATE_FIRST_RUN_MAIN, true).commit();
      String title = getResources().getString(R.string.main_title_saturate);
      String message = getResources().getString(R.string.saturate_description);
      new CustomDialogs().openFirstDialog(fa, title, message);
    }
    setHasOptionsMenu(true);
    return ll;
  }
 @Override
 protected Boolean doInBackground(Void... params) {
   WallpaperManager wallpaperManager = WallpaperManager.getInstance(mContext);
   try {
     String path =
         mContext.getString(R.string.theme)
             + "/"
             + theme
             + "/"
             + mContext.getString(R.string.wallpaper)
             + "/"
             + mContext.getString(R.string.wallpaper)
             + ".jpg";
     wallpaperManager.setStream(mContext.getAssets().open(path));
     /*Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(path));
     			int width = Utilities.getScreenWidth(ThemeEffectPreview.this);
     			int height = Utilities.getScreenHeight(ThemeEffectPreview.this);
     			int x = (bitmap.getWidth() -width)/2;
     			int y = (bitmap.getHeight() - height)/2;
     			Bitmap bitmapCrop = Bitmap.createBitmap(bitmap,x,y,width,height);
     ;			ByteArrayOutputStream bos = new ByteArrayOutputStream();
     			bitmapCrop.compress(CompressFormat.JPEG,85,bos);
     			String[] array = mContext.getResources().getStringArray(R.array.wallpaper_chooser);*/
     ContentValues value_lock_screen = new ContentValues();
     value_lock_screen.put("_id", 1);
     value_lock_screen.put("flag", 0);
     ContentValues value_main_menu = new ContentValues();
     value_main_menu.put("_id", 2);
     value_main_menu.put("flag", 0);
     Uri url = Uri.parse("content://" + "com.android.launcher3.settings" + "/" + "wallpaper");
     Log.i("messi", "insert start");
     Uri newUrl_lock_screen =
         ThemeEffectPreview.this.getContentResolver().insert(url, value_lock_screen);
     Uri newUrl_main_menu =
         ThemeEffectPreview.this.getContentResolver().insert(url, value_main_menu);
     if (newUrl_lock_screen == null) {
       Log.i("messi", "update start");
       mContext
           .getContentResolver()
           .update(url, value_lock_screen, "_id =  ?", new String[] {"1"});
     }
     if (newUrl_main_menu == null) {
       Log.i("messi", "update start");
       mContext
           .getContentResolver()
           .update(url, value_main_menu, "_id =  ?", new String[] {"2"});
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
   return true;
 }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mView = (RelativeLayout) findViewById(R.id.mainview);
    mView.setFocusableInTouchMode(false);

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
      mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    }

    mWPM = WallpaperManager.getInstance(this);
  }
  @Override
  public void onClick() {
    if (fd.fileType != Constants.FILE_TYPE_PICTURES) {
      return;
    }

    try {
      Bitmap bitmap = BitmapFactory.decodeFile(fd.filePath);
      WallpaperManager.getInstance(getContext()).setBitmap(bitmap);
    } catch (Throwable e) {
      UIUtils.showShortMessage(getContext(), R.string.failed_to_set_wallpaper);
    }
  }
  protected void updateWallpaperDimensions(int width, int height) {
    String spKey = getSharedPreferencesKey();
    SharedPreferences sp = getSharedPreferences(spKey, Context.MODE_MULTI_PROCESS);
    SharedPreferences.Editor editor = sp.edit();
    if (width != 0 && height != 0) {
      editor.putInt(WALLPAPER_WIDTH_KEY, width);
      editor.putInt(WALLPAPER_HEIGHT_KEY, height);
    } else {
      editor.remove(WALLPAPER_WIDTH_KEY);
      editor.remove(WALLPAPER_HEIGHT_KEY);
    }
    editor.commit();

    suggestWallpaperDimension(
        getResources(), sp, getWindowManager(), WallpaperManager.getInstance(this), true);
  }
  private void saveOutput(Bitmap croppedImage) {
    if (mSaveUri != null) {
      makeSureFileExist(mSaveUri);
      OutputStream outputStream = null;
      try {
        outputStream = mContentResolver.openOutputStream(mSaveUri);
        if (outputStream != null) {
          croppedImage.compress(mOutputFormat, 75, outputStream);
        }
      } catch (IOException ex) {
        // TODO: report error to caller
        Log.e(TAG, "Cannot open file: " + mSaveUri, ex);
      } catch (IllegalStateException e) {
        Log.e(TAG, "IllegalStateException Error");
      } finally {
        Util.closeSilently(outputStream);
      }

      Bundle extras = new Bundle();
      // 将保存的路径再次返回给调用者
      setResult(RESULT_OK, new Intent(mSaveUri.toString()).putExtras(extras));
    } else if (mSetWallpaper) {
      try {
        WallpaperManager.getInstance(this).setBitmap(croppedImage);
        setResult(RESULT_OK);
      } catch (IOException e) {
        Log.e(TAG, "Failed to set wallpaper.", e);
        setResult(RESULT_CANCELED);
      }
    }

    final Bitmap b = croppedImage;
    mHandler.post(
        new Runnable() {
          @Override
          public void run() {
            mImageView.clear();
            b.recycle();
          }
        });

    finish();
  }
    @Override
    public void onClick(WallpaperPickerActivity a) {
      CropView c = a.getCropView();

      Drawable defaultWallpaper =
          WallpaperManager.getInstance(a)
              .getBuiltInDrawable(c.getWidth(), c.getHeight(), false, 0.5f, 0.5f);

      if (defaultWallpaper == null) {
        Log.w(TAG, "Null default wallpaper encountered.");
        c.setTileSource(null, null);
        return;
      }

      c.setTileSource(
          new DrawableTileSource(a, defaultWallpaper, DrawableTileSource.MAX_PREVIEW_SIZE), null);
      c.setScale(1f);
      c.setTouchEnabled(false);
      a.setSystemWallpaperVisiblity(false);
    }
  @Override
  public View onCreateView(
      LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View v = inflater.inflate(R.layout.wallpaper_effects, container, false);

    mWall = (ImageView) v.findViewById(R.id.wall);
    mBlur = (SeekBar) v.findViewById(R.id.sb_blur);
    mApply = (Button) v.findViewById(R.id.btn_apply);
    mWall.setDrawingCacheEnabled(true);
    mBlur.setMax(25);

    mBlur.setOnSeekBarChangeListener(this);
    mApply.setOnClickListener(this);

    wallpaperManager = WallpaperManager.getInstance(getActivity());
    final Drawable wallpaperDrawable = wallpaperManager.getDrawable();

    mWall.setImageDrawable(wallpaperDrawable);

    source = drawableToBitmap(wallpaperDrawable);

    return v;
  }
 public ShortcutAndWidgetContainer(Context context) {
   super(context);
   mWallpaperManager = WallpaperManager.getInstance(context);
 }
  private void init_resource() {

    setContentView(R.layout.activity_set_as_wallpaper);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setHomeButtonEnabled(true);
    actionBar.setDisplayHomeAsUpEnabled(true);

    mContext = this;
    isWallpaperSet = false;

    flOuter = (FrameLayout) findViewById(R.id.flOuter);
    ivImage = (ImageView) findViewById(R.id.ivImage);
    ivSelection = (ImageView) findViewById(R.id.ivSelection);
    //        ivSelection2 = (ImageView) findViewById(R.id.ivSelection2);
    btnOk = (Button) findViewById(R.id.btnSetWallPaper);
    btnCancel = (Button) findViewById(R.id.btnCancel);
    standardLinearLayout = (ImageView) findViewById(R.id.standard);
    fixedLinearLayout = (ImageView) findViewById(R.id.fixed);
    entireLinearLayout = (ImageView) findViewById(R.id.entire);
    fixedLinearLayout.setBackgroundResource(R.drawable.circle_blue);
    checkBoxScrollable = (CheckBox) findViewById(R.id.checkBoxScrollable);
    checkBoxScrollable.setEnabled(false);
    isScrollable = false;
    // Calculate grip width
    metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    border_grip = metrics.density * 20;

    opt_display_width = getResources().getDisplayMetrics().widthPixels;
    opt_display_height = getResources().getDisplayMetrics().heightPixels;

    //
    ui_handler = new Handler();

    //
    wpm = WallpaperManager.getInstance(this);

    btnOk.setEnabled(false);

    // Expansion and movement of the selected range
    ivSelection.setOnTouchListener(
        new OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            // It does not process if yet initialized
            if (bLoading) return false;
            // It is not processed if the entire mode
            if (bEntire) return false;

            float x = event.getX();
            float y = event.getY();
            float raw_x = event.getRawX();
            float raw_y = event.getRawY();

            switch (event.getAction()) {
              case MotionEvent.ACTION_UP:
              case MotionEvent.ACTION_CANCEL:
                // The end of the drag operation
                if (tracking_mode != TRACK_NONE) {
                  tracking_mode = TRACK_NONE;
                  return true;
                }
                break;
              case MotionEvent.ACTION_DOWN: // Start of move expansion
                if (tracking_mode == TRACK_NONE) {
                  // Remember the position and width of the selection at the time of start of
                  // movement
                  LinearLayout.LayoutParams lpSelection =
                      (LinearLayout.LayoutParams) ivSelection.getLayoutParams();
                  prev_selection.left = lpSelection.leftMargin;
                  prev_selection.top = lpSelection.topMargin;
                  prev_selection.right = prev_selection.left + ivSelection.getWidth();
                  prev_selection.bottom = prev_selection.top + ivSelection.getHeight();

                  if (x < border_grip
                      || prev_selection.width() - x < border_grip
                      || y < border_grip
                      || prev_selection.height() - y < border_grip) {
                    // Scale to grab the Hajikko
                    tracking_mode = TRACK_ZOOM;
                    // Center position at the touch start (raw coordinates)
                    zoom_center_x = raw_x - x + ivSelection.getWidth() / 2;
                    zoom_center_y = raw_y - y + ivSelection.getHeight() / 2;
                    // Distance of the center and the current position
                    zoom_start_len =
                        (float)
                            Math.sqrt(
                                Math.pow(raw_x - zoom_center_x, 2)
                                    + Math.pow(raw_y - zoom_center_y, 2));
                  } else {
                    // Move and grab the center
                    tracking_mode = TRACK_MOVE;
                    // Touch position at the touch start
                    touch_start_x = raw_x;
                    touch_start_y = raw_y;
                  }
                  return true;
                }
                break;
              case MotionEvent.ACTION_MOVE:
                if (tracking_mode == TRACK_ZOOM && !bStandard && !bFixed) {
                  // Examine the distance from the center
                  float len =
                      (float)
                          Math.sqrt(
                              Math.pow(raw_x - zoom_center_x, 2)
                                  + Math.pow(raw_y - zoom_center_y, 2));
                  if (len < border_grip * 2) len = border_grip * 2;

                  // Changes size according to the distance change of the
                  int new_w, new_h;
                  if (wall_image_aspect >= 1) {
                    new_w = (int) (0.5 + prev_selection.width() * len / zoom_start_len);
                    new_h = (int) (0.5 + new_w / wall_image_aspect);
                  } else {
                    new_h = (int) (0.5 + prev_selection.height() * len / zoom_start_len);
                    new_w = (int) (0.5 + new_h * wall_image_aspect);
                  }
                  // クリッピング
                  if (new_w > shown_image_rect.width()) {
                    new_w = (int) shown_image_rect.width();
                    new_h = (int) (0.5 + new_w / wall_image_aspect);
                  }
                  if (new_h > shown_image_rect.height()) {
                    new_h = (int) shown_image_rect.height();
                    new_w = (int) (0.5 + new_h * wall_image_aspect);
                  }
                  setSelection(
                      (prev_selection.left + prev_selection.right) / 2 - new_w / 2,
                      (prev_selection.top + prev_selection.bottom) / 2 - new_h / 2,
                      new_w,
                      new_h);

                  return true;
                }
                if (tracking_mode == TRACK_MOVE) {
                  // And update the position of the mobile mode
                  setSelection(
                      prev_selection.left + (int) (0.5 + raw_x - touch_start_x),
                      prev_selection.top + (int) (0.5 + raw_y - touch_start_y),
                      prev_selection.width(),
                      prev_selection.height());
                  return true;
                }
                break;
            }
            return false;
          }
        });

    // キャンセルボタン
    btnCancel.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            finish();
          }
        });

    // 壁紙セット
    btnOk.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            Log.e("OK", "1");
            if (bLoading) return;
            Log.e("OK", "2");
            // 既に作業中なら何もしない
            if (dialog != null) return;
            Log.e("OK", "3");
            if (wp_task != null) return;
            Log.e("OK", "4");
            // 処理中ダイアログを表示
            dialog =
                ProgressDialog.show(
                    SetWallpaperActivity.this,
                    getText(R.string.wallpaper_progress_title),
                    getText(R.string.wallpaper_progress_message),
                    true);
            // Background processing
            Log.e("OK", "5");
            wp_task = new WallpaperTask();
            wp_task.start();
          }
        });
    standardLinearLayout.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            standardWallpaperOption();
          }
        });
    fixedLinearLayout.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            fixedWallpaperOption();
          }
        });
    entireLinearLayout.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View v) {
            entireWallpaperOption();
          }
        });
    checkBoxScrollable.setOnCheckedChangeListener(
        new CompoundButton.OnCheckedChangeListener() {
          @Override
          public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            isScrollable = isChecked;
          }
        });
  }
  @Override
  public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    CONTEXT = this.getApplicationContext();
    AM = this.getAssets();

    try {
      PLACEHOLDERBMP = BitmapFactory.decodeStream(AM.open("transparent.png"));
    } catch (IOException e) {
      e.printStackTrace();
    }

    WPM = WallpaperManager.getInstance(this);
    PREFS = PreferenceManager.getDefaultSharedPreferences(OMWPP.CONTEXT);

    BMPQUERYOPTIONS = new BitmapFactory.Options();
    BMPQUERYOPTIONS.inJustDecodeBounds = true;

    BMPVALIDOPTIONS = new BitmapFactory.Options();
    BMPVALIDOPTIONS.inSampleSize = 4;

    BMPAPPLYOPTIONS = new BitmapFactory.Options();
    BMPAPPLYOPTIONS.inSampleSize = 1;
    BMPAPPLYOPTIONS.inScaled = false;
    BMPAPPLYOPTIONS.inDither = false;
    BMPAPPLYOPTIONS.inPreferredConfig = Config.ARGB_8888;

    // Initialize the four queues.
    THUMBNAILQUEUE = new ConcurrentLinkedQueue<File>();
    DOWNLOADQUEUE = new ArrayBlockingQueue<URL>(20, false);
    UNZIPQUEUE = new ArrayBlockingQueue<File>(20, false);

    SCREENWIDTH = getResources().getDisplayMetrics().widthPixels;
    SCREENHEIGHT = getResources().getDisplayMetrics().heightPixels;

    WPWIDTH = WPM.getDesiredMinimumWidth();
    WPHEIGHT = WPM.getDesiredMinimumHeight();
    if (WPWIDTH < SCREENWIDTH * 2) WPWIDTH = SCREENWIDTH * 2;
    if (WPHEIGHT < SCREENHEIGHT) WPHEIGHT = SCREENHEIGHT;
    if (OMWPP.DEBUG) Log.i("OMWPPApp", "Target Width is" + WPWIDTH);
    if (OMWPP.DEBUG) Log.i("OMWPPApp", "Target Height is " + WPHEIGHT);

    try {
      ENDMARKER_URL = new URL("http://localhost");
    } catch (Exception e) {
      e.printStackTrace();
    }

    if (isSDPresent()) {
      // Check and/or create the wallpapers directory.
      SDROOT = new File(Environment.getExternalStorageDirectory().getPath() + "/ubuntuwps/");
      if (OMWPP.DEBUG) Log.i("OMWPPApp", "Checking/Creating " + SDROOT.getAbsoluteFile());
      SDROOT.mkdirs();
      THUMBNAILROOT = getExternalFilesDir(null);
      if (OMWPP.DEBUG) Log.i("OMWPPApp", "Checking/Creating " + THUMBNAILROOT.getAbsoluteFile());
      THUMBNAILROOT.mkdirs();
      File nomedia = new File(THUMBNAILROOT.getAbsolutePath() + "/.nomedia");
      try {
        if (!nomedia.exists()) nomedia.createNewFile();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
    // First of all, let's load up the latest configuration JSON file.
    try {
      if (isSDPresent()) {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "Loading config file from TN folder");
        CONFIGJSON =
            streamToJSONObject(
                new FileInputStream(new File(THUMBNAILROOT.getPath() + "/omwpp_config.json")));
      } else {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "No config file in TN folder");
        throw new Exception();
      }
    } catch (Exception e) {
      try {
        if (OMWPP.DEBUG) Log.i("OMWPPApp", "Copying default files to Wallpaper folder");
        copyAssetToFile("omwpp_config.json", THUMBNAILROOT.getPath() + "/omwpp_config.json");
        CONFIGJSON =
            streamToJSONObject(
                new FileInputStream(new File(THUMBNAILROOT.getPath() + "/omwpp_config.json")));
        CONFIGJSON.putOpt("localpaths", new JSONArray("[\"" + SDROOT.toString() + "\"]"));
        commitJSONChanges();

        try {
          for (String sFile : OMWPP.AM.list("")) {
            copyAssetToFile(sFile, SDROOT.getPath() + "/" + sFile);
          }
        } catch (Exception ee) {
          ee.printStackTrace();
        }
      } catch (Exception ee) {
        e.printStackTrace();
      }
    }

    // Figure out when we last downloaded a new config file.
    LASTCONFIGREFRESH = OMWPP.PREFS.getLong("LASTCONFIGREFRESH", 0l);
  }
  /**
   * 调整壁纸尺寸的方法,只要是针对壁纸放大的问题(用户当前是可滚,但是选择壁纸时却是单屏,这时候设回为单屏)
   *
   * @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
 private WallpaperControler(Activity activity, IWallpaperChangeListener listener) {
   mWallPaperManager = WallpaperManager.getInstance(activity);
   mActivityReference = new WeakReference<Activity>(activity);
   mUpdateWallpaperRunnable = new UpdateWallpaperRunnable();
   mListener = listener;
 }
  private void saveOutput(Bitmap croppedImage) {
    if (mSaveUri != null) {
      OutputStream outputStream = null;
      try {
        outputStream = mContentResolver.openOutputStream(mSaveUri);
        if (outputStream != null) {
          croppedImage.compress(mOutputFormat, mOutputQuality, outputStream);
        }
      } catch (IOException ex) {
        // TODO: report error to caller
        Log.e(TAG, "Cannot open file: " + mSaveUri, ex);
      } finally {
        Util.closeSilently(outputStream);
      }
      Bundle extras = new Bundle();
      setResult(RESULT_OK, new Intent(mSaveUri.toString()).putExtras(extras));
    } else if (mSetWallpaper) {
      try {
        WallpaperManager.getInstance(this).setBitmap(croppedImage);
        setResult(RESULT_OK);
      } catch (IOException e) {
        Log.e(TAG, "Failed to set wallpaper.", e);
        setResult(RESULT_CANCELED);
      }
    } else {
      Bundle extras = new Bundle();
      extras.putString("rect", mCrop.getCropRect().toString());

      File oldPath = new File(mImage.getDataPath());
      File directory = new File(oldPath.getParent());

      int x = 0;
      String fileName = oldPath.getName();
      fileName = fileName.substring(0, fileName.lastIndexOf("."));

      // Try file-1.jpg, file-2.jpg, ... until we find a filename which
      // does not exist yet.
      while (true) {
        x += 1;
        String candidate = directory.toString() + "/" + fileName + "-" + x + ".jpg";
        boolean exists = (new File(candidate)).exists();
        if (!exists) {
          break;
        }
      }

      try {
        int[] degree = new int[1];
        Uri newUri =
            ImageManager.addImage(
                mContentResolver,
                mImage.getTitle(),
                mImage.getDateTaken(),
                null, // TODO this null is going to cause us to lose
                // the location (gps).
                directory.toString(),
                fileName + "-" + x + ".jpg",
                croppedImage,
                null,
                degree);

        setResult(RESULT_OK, new Intent().setAction(newUri.toString()).putExtras(extras));
      } catch (Exception ex) {
        // basically ignore this or put up
        // some ui saying we failed
        Log.e(TAG, "store image fail, continue anyway", ex);
      }
    }

    final Bitmap b = croppedImage;
    mHandler.post(
        new Runnable() {
          public void run() {
            mImageView.clear();
            b.recycle();
          }
        });

    finish();
  }
    public boolean cropBitmap() {
      boolean failure = false;

      WallpaperManager wallpaperManager = null;
      if (mSetWallpaper) {
        wallpaperManager = WallpaperManager.getInstance(mContext.getApplicationContext());
      }

      if (mSetWallpaper && mNoCrop) {
        try {
          InputStream is = regenerateInputStream();
          if (is != null) {
            wallpaperManager.setStream(is);
            Utils.closeSilently(is);
          }
        } catch (IOException e) {
          Log.w(LOGTAG, "cannot write stream to wallpaper", e);
          failure = true;
        }
        return !failure;
      } else {
        // Find crop bounds (scaled to original image size)
        Rect roundedTrueCrop = new Rect();
        Matrix rotateMatrix = new Matrix();
        Matrix inverseRotateMatrix = new Matrix();

        Point bounds = getImageBounds();
        if (mRotation > 0) {
          rotateMatrix.setRotate(mRotation);
          inverseRotateMatrix.setRotate(-mRotation);

          mCropBounds.roundOut(roundedTrueCrop);
          mCropBounds = new RectF(roundedTrueCrop);

          if (bounds == null) {
            Log.w(LOGTAG, "cannot get bounds for image");
            failure = true;
            return false;
          }

          float[] rotatedBounds = new float[] {bounds.x, bounds.y};
          rotateMatrix.mapPoints(rotatedBounds);
          rotatedBounds[0] = Math.abs(rotatedBounds[0]);
          rotatedBounds[1] = Math.abs(rotatedBounds[1]);

          mCropBounds.offset(-rotatedBounds[0] / 2, -rotatedBounds[1] / 2);
          inverseRotateMatrix.mapRect(mCropBounds);
          mCropBounds.offset(bounds.x / 2, bounds.y / 2);
        }

        mCropBounds.roundOut(roundedTrueCrop);

        if (roundedTrueCrop.width() <= 0 || roundedTrueCrop.height() <= 0) {
          Log.w(LOGTAG, "crop has bad values for full size image");
          failure = true;
          return false;
        }

        // See how much we're reducing the size of the image
        int scaleDownSampleSize =
            Math.max(
                1,
                Math.min(
                    roundedTrueCrop.width() / mOutWidth, roundedTrueCrop.height() / mOutHeight));
        // Attempt to open a region decoder
        BitmapRegionDecoder decoder = null;
        InputStream is = null;
        try {
          is = regenerateInputStream();
          if (is == null) {
            Log.w(LOGTAG, "cannot get input stream for uri=" + mInUri.toString());
            failure = true;
            return false;
          }
          decoder = BitmapRegionDecoder.newInstance(is, false);
          Utils.closeSilently(is);
        } catch (IOException e) {
          Log.w(LOGTAG, "cannot open region decoder for file: " + mInUri.toString(), e);
        } finally {
          Utils.closeSilently(is);
          is = null;
        }

        Bitmap crop = null;
        if (decoder != null) {
          // Do region decoding to get crop bitmap
          BitmapFactory.Options options = new BitmapFactory.Options();
          if (scaleDownSampleSize > 1) {
            options.inSampleSize = scaleDownSampleSize;
          }
          crop = decoder.decodeRegion(roundedTrueCrop, options);
          decoder.recycle();
        }

        if (crop == null) {
          // BitmapRegionDecoder has failed, try to crop in-memory
          is = regenerateInputStream();
          Bitmap fullSize = null;
          if (is != null) {
            BitmapFactory.Options options = new BitmapFactory.Options();
            if (scaleDownSampleSize > 1) {
              options.inSampleSize = scaleDownSampleSize;
            }
            fullSize = BitmapFactory.decodeStream(is, null, options);
            Utils.closeSilently(is);
          }
          if (fullSize != null) {
            // Find out the true sample size that was used by the decoder
            scaleDownSampleSize = bounds.x / fullSize.getWidth();
            mCropBounds.left /= scaleDownSampleSize;
            mCropBounds.top /= scaleDownSampleSize;
            mCropBounds.bottom /= scaleDownSampleSize;
            mCropBounds.right /= scaleDownSampleSize;
            mCropBounds.roundOut(roundedTrueCrop);

            // Adjust values to account for issues related to rounding
            if (roundedTrueCrop.width() > fullSize.getWidth()) {
              // Adjust the width
              roundedTrueCrop.right = roundedTrueCrop.left + fullSize.getWidth();
            }
            if (roundedTrueCrop.right > fullSize.getWidth()) {
              // Adjust the left value
              int adjustment =
                  roundedTrueCrop.left
                      - Math.max(0, roundedTrueCrop.right - roundedTrueCrop.width());
              roundedTrueCrop.left -= adjustment;
              roundedTrueCrop.right -= adjustment;
            }
            if (roundedTrueCrop.height() > fullSize.getHeight()) {
              // Adjust the height
              roundedTrueCrop.bottom = roundedTrueCrop.top + fullSize.getHeight();
            }
            if (roundedTrueCrop.bottom > fullSize.getHeight()) {
              // Adjust the top value
              int adjustment =
                  roundedTrueCrop.top
                      - Math.max(0, roundedTrueCrop.bottom - roundedTrueCrop.height());
              roundedTrueCrop.top -= adjustment;
              roundedTrueCrop.bottom -= adjustment;
            }

            crop =
                Bitmap.createBitmap(
                    fullSize,
                    roundedTrueCrop.left,
                    roundedTrueCrop.top,
                    roundedTrueCrop.width(),
                    roundedTrueCrop.height());
          }
        }

        if (crop == null) {
          Log.w(LOGTAG, "cannot decode file: " + mInUri.toString());
          failure = true;
          return false;
        }
        if (mOutWidth > 0 && mOutHeight > 0 || mRotation > 0) {
          float[] dimsAfter = new float[] {crop.getWidth(), crop.getHeight()};
          rotateMatrix.mapPoints(dimsAfter);
          dimsAfter[0] = Math.abs(dimsAfter[0]);
          dimsAfter[1] = Math.abs(dimsAfter[1]);

          if (!(mOutWidth > 0 && mOutHeight > 0)) {
            mOutWidth = Math.round(dimsAfter[0]);
            mOutHeight = Math.round(dimsAfter[1]);
          }

          RectF cropRect = new RectF(0, 0, dimsAfter[0], dimsAfter[1]);
          RectF returnRect = new RectF(0, 0, mOutWidth, mOutHeight);

          Matrix m = new Matrix();
          if (mRotation == 0) {
            m.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL);
          } else {
            Matrix m1 = new Matrix();
            m1.setTranslate(-crop.getWidth() / 2f, -crop.getHeight() / 2f);
            Matrix m2 = new Matrix();
            m2.setRotate(mRotation);
            Matrix m3 = new Matrix();
            m3.setTranslate(dimsAfter[0] / 2f, dimsAfter[1] / 2f);
            Matrix m4 = new Matrix();
            m4.setRectToRect(cropRect, returnRect, Matrix.ScaleToFit.FILL);

            Matrix c1 = new Matrix();
            c1.setConcat(m2, m1);
            Matrix c2 = new Matrix();
            c2.setConcat(m4, m3);
            m.setConcat(c2, c1);
          }

          Bitmap tmp =
              Bitmap.createBitmap(
                  (int) returnRect.width(), (int) returnRect.height(), Bitmap.Config.ARGB_8888);
          if (tmp != null) {
            Canvas c = new Canvas(tmp);
            Paint p = new Paint();
            p.setFilterBitmap(true);
            c.drawBitmap(crop, m, p);
            crop = tmp;
          }
        }

        if (mSaveCroppedBitmap) {
          mCroppedBitmap = crop;
        }

        // Get output compression format
        CompressFormat cf = convertExtensionToCompressFormat(getFileExtension(mOutputFormat));

        // Compress to byte array
        ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(2048);
        if (crop.compress(cf, DEFAULT_COMPRESS_QUALITY, tmpOut)) {
          // If we need to set to the wallpaper, set it
          if (mSetWallpaper && wallpaperManager != null) {
            try {
              byte[] outByteArray = tmpOut.toByteArray();
              wallpaperManager.setStream(new ByteArrayInputStream(outByteArray));
              if (mOnBitmapCroppedHandler != null) {
                mOnBitmapCroppedHandler.onBitmapCropped(outByteArray);
              }
            } catch (IOException e) {
              Log.w(LOGTAG, "cannot write stream to wallpaper", e);
              failure = true;
            }
          }
        } else {
          Log.w(LOGTAG, "cannot compress bitmap");
          failure = true;
        }
      }
      return !failure; // True if any of the operations failed
    }
  @Override
  public void run() {
    WallpaperManager wm = WallpaperManager.getInstance(mContext);
    Drawable oldWallpaper = wm.getDrawable();
    InputStream inputstream = null;
    try {
      // TODO: This will cause the resource to be downloaded again, when
      // we should in most cases be able to grab it from the cache. To fix
      // this we should query WebCore to see if we can access a cached
      // version and instead open an input stream on that. This pattern
      // could also be used in the download manager where the same problem
      // exists.
      inputstream = openStream();
      if (inputstream != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int seg = 0;
        byte buf[] = new byte[8192];
        while ((seg = inputstream.read(buf)) != -1) {
          baos.write(buf, 0, seg);
        }
        final byte[] imageData = baos.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // We give decodeStream a wrapped input stream so it doesn't
        // mess with our mark (currently it sets a mark of 1024)
        Bitmap firstImage = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
        int maxWidth = wm.getDesiredMinimumWidth();
        int maxHeight = wm.getDesiredMinimumHeight();
        // Give maxWidth and maxHeight some leeway
        maxWidth *= 1.25;
        maxHeight *= 1.25;
        int bmWidth = options.outWidth;
        int bmHeight = options.outHeight;

        int scale = 1;
        while (bmWidth > maxWidth || bmHeight > maxHeight) {
          scale <<= 1;
          bmWidth >>= 1;
          bmHeight >>= 1;
        }
        options.inJustDecodeBounds = false;
        options.inSampleSize = scale;
        Bitmap scaledWallpaper =
            BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
        if (scaledWallpaper != null) {
          wm.setBitmap(scaledWallpaper);
        }
      }
    } catch (IOException e) {
      Log.e(LOGTAG, "Unable to set new wallpaper");
      // Act as though the user canceled the operation so we try to
      // restore the old wallpaper.
      mCanceled = true;
    } finally {
      if (inputstream != null) {
        try {
          inputstream.close();
        } catch (IOException e) {
          // Ignore
        }
      }
    }

    if (mCanceled) {
      // Restore the old wallpaper if the user cancelled whilst we were
      // setting
      // the new wallpaper.
      int width = oldWallpaper.getIntrinsicWidth();
      int height = oldWallpaper.getIntrinsicHeight();
      Bitmap bm = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
      Canvas canvas = new Canvas(bm);
      oldWallpaper.setBounds(0, 0, width, height);
      oldWallpaper.draw(canvas);
      canvas.setBitmap(null);
      try {
        wm.setBitmap(bm);
      } catch (IOException e) {
        Log.e(LOGTAG, "Unable to restore old wallpaper.");
      }
      mCanceled = false;
    }

    if (mWallpaperProgress.isShowing()) {
      mWallpaperProgress.dismiss();
    }
  }
 public void onLiveWallpaperPickerLaunch(WallpaperInfo info) {
   mLastClickedLiveWallpaperInfo = info;
   mLiveWallpaperInfoOnPickerLaunch = WallpaperManager.getInstance(this).getWallpaperInfo();
 }