设置壁纸

 public class MainActivity extends Activity {

    
    private Bitmap mWallpaper;
    private TextView tv=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv=(TextView)this.findViewById(R.id.setWallPaper);
        setWallPaper();
        
    }
    
    public void setWallPaper(){
        WallpaperManager wpm = (WallpaperManager) this.getSystemService(Context.WALLPAPER_SERVICE);
        InputStream is = null;
        is = getStream("wallpapers/wallpaper02.jpg");
        if(wpm.getWallpaperInfo()!=null){
            mWallpaper = Tools.getImageFromInStream(is);
            try {
                wpm.setBitmap(mWallpaper);
                mWallpaper.recycle();
                mWallpaper = null;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
         
        }
    }
    public InputStream getStream(String filename) {
        InputStream stream = null;
        try {
            stream = this.getAssets().open(getFileForDpi(filename));
        } catch (IOException e) {
            try {
                stream = this.getAssets().open("theme/" + filename);
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }
        return stream;
    }
    
    public String getFileForDpi(String filename) {
        float mScreenScale = this.getResources().getDisplayMetrics().density;
        if (mScreenScale <= 0.75f) {
            Log.d("launcher", "dpi=0.75");
            filename = "theme-ldpi/" + filename;
        } else if (mScreenScale <= 1f) {
            Log.d("launcher", "dpi=1");
            filename = "theme-mdpi/" + filename;
        } else if (mScreenScale <= 1.5f) {
            Log.d("launcher", "dpi=1.5");
            filename = "theme-hdpi/" + filename;
        } else
            filename = "theme-xhdpi/" + filename;
        return filename;
    }
}

 注意:需要增加权限:<uses-permission android:name="android.permission.SET_WALLPAPER" />

posted @ 2013-03-22 13:34  mogul  阅读(256)  评论(0编辑  收藏  举报