Android set wallpaper

In this Android tip, I am going to provide you an example of setting wallpaper programmatically. The user can select an image from file explorer, or send an image from another application or from browser. The image received is set as the background of activity of the example application. The Set As Wallpaper button is clicked to set the image as wallpaper.
In Android, it is simple to set an image as the wallpaper of an Android device. You can use setBitmap(), setResource(), or setStream() method of WallpaperManager class to achieve this goal. You have to pass a Bitmap object to the setBitmap(). The setResource() method accepts an resource id pointing to a local image stored in res/drawable folder. The setStream() method allows you pass an InputStream object. Before the image is loaded effectively into a container of your application, it should be decoded. You can use methods of BitmapFactory to decode the image. Every decoding method of the BitmapFactory returns a Bitmap object. So, in this example, I use setBitmap() method to set the decoded bitmap as the wallpaper.
Now to have an example application on setting wallpaper, you create an Android project called AsWallpager. Then add a TextView and a Button to the activity_main.xml file.



<RelativeLayout xmlns:android= "http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context= "com.example.aswallpaper.MainActivity"
   android:id="@+id/layoutparent"
   >
<TextView
     android:id="@+id/txtmessage"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:text="Loading image..."
     android:padding="15dp"
  
     />
   <Button
     android:id="@+id/btsetwbtallpager"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Set As Wallpaper"
     android:layout_centerInParent= "true"
     />

</RelativeLayout>


In the AndroidManifest.xml file, you need to add INTERNET and SET_WALLPAPER permissions. You also have to define two intent-filters. One is to match an intent that contains image link shared from browser. Another intent-filter is to match an intent that points to an image which is selected from file browser or sent from other applications. In code, you see different approaches to get the image sent from the different sources.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
   package="com.example.aswallpaper"
   android:versionCode="1"
   android:versionName="1.0" >

   <uses-sdk
     android:minSdkVersion="8"
     android:targetSdkVersion="21" />
   <uses-permission android:name="android.permission.SET_WALLPAPER" />
<uses-permission android:name="android.permission.INTERNET"/>
   <application
     android:allowBackup="true"
     android:icon="@drawable/ic_launcher"
     android:label="@string/app_name"
     android:theme="@style/AppTheme" >
     <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
           <action android:name="android.intent.action.MAIN" />
           <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
<data android:host="*"/>

</intent-filter>
        <intent-filter>
<action android:name="android.intent.action.VIEW"/>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>

</intent-filter>
        
     </activity>
   </application>

</manifest>


Here is the code written in the MainActivity class to receive the image sent from web browser, selected from file explorer, and sent from other applications (e.g. Gallery). The image is decoded before loading to the application and setting it as the wallpaper.

package com.example.aswallpaper;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.support.v7.app.ActionBarActivity;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

public class MainActivity extends ActionBarActivity {

Activity context;
Bitmap bitmap=null;
Intent intent;
Button bt;
TextView txtMessage;
int screenWidth;
int screenHeight;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
DisplayMetrics metrics=new DisplayMetrics();
     // Get screen size (width and height)
     this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
     screenWidth=metrics.widthPixels;
     screenHeight=metrics.heightPixels;
txtMessage=(TextView)findViewById(R.id.txtmessage);
txtMessage.setVisibility(TextView.GONE);  
bt=(Button)findViewById(R.id.btsetwbtallpager);
   bt.setOnClickListener(new OnClickListener(){
   public void onClick(View view){
   // Create WallpaperManager instance
         WallpaperManager wallpaperManager=WallpaperManager.getInstance(context);
        
         try {
         // Set the image as wallpaper
         if(bitmap!=null)
         wallpaperManager.setBitmap(bitmap);        
         else
         Toast.makeText(context, "No image was chosen.", Toast.LENGTH_LONG).show();
         } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
       
   }
   });
// Get intent object
     intent=getIntent();
     // Get action
     String action=intent.getAction();
     // Get mineType
     String type =intent.getType();
    
