如何在android中永久设置壁纸

Posted

技术标签:

【中文标题】如何在android中永久设置壁纸【英文标题】:How to set wallpaper permanently in android 【发布时间】:2014-05-28 00:35:50 【问题描述】:

我正在创建应用程序以将图像设置为墙纸。我正在使用以下代码来修复每个屏幕中的图像。代码工作正常。图像适合。但是如果我玩任何游戏然后回到主屏幕或者我重新启动我的设备然后壁纸缩放大小,我就会遇到一个问题。我想阻止这一切。我希望图像尺寸适合我第一次从我的 android 应用设置壁纸时的尺寸。

这是代码-

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.full_image);
        face = Typeface.createFromAsset(getAssets(), "fonts/ABEAKRG.TTF");
        Intent i = getIntent();
        position = i.getExtras().getInt("id");        
        full = (LinearLayout) findViewById(R.id.full);
        btn = (Button)findViewById(R.id.btn);
        btn.setTypeface(face);
        btn.setOnClickListener(new Button.OnClickListener()
        @Override
        public void onClick(View arg0)  
             DisplayMetrics metrics = new DisplayMetrics(); 
             getWindowManager().getDefaultDisplay().getMetrics(metrics);
             int height = metrics.heightPixels; 
             int width = metrics.widthPixels;
             Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), mThumbId[position]);
             Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
             WallpaperManager wallpaperManager = WallpaperManager.getInstance(FullImageActivity.this); 
             wallpaperManager.setWallpaperOffsetSteps(1, 1);
             wallpaperManager.suggestDesiredDimensions(width, height);
             try 
               wallpaperManager.setBitmap(bitmap);
               Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
                catch (IOException e) 
               e.printStackTrace();
             
        );
        changeBackground();
        ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
        full.setOnTouchListener(activitySwipeDetector);
    



    private void changeBackground()
        full.setBackgroundResource(mThumbId[position]);
   

提前致谢。

【问题讨论】:

【参考方案1】:

这是为此工作的代码段

MainActivity.java Code

开机后设置壁纸的BootReceiver.java..Code

Manifest.xml 用于设置权限..Code

谢谢

【讨论】:

【参考方案2】:

昨天我完成了这项任务..从画廊或通过相机获取图像并将其设置为墙纸。 为此,我确实喜欢这个。 首先从图库或相机中获取图像。 第二次根据您的需要适当地压缩或重新缩放它。 第三,将该图像保存在 sharedpreferences 中,这样如果图像从图库或手机内存中删除,即使在这种情况下,它也会像墙纸一样。 最后在活动的 onCreate 方法中将图片设置为墙纸。

public class Util 


public static final String PREFERENCES_NAME = "prefs";
public static SharedPreferences getSharedPreference(Context context) 
    return context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
     
public static String getBackgroundImagePath(Context context) 
    return getSharedPreference(context).getString("imagepath","");


public static void setBackgroundImagePath(Context context, String path) 
    Editor edit = getSharedPreference(context).edit();
    edit.putString("imagepath", path);
    edit.commit();

通过传递字符串路径和上下文从活动中调用此 setBackgroundImagePath 方法。像这样 //你的图片路径

 String path = "";
 Util.setBackgroundImagePath(getApplicationContext(), path);

来自活动的onCreate(),

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.full_image);
    face = Typeface.createFromAsset(getAssets(), "fonts/ABEAKRG.TTF");
    Intent i = getIntent();
    position = i.getExtras().getInt("id");        
    full = (LinearLayout) findViewById(R.id.full);
    btn = (Button)findViewById(R.id.btn);
    btn.setTypeface(face);
 Bitmap path = StringToBitMap(Util.getBackgroundImagePath(getApplicationContext()));
    if (path != null) 
        full.setBackgroundDrawable(new BitmapDrawable((path))); 
    else 
        full.setBackgroundDrawable(R.drawable.defaultImage);
    
    btn.setOnClickListener(new Button.OnClickListener()
    @Override
    public void onClick(View arg0)  
         DisplayMetrics metrics = new DisplayMetrics(); 
         getWindowManager().getDefaultDisplay().getMetrics(metrics);
         int height = metrics.heightPixels; 
         int width = metrics.widthPixels;
         Bitmap tempbitMap = BitmapFactory.decodeResource(getResources(), mThumbId[position]);
         Bitmap bitmap = Bitmap.createScaledBitmap(tempbitMap,width,height, true);
     full.setBackgroundDrawable(new BitmapDrawable((bitmap)));  
         String image_path = BitMapToString(bitmap);
         Util.setBackgroundImagePath(getApplicationContext(),image_path);
         WallpaperManager wallpaperManager= WallpaperManager.getInstance(FullImageActivity.this); 
         wallpaperManager.setWallpaperOffsetSteps(1, 1);
         wallpaperManager.suggestDesiredDimensions(width, height);
         try 
           wallpaperManager.setBitmap(bitmap);
           Toast.makeText(getApplicationContext(), "Done", Toast.LENGTH_SHORT).show();
            catch (IOException e) 
           e.printStackTrace();
         
    );
    ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
    full.setOnTouchListener(activitySwipeDetector);

