@Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int count = getChildCount();
    for (int i = 0; i < count; i++) {
      final View child = getChildAt(i);
      if (child.getVisibility() != GONE) {
        CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
        int childLeft = lp.x;
        int childTop = lp.y;
        child.layout(childLeft, childTop, childLeft + lp.width, childTop + lp.height);

        if (lp.dropped) {
          lp.dropped = false;

          final int[] cellXY = mTmpCellXY;
          getLocationOnScreen(cellXY);
          mWallpaperManager.sendWallpaperCommand(
              getWindowToken(),
              WallpaperManager.COMMAND_DROP,
              cellXY[0] + childLeft + lp.width / 2,
              cellXY[1] + childTop + lp.height / 2,
              0,
              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);
       }
     }
   }
 }
  public static void suggestWallpaperDimension(
      Resources res,
      final SharedPreferences sharedPrefs,
      WindowManager windowManager,
      final WallpaperManager wallpaperManager,
      boolean fallBackToDefaults) {
    final Point defaultWallpaperSize = getDefaultWallpaperSize(res, windowManager);
    // If we have saved a wallpaper width/height, use that instead

    int savedWidth = sharedPrefs.getInt(WALLPAPER_WIDTH_KEY, -1);
    int savedHeight = sharedPrefs.getInt(WALLPAPER_HEIGHT_KEY, -1);

    if (savedWidth == -1 || savedHeight == -1) {
      if (!fallBackToDefaults) {
        return;
      } else {
        savedWidth = defaultWallpaperSize.x;
        savedHeight = defaultWallpaperSize.y;
      }
    }

    if (savedWidth != wallpaperManager.getDesiredMinimumWidth()
        || savedHeight != wallpaperManager.getDesiredMinimumHeight()) {
      wallpaperManager.suggestDesiredDimensions(savedWidth, savedHeight);
    }
  }
 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) {
   }
 }
Esempio n. 6
0
  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;
 }
 private void selectWallpaper(int position) {
   if (LauncherLog.DEBUG) {
     LauncherLog.d(TAG, "selectWallpaper: position = " + position + ", this = " + this);
   }
   try {
     WallpaperManager wpm =
         (WallpaperManager) getActivity().getSystemService(Context.WALLPAPER_SERVICE);
     wpm.setResource(mImages.get(position));
     Activity activity = getActivity();
     activity.setResult(Activity.RESULT_OK);
     activity.finish();
   } catch (IOException e) {
     Log.e(TAG, "Failed to set wallpaper: " + e);
   }
 }
  /*
   * When using touch if you tap an image it triggers both the onItemClick and
   * the onTouchEvent causing the wallpaper to be set twice. Ensure we only
   * set the wallpaper once.
   */
  private void selectWallpaper(int position) {
    if (mIsWallpaperSet) {
      return;
    }

    mIsWallpaperSet = true;
    try {
      WallpaperManager wpm = (WallpaperManager) getSystemService(WALLPAPER_SERVICE);
      wpm.setResource(mImages.get(position));
      setResult(RESULT_OK);
      finish();
    } catch (IOException e) {
      Log.e(TAG, "Failed to set wallpaper: " + e);
    }
  }
  private void updateWallpaperOffset(View window, int nums, int scrollX, int range) {
    if (!mSysDrawSuport || window == null) {
      return;
    }

    try {
      Method setWallpaperOffsetSteps =
          mWallPaperManager
              .getClass()
              .getMethod("setWallpaperOffsetSteps", float.class, float.class);
      setWallpaperOffsetSteps.invoke(mWallPaperManager, 1.0f / (nums - 1), 0);
      mWallPaperManager.setWallpaperOffsets(window.getWindowToken(), scrollX / (float) range, 0);
    } catch (Exception e) {
      Log.i(LogConstants.HEART_TAG, e.toString());
    }
  }
  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;
  }
 public WallpaperBackupHelper(Context context, String as[], String as1[]) {
   super(context);
   mContext = context;
   mFiles = as;
   mKeys = as1;
   WallpaperManager wallpapermanager = (WallpaperManager) context.getSystemService("wallpaper");
   mDesiredMinWidth = wallpapermanager.getDesiredMinimumWidth();
   mDesiredMinHeight = wallpapermanager.getDesiredMinimumHeight();
   if (mDesiredMinWidth <= 0.0D || mDesiredMinHeight <= 0.0D) {
     Display display = ((WindowManager) context.getSystemService("window")).getDefaultDisplay();
     Point point = new Point();
     display.getSize(point);
     mDesiredMinWidth = point.x;
     mDesiredMinHeight = point.y;
   }
 }
 @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();
   }
 }
  @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);
    }
  }
 @Override
 public void onClick(View v) {
   // TODO Auto-generated method stub
   switch (v.getId()) {
     case R.id.btn_apply:
       try {
         wallpaperManager.setBitmap(mWall.getDrawingCache());
       } catch (IOException e) {
         e.printStackTrace();
       }
       break;
   }
 }
