Crash when using android setWallpaper method?
I get a photo with my camera (mobile phone) and then I need to set the wallpaper, but I had to dump. When I use it setWallpaper()
, it tells me The method setWallpaper(Bitmap) from the type Context is deprecated
. Here is my code:
public class Camera extends Activity implements View.OnClickListener {
ImageButton ib;
Button b;
ImageView iv;
Intent i;
final static int cameraData = 0;
Bitmap bmp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo);
initialize();
}
private void initialize() {
iv = (ImageView) findViewById(R.id.IVReturnedPic);
ib = (ImageButton) findViewById(R.id.IBTakePic);
b = (Button) findViewById(R.id.btnSetWall);
b.setOnClickListener(this);
ib.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.IBTakePic:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, cameraData);
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
I get an accident here setWallpaper()
:
getApplicationContext().setWallpaper(bmp);
Note: In this code, I am using View.OnClickListener
.
source to share
Try this way, hope it helps you solve your problem.
Declare the WallpaperManager object at the class level:
private WallpaperManager wallpaperManager;
Initialize the WallpaperManager object in initialize ():
private void initialize() {
wallpaperManager = WallpaperManager.getInstance(this);
}
Set the bitmap for the wallpaperManager object.
case R.id.btnSetWall:
try {
if(bmp!=null){
wallpaperManager.setBitmap(bmp);
}else{
// write your bitmap null handle code here.
}
} catch (IOException e) {
Log.e(TAG, "Cannot set image as wallpaper", e);
}
break;
Add this permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.SET_WALLPAPER" />
source to share
You need to use the WallpaperManager class if you are developing higher API level 5:
WallpaperManager mManager = WallpaperManager.getInstance(getApplicationContext());
try {
mManager.setResource(R.drawable.yourDrawable);
} catch (IOException e) {
//warning for the user
e.printStackTrace();
}
And in order to use the dispatcher, you need to set SET_WALLPAPER permissions in the manifest. Also, if you are developing to API level 5 and want to use the method you used, you must also set the permission.
source to share