下面列出了怎么用android.app.WallpaperManager的API类实例代码及写法,或者点击链接到github查看源代码。
private void setWallpaper() {
Observable.just(null)
.compose(bindToLifecycle())
.compose(ensurePermissions(Manifest.permission.WRITE_EXTERNAL_STORAGE))
.filter(granted -> {
if (granted) {
return true;
} else {
Toasty.info(this, getString(R.string.permission_required),
Toast.LENGTH_LONG).show();
return false;
}
})
.flatMap(granted -> download(picture.downloadUrl))
.map(file -> FileProvider.getUriForFile(this, AUTHORITIES, file))
.doOnNext(uri -> {
final WallpaperManager wm = WallpaperManager.getInstance(this);
startActivity(wm.getCropAndSetWallpaperIntent(uri));
})
.subscribe();
}
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));
}
static public 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);
}
}
private void handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
mImageView.setImageURI(Crop.getOutput(result));
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
try {
Bitmap mBitmap = getImageBitmap();
myWallpaperManager.setBitmap(mBitmap);
Toast.makeText(DetailActivity.this, "Wallpaper set",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(DetailActivity.this,
"Error setting wallpaper", Toast.LENGTH_SHORT)
.show();
}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
@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 static boolean isLightWallpaper(Context context) {
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
return false;
}
try {
WallpaperManager manager = WallpaperManager.getInstance(context);
if (manager == null) {
return false;
}
Drawable drawable = manager.getDrawable();
if (!(drawable instanceof BitmapDrawable)) {
return false;
}
return DisplayUtils.isLightColor(
DisplayUtils.bitmapToColorInt(((BitmapDrawable) drawable).getBitmap())
);
} catch (Exception ignore) {
return false;
}
}
public static BitmapDrawable getBackground(Context context) {
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(context);
// 获取当前壁纸
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
// 将Drawable,转成Bitmap
Bitmap bm = ((BitmapDrawable) wallpaperDrawable).getBitmap();
float step = 0;
// 计算出屏幕的偏移量
step = (bm.getWidth() - 480) / (7 - 1);
// 截取相应屏幕的Bitmap
DisplayMetrics dm = new DisplayMetrics();
Bitmap pbm = Bitmap.createBitmap(bm, (int) (5 * step), 0,
dm.widthPixels, dm.heightPixels);
return new BitmapDrawable(pbm);
}
public static Drawable getWallpaperDrawableWithSizeDrawable(Context context,
int width, int height, int alpha) {
WallpaperManager wallpaperManager = WallpaperManager
.getInstance(context);
// 获取当前壁纸
Drawable wallpaperDrawable = wallpaperManager.getDrawable();
// 将Drawable,转成Bitmap
Bitmap bm = ((BitmapDrawable) wallpaperDrawable).getBitmap();
bm = BitmapUtils.getAdpterBitmap(bm, width, height);
Drawable d = BitmapUtils.Bitmap2Drawable(bm);
bm = BitmapUtils.setAlpha(bm, alpha);
if (bm != null && bm.isRecycled()) {
bm.recycle();
}
return d;
}
private void toSetWallPage(Uri data) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(mActivity);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
File wallpageFile = new File(data.getPath());
Uri contentUri = getImageContentUri(mActivity,wallpageFile.getAbsolutePath());
mActivity.startActivity(wallpaperManager.getCropAndSetWallpaperIntent(contentUri));
}else{
try {
wallpaperManager.setStream(mActivity.getContentResolver().openInputStream(data));
mView.showMsg(MyApplication.getInstance().getString(R.string.set_wallpaper_success));
} catch (IOException e) {
e.printStackTrace();
mView.showMsg(e.getMessage());
}
}
}
@Override
public void onClick(WallpaperPickerActivity a) {
CropView c = a.getCropView();
Drawable defaultWallpaper = WallpaperManager.getInstance(a.getContext())
.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;
}
LoadRequest req = new LoadRequest();
req.moveToLeft = false;
req.touchEnabled = false;
req.scaleProvider = new CropViewScaleProvider() {
@Override
public float getScale(TileSource src) {
return 1f;
}
};
req.result = new DrawableTileSource(a.getContext(),
defaultWallpaper, DrawableTileSource.MAX_PREVIEW_SIZE);
a.onLoadRequestComplete(req, true);
}
@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);
}
}
}
}
public static void suggestWallpaperDimension(Resources res,
final SharedPreferences sharedPrefs,
WindowManager windowManager,
final WallpaperManager wallpaperManager, boolean fallBackToDefaults) {
final Point defaultWallpaperSize = WallpaperUtils.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);
}
}
@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 handleCrop(int resultCode, Intent result) {
if (resultCode == RESULT_OK) {
mImageView.setImageURI(Crop.getOutput(result));
WallpaperManager myWallpaperManager = WallpaperManager
.getInstance(getApplicationContext());
try {
Bitmap mBitmap = getImageBitmap();
myWallpaperManager.setBitmap(mBitmap);
Toast.makeText(DetailActivity.this, "Wallpaper set",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(DetailActivity.this,
"Error setting wallpaper", Toast.LENGTH_SHORT)
.show();
}
} else if (resultCode == Crop.RESULT_ERROR) {
Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
}
}
private void onWallpaperButtonClick() {
Toast.makeText(mActivity, mActivity.getString(R.string.setting_wallpaper),
Toast.LENGTH_SHORT).show();
if (mBasePhoto != null) {
String url = getLargestUrlAvailable(mBasePhoto);
new DownloadPhotoTask(mActivity, new Events.IPhotoDownloadedListener() {
@Override
public void onPhotoDownloaded(Bitmap bitmap, Exception e) {
if (e == null) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(mActivity);
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e1) {
e1.printStackTrace();
}
} else {
Log.e(TAG, "Error setting wallpaper");
e.printStackTrace();
}
}
}, url).execute();
}
}
@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 WallpaperManagerService(Context context) {
if (DEBUG) Slog.v(TAG, "WallpaperService startup");
mContext = context;
mShuttingDown = false;
mImageWallpaper = ComponentName.unflattenFromString(
context.getResources().getString(R.string.image_wallpaper_component));
mDefaultWallpaperComponent = WallpaperManager.getDefaultWallpaperComponent(context);
mIWindowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context.WINDOW_SERVICE));
mIPackageManager = AppGlobals.getPackageManager();
mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
mMonitor = new MyPackageMonitor();
mColorsChangedListeners = new SparseArray<>();
}
ParcelFileDescriptor updateWallpaperBitmapLocked(String name, WallpaperData wallpaper,
Bundle extras) {
if (name == null) name = "";
try {
File dir = getWallpaperDir(wallpaper.userId);
if (!dir.exists()) {
dir.mkdir();
FileUtils.setPermissions(
dir.getPath(),
FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IXOTH,
-1, -1);
}
ParcelFileDescriptor fd = ParcelFileDescriptor.open(wallpaper.wallpaperFile,
MODE_CREATE|MODE_READ_WRITE|MODE_TRUNCATE);
if (!SELinux.restorecon(wallpaper.wallpaperFile)) {
return null;
}
wallpaper.name = name;
wallpaper.wallpaperId = makeWallpaperIdLocked();
if (extras != null) {
extras.putInt(WallpaperManager.EXTRA_NEW_WALLPAPER_ID, wallpaper.wallpaperId);
}
// Nullify field to require new computation
wallpaper.primaryColors = null;
if (DEBUG) {
Slog.v(TAG, "updateWallpaperBitmapLocked() : id=" + wallpaper.wallpaperId
+ " name=" + name + " file=" + wallpaper.wallpaperFile.getName());
}
return fd;
} catch (FileNotFoundException e) {
Slog.w(TAG, "Error setting wallpaper", e);
}
return null;
}
/**
* Legacy wallpaper restores, from back when the imagery was stored under the
* "android" system package as file key/value entities.
*
* @param context
* @param files
*/
public WallpaperBackupHelper(Context context, String[] keys) {
super(context);
mContext = context;
mKeys = keys;
mWpm = (WallpaperManager) context.getSystemService(Context.WALLPAPER_SERVICE);
}
/**
* @return The {@link Bitmap} for the current wallpaper, or null if none exists.
*/
public static Bitmap getWallpaperBitmap(WallpaperManager wManager, Context mContext) {
if (null == wManager || null == mContext) return null;
final Bitmap wallpaper = getCurrentWallpaperLocked(wManager, mContext);
if (null != wallpaper) return wallpaper;
final Drawable wallpaperD = wManager.getDrawable();
if (null != wallpaperD) {
return drawableToBitmap(wallpaperD);
}
return null;
}
/**
* @see android.app.WallpaperManager$Globals#getCurrentWallpaperLocked(Context)
*/
public static Bitmap getCurrentWallpaperLocked(WallpaperManager wManager, Context mContext) {
if (null == wManager) return null;
final String GLOBALS = "Globals";
try {
// Find: android.app.WallpaperManager$Globals
final Class<?>[] sClasses = wManager.getClass().getDeclaredClasses();
for (final Class<?> sClass : sClasses) {
final String sName = sClass.getSimpleName();
if (TextUtils.isEmpty(sName)) continue;
if (GLOBALS.equals(sName)) {
// Invoke the default constructor, Globals(Looper)
final Constructor<?> sConstructor = sClass.getDeclaredConstructor(Looper.class);
if (null != sConstructor) {
sConstructor.setAccessible(true);
final Object sGlobals = sConstructor.newInstance(mContext.getMainLooper());
// Call the getCurrentWallpaperLocked() method on our Globals Object.
final Method getBitmap = sClass.getDeclaredMethod("getCurrentWallpaperLocked", Context.class);
if (null != getBitmap) {
// It's private, but who cares?
getBitmap.setAccessible(true);
return (Bitmap) getBitmap.invoke(sGlobals, mContext);
}
}
}
}
} catch (Throwable t) {
LOGE(TAG, "Cannot call WallpaperManager#getCurrentWallpaperLocked", t);
}
return null;
}
@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();
}
static public void suggestWallpaperDimension(Resources res,
final SharedPreferences sharedPrefs,
WindowManager windowManager,
final WallpaperManager wallpaperManager) {
final Point defaultWallpaperSize = getDefaultWallpaperSize(res, windowManager);
// If we have saved a wallpaper width/height, use that instead
int savedWidth = sharedPrefs.getInt(WALLPAPER_WIDTH_KEY, defaultWallpaperSize.x);
int savedHeight = sharedPrefs.getInt(WALLPAPER_HEIGHT_KEY, 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();
}
}
}
@TargetApi(Build.VERSION_CODES.N)
private Palette getHotseatPalette() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
if (AndroidVersion.isAtLeastNougat) {
try (ParcelFileDescriptor fd = wallpaperManager
.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)) {
BitmapRegionDecoder decoder = BitmapRegionDecoder
.newInstance(fd.getFileDescriptor(), false);
int height = decoder.getHeight();
Rect decodeRegion = new Rect(0, (int) (height * (1f - HOTSEAT_FRACTION)),
decoder.getWidth(), height);
Bitmap bitmap = decoder.decodeRegion(decodeRegion, null);
decoder.recycle();
if (bitmap != null) {
return Palette.from(bitmap).clearFilters().generate();
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
}
Bitmap wallpaper = ((BitmapDrawable) wallpaperManager.getDrawable()).getBitmap();
return Palette.from(wallpaper)
.setRegion(0, (int) (wallpaper.getHeight() * (1f - HOTSEAT_FRACTION)),
wallpaper.getWidth(), wallpaper.getHeight())
.clearFilters()
.generate();
}
@TargetApi(Build.VERSION_CODES.N)
private Palette getStatusBarPalette() {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(this);
int statusBarHeight = getResources()
.getDimensionPixelSize(R.dimen.status_bar_height);
if (AndroidVersion.isAtLeastNougat) {
try (ParcelFileDescriptor fd = wallpaperManager
.getWallpaperFile(WallpaperManager.FLAG_SYSTEM)) {
BitmapRegionDecoder decoder = BitmapRegionDecoder
.newInstance(fd.getFileDescriptor(), false);
Rect decodeRegion = new Rect(0, 0,
decoder.getWidth(), statusBarHeight);
Bitmap bitmap = decoder.decodeRegion(decodeRegion, null);
decoder.recycle();
if (bitmap != null) {
return Palette.from(bitmap).clearFilters().generate();
}
} catch (IOException | NullPointerException e) {
e.printStackTrace();
}
}
Bitmap wallpaper = ((BitmapDrawable) wallpaperManager.getDrawable()).getBitmap();
return Palette.from(wallpaper)
.setRegion(0, 0, wallpaper.getWidth(), statusBarHeight)
.clearFilters()
.generate();
}
@Override
public void onClick(WallpaperPickerActivity a) {
Intent preview = new Intent(WallpaperManager.ACTION_CHANGE_LIVE_WALLPAPER);
preview.putExtra(WallpaperManager.EXTRA_LIVE_WALLPAPER_COMPONENT,
mInfo.getComponent());
a.onLiveWallpaperPickerLaunch(mInfo);
a.startActivityForResultSafely(preview, WallpaperPickerActivity.PICK_LIVE_WALLPAPER);
}
private void checkFileAndSetWallPaper(File file){
if(null != file && file.exists()){
//get the contentUri for this file and start the intent
Uri contentUri = FileProvider.getUriForFile(getActivity(), "com.android.ted.gank.fileprovider", file);
//get crop intent
Intent intent = WallpaperManager.getInstance(getActivity()).getCropAndSetWallpaperIntent(contentUri);
//start activity for result so we can animate if we finish
getActivity().startActivityForResult(intent, ViewerActivity.REQUEST_CODE_SET_WALLPAPER);
}
}
public WallpaperOffsetInterpolator(Workspace workspace) {
mChoreographer = Choreographer.getInstance();
mInterpolator = new DecelerateInterpolator(1.5f);
mWorkspace = workspace;
mWallpaperManager = WallpaperManager.getInstance(workspace.getContext());
mIsRtl = Utilities.isRtl(workspace.getResources());
}
@TargetApi(Build.VERSION_CODES.KITKAT)
private DefaultWallpaperInfo getDefaultWallpaper() {
File defaultThumbFile = getDefaultThumbFile();
Bitmap thumb = null;
boolean defaultWallpaperExists = false;
if (defaultThumbFile.exists()) {
thumb = BitmapFactory.decodeFile(defaultThumbFile.getAbsolutePath());
defaultWallpaperExists = true;
} else {
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 = saveDefaultWallpaperThumb(thumb);
}
}
if (defaultWallpaperExists) {
return new DefaultWallpaperInfo(new BitmapDrawable(thumb));
}
return null;
}