Android 用线程更换壁纸

2021-09-24 12:27:35 浏览数 (1)

先看效果:

一个线程30行代码搞定:

代码语言:javascript复制
public class MainActivity extends Activity {
    Thread thread = new Thread(){
        @Override
        public void run() {
            for (;current<5;){
                if (current >= 3) {
                    current = 0;
                }
                //使用资源文件  当然你也可以使用其他图片bitmap
                BitmapDrawable bitmap = (BitmapDrawable) getResources().getDrawable(wallpapers[current  ]);
                wallpaperManager = WallpaperManager.getInstance(MainActivity.this);
                try {
                    wallpaperManager.setBitmap(bitmap.getBitmap());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    int[] wallpapers = new int[]{
            R.drawable.background1, R.drawable.background2, R.drawable.background3
    };
    WallpaperManager wallpaperManager;
    int current = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        thread.start();
    }
}

就这么简单 对了别忘了在mainfest里加权限

代码语言:javascript复制
<!--授予用户修改壁纸权限-->
    <uses-permission android:name="android.permission.SET_WALLPAPER" />

0 人点赞