public Bitmap StringToBitMap(String encodedString)
    try
        byte [] encodeByte=Base64.decode(encodedString,Base64.DEFAULT);
        Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
        return bitmap;
    catch(Exception e)
        e.getMessage();
        return null;
    

public String BitMapToString(Bitmap bitmap)
    ByteArrayOutputStream baos=new  ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
    byte [] b=baos.toByteArray();
    String temp=Base64.encodeToString(b, Base64.DEFAULT);
    return temp;

我在这里设置背景布局 如果您有疑问..问 希望对你有帮助

【讨论】:

我知道我必须使用 sharedpreferences 但不知道如何将图像保存在 sharedpreferences 中。请告诉我如何保存? 这段代码对我来说有点混乱。你能告诉我我必须在我的代码中的哪里添加这个代码吗?查看更新。 你能告诉我我必须在我的代码中的什么地方添加这个代码吗? 我收到错误返回 getSharedPreference(context).getString("imagepath","");在utill类中。 它在解决方案中的显示创建 getSharedPreference 方法。【参考方案3】:

试试这个把图片设置为墙纸

   try 
        WallpaperManager myWallpaperManager = WallpaperManager
                .getInstance(context);

        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        int fullWidth = size.x;
        int fullHeight = size.y;

        // int fullWidth = wManager.getDesiredMinimumWidth();
        // int fullHeight = wManager.getDesiredMinimumHeight();

        Log.d("Debug", Integer.toString(fullWidth));
        Log.d("Debug", Integer.toString(fullHeight));

        Bitmap bitmap = BitmapFactory.decodeStream(getResources()
                .openRawResource(R.drawable.hello));

        Bitmap bitmapResized = Bitmap.createScaledBitmap(bitmap, fullWidth,
                fullHeight, true);
        myWallpaperManager.suggestDesiredDimensions(
                bitmapResized.getWidth(), bitmapResized.getHeight());

        myWallpaperManager.setBitmap(bitmapResized);

     catch (IOException e) 
        e.printStackTrace();
    

图像在哪里 hello(R.drawable.hello)...

【讨论】:

【参考方案4】:

前段时间我开始开发一个应用程序来自动更换壁纸。我没有你说的问题。关键代码如下,或许对你有帮助。

我认为唯一的区别是我在getRandomFile中随机选择了一张壁纸。在gitHub查看整个应用程序可能更容易,虽然更换壁纸的班级是this

private void changeWallPaper(int h, int w)
    String path = getRandomFile();
    Bitmap bm = decodeSampledBitmapFromFile(path, w, h);

    try 
        WallpaperManager mywall = WallpaperManager.getInstance(this);
        Log.i(MainActivity.TAG, "Setting wallpaper to " + path);
        mywall.setBitmap(bm);
     catch (IOException e) 
        Log.e(MainActivity.TAG, "Cannot set image as wallpaper", e);
    


public static Bitmap decodeSampledBitmapFromFile(String path, int width, int height) 

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(path, options);
    //String imageType = options.outMimeType;

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, width, height);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeFile(path, options);

/**
 * 
 * @param options
 * @param reqWidth
 * @param reqHeight
 * @return int
 * @see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
 */
public static int calculateInSampleSize(BitmapFactory.Options options,
        int reqWidth, int reqHeight) 
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) 

        // Calculate ratios of height and width to requested height and
        // width
        final int heightRatio = Math.round((float) height
                / (float) reqHeight);
        final int widthRatio = Math.round((float) width / (float) reqWidth);

        // Choose the smallest ratio as inSampleSize value, this will
        // guarantee
        // a final image with both dimensions larger than or equal to the
        // requested height and width.
        inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
    
    Log.d(MainActivity.TAG, " in sample Size: " + inSampleSize);
    return inSampleSize;

【讨论】:

以上是关于如何在android中永久设置壁纸的主要内容,如果未能解决你的问题,请参考以下文章

android如何通过代码设置锁屏壁纸

Android自定义动态壁纸开发

仅设置 Android 主屏幕壁纸

如何在 Android 11 中检测权限的永久拒绝?

如何为 Android 动态壁纸创建设置活动

设置 iPhone 和 Android 的壁纸 - Appcelerator