public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView Image;
private Button Get_Image_Btn;
private ImageView Image_Two;
private ImageView mLocalImage;
private Button mLocalBtn;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bitmap bit = (Bitmap) msg.obj;
Image.setImageBitmap(bit);
mPhone.putImage(ImageUrls.imageUrls[1], bit);
try {
mLocal.putImage(ImageUrls.imageUrls[1], bit);
} catch (Exception e) {
e.printStackTrace();
}
}
};
private PhoneCache mPhone;
private LocalCache mLocal;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//手机内存
mPhone = new PhoneCache(MainActivity.this);
//本地内存
mLocal = new LocalCache();
initView();
Bitmap bit = mPhone.getImage(ImageUrls.imageUrls[1]);
if (bit != null) {
} else {
try {
bit = mLocal.getImage(ImageUrls.imageUrls[1]);
if (bit != null) {
} else {
getImage();
}
} catch (Exception e) {
e.printStackTrace();
}
}
// getImage();
}
private void getImage() {
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(ImageUrls.imageUrls[1]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = new Message();
msg.obj = bitmap;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
private void initView() {
Image = (ImageView) findViewById(R.id.Image);
Get_Image_Btn = (Button) findViewById(R.id.Get_Image_Btn);
Image_Two = (ImageView) findViewById(R.id.Image_Two);
mLocalImage = (ImageView) findViewById(R.id.Local_Image);
mLocalBtn = (Button) findViewById(R.id.Local_Btn);
mLocalBtn.setOnClickListener(this);
Get_Image_Btn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Get_Image_Btn:
Bitmap image = mPhone.getImage(ImageUrls.imageUrls[1]);
Image_Two.setImageBitmap(image);
break;
case R.id.Local_Btn:
try {
Bitmap image1 = mLocal.getImage(ImageUrls.imageUrls[1]);
mLocalImage.setImageBitmap(image1);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}