      // User shared image link from browser.
      // Get image uri from the intent
     if(Intent.ACTION_SEND.equals(action) && type.startsWith("text/plain")){
     BackTask task=new BackTask();
     task.execute(intent.getStringExtra(Intent.EXTRA_TEXT));
     //Log.e("Main",intent.getStringExtra(Intent.EXTRA_TEXT));
    
     }
     else if(Intent.ACTION_VIEW.equals(action) && type.startsWith("image/")){
    
     // URI of the image data
           Uri imgURI=intent.getData();
           // From the URI, create Bitmap object
           try {
     bitmap=decodeBitmap(context.getContentResolver().openInputStream(imgURI),getDimension(context.getContentResolver().openInputStream(imgURI)));
     setAsBackGround(bitmap);
     } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
          
      
     }
     // User shared an image from another application (e.g. Gallery).
     // Get image stream from the intent
     else if(Intent.ACTION_SEND.equals(action) && type.startsWith("image/")){
     Uri imgURI = (Uri) intent.getExtras().get(Intent.EXTRA_STREAM);
     // From the URI, create Bitmap object
           try {
     bitmap=decodeBitmap(context.getContentResolver().openInputStream(imgURI),getDimension(context.getContentResolver().openInputStream(imgURI)));
        
           setAsBackGround(bitmap);
     } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     }
     }
    
    
               
    
  
}

@SuppressLint("NewApi")
public void setAsBackGround(Bitmap bitmap){
// Convert the Bitmap object to be used in the setBackground and setBackgroundDrawable methods
   Drawable drawable =new BitmapDrawable(getResources(),bitmap);
   // Reference to the parent layout of activity
RelativeLayout layoutparent = (RelativeLayout) findViewById(R.id.layoutparent);
// Set the image to the background of the activity
// The setBackgroundDrawable is deprecated in API level 16.
// So check API level before calling the methods
if(android.os.Build.VERSION.SDK_INT>=16)
layoutparent.setBackground(drawable);

else
layoutparent.setBackgroundDrawable(drawable);
}

// AsynnTask to run the zip file extraction in background
   private class BackTask extends AsyncTask<String,Void,Bitmap>{
  
   protected void onPreExecute(){
   bt.setVisibility(Button.GONE);
   txtMessage.setVisibility(TextView.VISIBLE);
  
   }
   protected Bitmap doInBackground(String...params){
   bitmap=decodeBitmap(getInputStream(params[0]),getDimension(getInputStream(params[0])));
   Log.e("Width=", bitmap.getWidth()+"");
   return bitmap;


   }
   protected void onPostExecute(Bitmap result){
   setAsBackGround(result);
   txtMessage.setVisibility(TextView.GONE);
   bt.setVisibility(Button.VISIBLE);
  
   }
  
   }

// Get InputStream to read image data from the internet
private InputStream getInputStream(String address){

   try {
   // Get InputStream from the image url
   URL url = new URL(address);
   HttpURLConnection connection = (HttpURLConnection) url.openConnection();
   connection.setDoInput(true);
   connection.connect();
   return connection.getInputStream();
   }
   catch(IOException e){
   Log.e("Thread",e.getMessage());
   return null;
   }
   }

private Bitmap decodeBitmap(InputStream is, Dimension ds){

int sampleSize=1;
// Calculate the sample size
if(screenWidth< ds.width || screenHeight<ds.height ){
int widthRatio=Math.round(ds.width/(float)screenWidth);
int heightRatio=Math.round(ds.height/(float)screenHeight);
sampleSize=Math.round((widthRatio+heightRatio)/(float)2);

}

// Decode the image with the specified sample size
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize=sampleSize;
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options);
return bitmap;

}
private Dimension getDimension(InputStream is){
// Decode image (without loading it in memory) to get its size
// The size will be used to calculate a sample size used in decode the image
final BitmapFactory.Options options = new BitmapFactory.Options();  
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
return new Dimension(options.outWidth,options.outHeight);
}
private class Dimension{
int width;
int height;
Dimension(int w,int h){
width=w;
height=h;
}
}
}

Android-set-wallpaper

Posted by: Dara | post date: 11-23-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.