直接加载服务端返回的图片地址,耗时较多。做开屏广告时,展示不及时。
开发思路,第一次不加载广告,把服务端数据存在SharePreferences,但存的仅是地址。并没有实现下载,再次读取仍然需要联网。特此粘出代码。
在我们应用的类里SaveImageActivity.java
public class SaveImageActivity extends AppCompatActivity {
private ImageView showImg;
private Button btn;
private String fileName = "openPicture";
private String pictureName = "ad_id";
String filePath = "http://www.ichong123.com/files/2016/8/11/44/7.jpg";//可以随意百度一个图片地址
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_save_image);
showImg = (ImageView) findViewById(R.id.showImg);
btn = (Button) findViewById(R.id.btn);
ImgDonwloads.donwloadImg(this, filePath, fileName, pictureName);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ImgDonwloads.getImg(fileName, pictureName) != null) {
showImg.setImageBitmap(ImgDonwloads.getImg(fileName, pictureName));
showImg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(SaveImageActivity.this, "点击", Toast.LENGTH_LONG).show();
}
});
}
}
});
}
}
activity_save_image.xml
布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击显示下载后的本地图片"/>
<ImageView
android:id="@+id/showImg"
android:layout_marginTop="13dp"
android:layout_width="match_parent"
android:layout_height="150dp" />
</LinearLayout>
工具类
ImgDonwloads.java
public class ImgDonwloads {
private static String urlPath;//网页路径
private static String filePath;//保存文件夹名
private static Bitmap mBitmap;
private static String mFileName;//保存文件名
private static String mSaveMessage;
private final static String TAG = "ImgDonwloads";
private static Context context;
private static ProgressDialog mSaveDialog = null;
static File appDir;
//下载图片
public static void donwloadImg(Context contexts, String url,String fileName ,String pictureName){
context = contexts;
urlPath = url;
filePath= fileName;
mFileName=pictureName;
mSaveDialog = ProgressDialog.show(context, "保存图片", "图片正在保存中,请稍等...", true);
new Thread(saveFileRunnable).start();//没有放线程会NetworkOnMainThreadException
}
private static Runnable saveFileRunnable = new Runnable(){
@Override
public void run() {
try {
byte[] data = getImage(urlPath);
if(data!=null){
mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
}else{
Toast.makeText(context, "Image error!", Toast.LENGTH_LONG).show();
}
saveImage(mBitmap,filePath,mFileName);
mSaveMessage = "Image success!";
} catch (IOException e) {
mSaveMessage = "Image error!";
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
messageHandler.sendMessage(messageHandler.obtainMessage());
}
};
private static Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mSaveDialog.dismiss();
Log.d(TAG, mSaveMessage);
Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show();
}
};
public static Bitmap getImg(String fileName , String pictureName){
appDir = new File(Environment.getExternalStorageDirectory(), fileName);
if (!appDir.exists()) {
appDir.mkdir();
}
if(TextUtils.isEmpty(pictureName)){
pictureName=mFileName;
}
//读取本地图片
Bitmap bitmap = null;
try{
File avaterFile = new File(appDir, pictureName+".jpg");
if(avaterFile.exists()) {
bitmap = BitmapFactory.decodeFile(appDir+"/"+pictureName+".jpg");
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* Get image from newwork
* @param path The path of image
* @return byte[]
* @throws Exception
*/
public static byte[] getImage(String path) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");
InputStream inStream = conn.getInputStream();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
return readStream(inStream);
}
return null;
}
/**
* Get data from stream
* @param inStream
* @return byte[]
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while( (len=inStream.read(buffer)) != -1){
outStream.write(buffer, 0, len);
}
outStream.close();
inStream.close();
return outStream.toByteArray();
}
public static void saveImage(Bitmap bmp, String fileName,String name) {
appDir = new File(Environment.getExternalStorageDirectory(), fileName);
if (!appDir.exists()) {
appDir.mkdir();
}
File file = new File(appDir, name+ ".jpg");
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();
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
}
}
在AndroidManifest.xml里面应该添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />