实现逻辑:
- 首先获取本地图库图片的绝对路径URL,保存;
- 通过图片的绝对路径转成bitmap;
- 设背景,结束。
权限:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
Intent getAlbum = new Intent(Intent.ACTION_GET_CONTENT);
getAlbum.setType(IMAGE_TYPE);
startActivityForResult(getAlbum, IMAGE_CODE);
重写onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) { // 此处的 RESULT_OK 是系统自定义得一个常量
Log.e("TAG->onresult", "ActivityResult resultCode error");
return;
}
ContentResolver resolver = getContentResolver();
if (requestCode == IMAGE_CODE) {
try {
Uri originalUri = data.getData(); // 获得图片的uri
MediaStore.Images.Media.getBitmap(resolver, originalUri);
String[] proj = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(originalUri, proj, null, null,
null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
SharedPreferences preferences = getSharedPreferences("PATH",
Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("path", path.trim());
editor.commit();
Toast.makeText(getApplicationContext(), "修改成功,重启应用方可生效!",
Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Log.e("TAG-->Error", e.toString());
}
}
super.onActivityResult(requestCode, resultCode, data);
}
设背景代码
private void setBackground() {
new Thread(new Runnable() {
public void run() {
SharedPreferences preferences = getSharedPreferences("PATH",
Context.MODE_PRIVATE);
String path = preferences.getString("path", "");
File file = new File(path);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(path);
Resources resources = getResources();
BitmapDrawable drawable = new BitmapDrawable(resources,
bitmap);
handler.sendMessage(handler.obtainMessage(7, drawable));
} else {
Resources resources = getResources();
Drawable btnDrawable = resources
.getDrawable(R.drawable.background_1);
handler.sendMessage(handler.obtainMessage(7, btnDrawable));
}
}
}).start();
}
handler 7:
linear_background.setBackgroundDrawable((Drawable) msg.obj);