Set the wallpaper from code in Android

During android application you may need to set wallpaper using code, then you have to use following method.

public void setStream (InputStream data)

For that you need to include the following permission to your menifest file.

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

I’ve made the method that will directly set the wallpaper image specified in argument.

public void setWallpaper(String pathToImage)    {
    try {
        WallpaperManager wpm = WallpaperManager.getInstance(getApplicationContext());
	    InputStream ins = new URL("file://" + pathToImage).openStream();
	    wpm.setStream(ins);
	    Toast.makeText(getApplicationContext(), "Wallpaper has been set", Toast.LENGTH_SHORT).show();            
    } 
    catch (MalformedURLException e) {
        e.printStackTrace();
    } 
    catch (IOException e) {
        e.printStackTrace();
    }     
}

Here we have to specify “file://” which specify the protocol which we use here. We can also use http, ftp, etc. Otherwise it throws “java.net.MalformedURLException: Protocol not found: ” exception.

Get Date and Time in Android

In Android, to get time and date you have to first create the object of calender then you can format it using simpledateformat class according to your need. At last it returns you a date and time as per your format in String return type.

Here is the sample code for getting date and time as string.

Code :

public String getDateTime()	{
	Calendar c = Calendar.getInstance(); 
	SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
	return df.format(c.getTime());
}