I have an app in which the user can set the image view in any fragment as wallpaper using an action bar item. I am using the following code for this:
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.action_wall:
{
WallpaperManager wm=WallpaperManager.getInstance(getActivity().getApplicationContext());
try{
wm.setBitmap(bmg1);
Toast.makeText(getActivity().getBaseContext(), "Wallpaper set successfully",Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
Toast.makeText(getActivity().getBaseContext(), "Wallpaper not set successfully",Toast.LENGTH_SHORT).show();
}
}
}
return false;
}
The problem I am facing is that when user clicks on the menu item, the app hangs for a few seconds before showing the toast and setting wallpaper. I am aware that we can use async task to solve this though i am not sure how exactly it can be used here. Please help me out regarding this. Thanks
EDIT: Here is my async task code:
class ImageTask extends AsyncTask<Void, Void, Void>
{
Context c;
ProgressDialog pd;
public ImageTask(Context ctx)
{
this.c=ctx;
}
@Override
protected void onPreExecute()
{
pd=ProgressDialog.show(c, "Please Wait", "Setting Wallpaper...");
}
public void onPostExecute()
{
pd.dismiss();
Toast.makeText(c, "Wallpaer set successfully", Toast.LENGTH_SHORT).show();
}
protected Void doInBackground(Void... params) {
WallpaperManager wm1=WallpaperManager.getInstance(c);
try {
wm1.setBitmap(ImageFrag1.bmg1);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
}