1. 程式人生 > >手機桌布設定以及圖片下載儲存到本地

手機桌布設定以及圖片下載儲存到本地

首先下載網路圖片(許可權自己處理)

public Bitmap GetImageInputStream(final String imageurl, final int i) { //i根據自己的業務做的處理 

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                HttpURLConnection connection = null;
                url = new URL(imageurl);
                connection = (HttpURLConnection) url.openConnection();
                connection.setConnectTimeout(6000);
                connection.setDoInput(true);
                connection.setUseCaches(false);
                InputStream inputStream = connection.getInputStream();

                bitmap = BitmapFactory.decodeStream(inputStream);
                inputStream.close();
                Message msg = new Message();
                if (i == 1) {    
                    msg.what = 1;
                    msg.arg1 = 1;
                } else {
                    msg.what = 2;
                    msg.arg1 = 2;
                }

                handler.sendMessage(msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();

    return bitmap;
}

然後是儲存網路圖片到本地     //這個也是自己的業務需求所要,一般拿到biamap就可以直接設定桌布

public static int saveImageToPhotos(Context context, Bitmap bmp) {
    // 首先儲存圖片
    File appDir = new File(Environment.getExternalStorageDirectory(), "WuFanWallPager");
    if (!appDir.exists()) {
        appDir.mkdir();
    }
    String fileName = System.currentTimeMillis() + ".jpg";
    File file = new File(appDir, fileName);
    try {
        FileOutputStream fos = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // 其次把檔案插入到系統圖庫
    try {
        MediaStore.Images.Media.insertImage(context.getContentResolver(),
                file.getAbsolutePath(), fileName, null);
    } catch (FileNotFoundException e) {
        e.printStackTrace();

        return 1;
    }
    // 最後通知相簿更新
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri uri = Uri.fromFile(file);
    intent.setData(uri);
    context.sendBroadcast(intent);
    return 2;
}

最後 設定 桌布:     

WallpaperManager manager = WallpaperManager.getInstance(context);
manager.setBitmap(bitmap);

即可。

當然到最後還有設定桌布成功的廣播:

WallpaperIntentReceiver server;
private void registerIntentReceivers() {    //註冊廣播
   if (server==null){
       server=new WallpaperIntentReceiver();
       IntentFilter filter=new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED);
       registerReceiver(server,filter);
   }
}

接收的廣播

public class WallpaperIntentReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e("TAG", "換了桌布!!");
        Toast.makeText(context, "我換了桌布", Toast.LENGTH_SHORT).show();

    }
}