手机壁纸设置以及图片下载保存到本地

首先下载网络图片(权限自己处理)

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();
                    msg.what = i;
                    msg.arg1 = i; 
                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();

    }
}

 

你可能感兴趣的:(android)