Android笔记:通过代码设置系统壁纸

来源:互联网 发布:java编程框架 编辑:程序博客网 时间:2024/06/05 08:52

项目中可能用到,上网上看了一些资料,整理了一下贴出来供以后自己使用,有用的拿走,不谢,
首先必须的设置权限,否则程序会崩:
允许程序设置壁纸的权限

 <uses-permission android:name="android.permission.SET_WALLPAPER"/>

代码比较简单:
testActivity代码:

package com.dfwy.cxy.picdemo;import android.app.Activity;import android.app.WallpaperManager;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.drawable.BitmapDrawable;import android.os.Bundle;import android.os.PersistableBundle;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.IOException;/** * Created by cxy on 2016/12/14. */public class Test extends Activity {    private Button btn_test;    private Bitmap bitmap;    private ImageView iv;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.suo);        btn_test = (Button) findViewById(R.id.button);        //把指定的图片转换成bitmap        bitmap = BitmapFactory.decodeResource(this.getResources(),R.mipmap.tableback);        btn_test.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                WallpaperManager manager = WallpaperManager.getInstance(Test.this);                try {                    manager.setBitmap(bitmap);                    Toast.makeText(Test.this,"更改壁纸成功",Toast.LENGTH_SHORT).show();                } catch (IOException e) {                    e.printStackTrace();                    Toast.makeText(Test.this,"设置失败",Toast.LENGTH_SHORT).show();                }            }        });    }}

布局代码:

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:textColor="@color/colorWhite"        android:background="@color/colorBlue"        android:text="更换壁纸"        android:layout_margin="20dp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/button"        android:layout_weight="1" /></RelativeLayout>
0 0
原创粉丝点击