Esempio n. 17
0
  /** 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 handleMessage(android.os.Message msg) {
          switch (msg.what) {
            case MSG_UPDATE_WALLPAPER:
              invokeWallPaperChange(); // 通知
              mSettingSupperWallpaper = false;
              break;

            case MSG_CHANGE_WALLPAPER_ITEM:
              // 通知添加模块添加壁纸设置选项发生变更
              GoLauncher.sendMessage(
                  this,
                  IDiyFrameIds.SCREEN_EDIT_BOX_FRAME,
                  IDiyMsgIds.SCREEN_EDIT_UPDATE_WALLPAPER_ITEMS,
                  0,
                  null,
                  null);
              break;

            case MSG_UPDATE_WALLPAPER_TYPE:
              setWindowBackground(mSysDrawSuport); // 更新壁纸
              break;

            case MSG_SET_WALLPAPER_INPUTSTREAM:
              if (mInputStream == null) {
                return;
              }
              try {
                try {
                  mWallPaperManager.setStream(mInputStream);
                } catch (IOException e) {
                  e.printStackTrace();
                }
              } catch (Exception e) {
                e.printStackTrace();
              } finally {
                try {
                  mInputStream.close();
                } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }
                mInputStream = null;
              }
              break;

            default:
              break;
          }
        }
Esempio n. 19
0
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      xPos = event.getX();
      yPos = event.getY();
      // kill app if touched in bottom right corner
      if (xPos > mView.getWidth() - 50 && event.getY() > mView.getHeight() - 50) finish();
      else {
        mWPM.sendWallpaperCommand(
            mView.getWindowToken(),
            WallpaperManager.COMMAND_TAP,
            (int) xPos,
            (int) event.getY(),
            0,
            null);
      }
    } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
      xWP = xWP + (xPos - event.getX()) / 500;
      xPos = event.getX();
      if (xWP < 0) xWP = 0;
      if (xWP > 1) xWP = 1;

      yWP = yWP + (yPos - event.getY()) / 500;
      yPos = event.getY();
      if (yWP < 0) yWP = 0;
      if (yWP > 1) yWP = 1;
      mWPM.setWallpaperOffsets(mView.getWindowToken(), xWP, yWP);
    }

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
      mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
      Log.d("Cleaner", "Lights out");
    }

    return super.onTouchEvent(event);
  }
  public boolean isLiveWallpaper() {
    boolean result = false;
    boolean hasException = false;
    Object wallpaperInfo = null;
    try {
      Method getWallpaperInfo = mWallPaperManager.getClass().getMethod("getWallpaperInfo");
      wallpaperInfo = getWallpaperInfo.invoke(mWallPaperManager);
    } catch (Throwable e) {
      hasException = true;
    }

    if (!hasException && wallpaperInfo != null) {
      // 动态壁纸
      mWallpaperDrawable = null;
      result = true;
    } else {
      if (mWallpaperDrawable == null) {
        try {
          mWallpaperDrawable = null;
          mWallpaperDrawable = mWallPaperManager.getDrawable();
        } catch (OutOfMemoryError e) {
          e.printStackTrace();
          // 交由系统去处理
          mWallpaperDrawable = null;
        } catch (Exception e) {
          e.fillInStackTrace();
        }
      }
      result = false;
      // 当获取壁纸失败时,交由系统自己处理
      if (null == mWallpaperDrawable) {
        result = true;
      }
    }
    return result;
  }
  @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;
  }
  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);
    }
 public void sendWallpaperCommand(View window, String action, int x, int y, int z, Bundle extras) {
   if (mSysDrawSuport) {
     if (window != null) {
       try {
         Method sendWallpaperCommand =
             mWallPaperManager
                 .getClass()
                 .getMethod(
                     "sendWallpaperCommand",
                     IBinder.class,
                     String.class,
                     int.class,
                     int.class,
                     int.class,
                     Bundle.class);
         sendWallpaperCommand.invoke(
             mWallPaperManager, window.getWindowToken(), action, x, y, z, extras);
       } catch (Exception e) {
         Log.i(LogConstants.HEART_TAG, "cannot send wall paper command");
       }
     }
   }
 }
 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;
          }
        });
  }
Esempio n. 28
0
  @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
 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
 }