上一篇:Android 高仿 扇贝 Splash 启动页 UI 篇,数据是程序里写死的,而扇贝的启动页 每天的图片是不同的,是通过每次启动的时候从服务端拉取数据的,我们也可以这样做,数据源可以用过必应来获取,接口:
数据信息:
{
"images": [{
"startdate": "20190708",
"fullstartdate": "201907081600",
"enddate": "20190709",
"url": "/th?id=OHR.JaguarPantanal_ZH-CN6062516404_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp",
"urlbase": "/th?id=OHR.JaguarPantanal_ZH-CN6062516404",
"copyright": "潘塔纳尔湿地的美洲豹,巴西 (© Andy Rouse/Minden Pictures)",
"copyrightlink": "https://www.bing.com/search?q=%E7%BE%8E%E6%B4%B2%E8%B1%B9&form=hpcapt&mkt=zh-cn",
"title": "",
"quiz": "/search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20190708_JaguarPantanal%22&FORM=HPQUIZ",
"wp": true,
"hsh": "732df6ef6bbf3713d1949cce81b5c68d",
"drk": 1,
"top": 1,
"bot": 1,
"hs": []
}],
"tooltips": {
"loading": "正在加载...",
"previous": "上一个图像",
"next": "下一个图像",
"walle": "此图片不能下载用作壁纸。",
"walls": "下载今日美图。仅限用作桌面壁纸。"
}
}
我们只需要获取images 里的数据即可。
创建ImageInfo:
public class ImageInfo extends LitePalSupport {
/**
* startdate : 20190708
* fullstartdate : 201907081600
* enddate : 20190709
* url : /th?id=OHR.JaguarPantanal_ZH-CN6062516404_1920x1080.jpg&rf=LaDigue_1920x1080.jpg&pid=hp
* urlbase : /th?id=OHR.JaguarPantanal_ZH-CN6062516404
* copyright : 潘塔纳尔湿地的美洲豹,巴西 (© Andy Rouse/Minden Pictures)
* copyrightlink : https://www.bing.com/search?q=%E7%BE%8E%E6%B4%B2%E8%B1%B9&form=hpcapt&mkt=zh-cn
* title :
* quiz : /search?q=Bing+homepage+quiz&filters=WQOskey:%22HPQuiz_20190708_JaguarPantanal%22&FORM=HPQUIZ
* wp : true
* hsh : 732df6ef6bbf3713d1949cce81b5c68d
* drk : 1
* top : 1
* bot : 1
* hs : []
*/
private String startdate;
private String fullstartdate;
private String enddate;
private String url;
private String urlbase;
private String copyright;
private String copyrightlink;
private String title;
private String quiz;
private boolean wp;
private String hsh;
private int drk;
private int top;
private int bot;
private String imagePath ;
@Column(ignore = true)
private List<?> hs;
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public String getStartdate() {
return startdate;
}
public void setStartdate(String startdate) {
this.startdate = startdate;
}
public String getFullstartdate() {
return fullstartdate;
}
public void setFullstartdate(String fullstartdate) {
this.fullstartdate = fullstartdate;
}
public String getEnddate() {
return enddate;
}
public void setEnddate(String enddate) {
this.enddate = enddate;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrlbase() {
return urlbase;
}
public void setUrlbase(String urlbase) {
this.urlbase = urlbase;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getCopyrightlink() {
return copyrightlink;
}
public void setCopyrightlink(String copyrightlink) {
this.copyrightlink = copyrightlink;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getQuiz() {
return quiz;
}
public void setQuiz(String quiz) {
this.quiz = quiz;
}
public boolean isWp() {
return wp;
}
public void setWp(boolean wp) {
this.wp = wp;
}
public String getHsh() {
return hsh;
}
public void setHsh(String hsh) {
this.hsh = hsh;
}
public int getDrk() {
return drk;
}
public void setDrk(int drk) {
this.drk = drk;
}
public int getTop() {
return top;
}
public void setTop(int top) {
this.top = top;
}
public int getBot() {
return bot;
}
public void setBot(int bot) {
this.bot = bot;
}
public List<?> getHs() {
return hs;
}
public void setHs(List<?> hs) {
this.hs = hs;
}
}
这里集成了郭霖的LitePal数据库:
拿到URL 拼接成:
"http://s.cn.bing.net"+URL
来下载图片。
封装网络:
添加网络权限:
<uses-permission android:name="android.permission.INTERNET"/>
封装Okhttp :
添加依赖:
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
封装成单例OkHttpManager:
public class OkHttpManager {
private static OkHttpManager okHttpManager ;
private OkHttpClient okHttpClient ;
private OkHttpManager()
{
okHttpClient = new okhttp3.OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.SECONDS)
.readTimeout(4,TimeUnit.SECONDS)
.build();
}
public static OkHttpManager getInstance()
{
if(okHttpManager == null)
{
synchronized (OkHttpManager.class)
{
if(okHttpManager == null)
{
okHttpManager = new OkHttpManager();
}
}
}
return okHttpManager ;
}
public void get(String url, Callback callback)
{
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(callback);
}
}
请求数据(ImageInfo)
private void getImage()
{
OkHttpManager.getInstance().get(GET_IMAGE_URL, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
JsonElement jsonElement = new JsonParser().parse(response.body().string());
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("images");
imageInfoList = new Gson().fromJson(jsonArray.toString(),new TypeToken<List<ImageInfo>>(){}.getType());
myHandler.sendEmptyMessage(DOWNLOAD_IMAGE);
}
});
}
请求到ImageList 数据后 ,在下载图片:
下载图片:
private void downLoadImage()
{
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
imagePath = getExternalFilesDir(null).getAbsolutePath()+"/"+simpleDateFormat.format(new Date())+"_splash.jpg";
String imageUrl = "http://s.cn.bing.net"+ imageInfoList.get(0).getUrl();
OkHttpManager.getInstance().get(imageUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
byte[] bytes = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = new FileOutputStream(imagePath);
while((len = inputStream.read(bytes)) != -1)
{
fileOutputStream.write(bytes,0,len);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
LitePal.deleteAll(ImageInfo.class);
ImageInfo imageBean = imageInfoList.get(0);
imageBean.setImagePath(imagePath);
imageBean.save();
}
});
}
下载图片后保存数据库,下次启动Splash 界面从数据库里取值:
启动获取数据:
ImageInfo imageInfo = LitePal.findFirst(ImageInfo.class);
if(imageInfo != null)
{
Glide.with(this).load(imageInfo.getImagePath()).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
}
展示,第一次启动:
获取网络图片后展示:
完整代码:
MainActivity:
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
/**
* 图片获取地址
*/
private String GET_IMAGE_URL = "https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1";
private List<ImageInfo> imageInfoList ;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_home:
mTextMessage.setText(R.string.title_home);
return true;
case R.id.navigation_dashboard:
mTextMessage.setText(R.string.title_dashboard);
return true;
case R.id.navigation_notifications:
mTextMessage.setText(R.string.title_notifications);
return true;
}
return false;
}
};
private static class MyHandler extends Handler
{
private WeakReference<MainActivity> weakReference ;
public MyHandler(MainActivity activity)
{
weakReference = new WeakReference<MainActivity>(activity);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case DOWNLOAD_IMAGE:
MainActivity mainActivity = weakReference.get();
if (mainActivity != null) {
mainActivity.downLoadImage();
}
break;
}
}
}
private MyHandler myHandler ;
private static final int DOWNLOAD_IMAGE = 1024 ;
/**
* 图片下载地址
*/
private String imagePath ;
private SimpleDateFormat simpleDateFormat ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myHandler = new MyHandler(this);
mTextMessage = (TextView) findViewById(R.id.message);
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
getImage();
}
private void getImage()
{
OkHttpManager.getInstance().get(GET_IMAGE_URL, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
JsonElement jsonElement = new JsonParser().parse(response.body().string());
JsonObject jsonObject = jsonElement.getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("images");
imageInfoList = new Gson().fromJson(jsonArray.toString(),new TypeToken<List<ImageInfo>>(){}.getType());
myHandler.sendEmptyMessage(DOWNLOAD_IMAGE);
}
});
}
private void downLoadImage()
{
simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
imagePath = getExternalFilesDir(null).getAbsolutePath()+"/"+simpleDateFormat.format(new Date())+"_splash.jpg";
String imageUrl = "http://s.cn.bing.net"+ imageInfoList.get(0).getUrl();
OkHttpManager.getInstance().get(imageUrl, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream inputStream = response.body().byteStream();
byte[] bytes = new byte[1024];
int len = 0;
FileOutputStream fileOutputStream = new FileOutputStream(imagePath);
while((len = inputStream.read(bytes)) != -1)
{
fileOutputStream.write(bytes,0,len);
}
fileOutputStream.flush();
fileOutputStream.close();
inputStream.close();
LitePal.deleteAll(ImageInfo.class);
ImageInfo imageBean = imageInfoList.get(0);
imageBean.setImagePath(imagePath);
imageBean.save();
}
});
}
}
SplashActivity:
public class SplashActivity extends AppCompatActivity {
private ImageView imageView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
imageView = findViewById(R.id.image);
ImageInfo imageInfo = LitePal.findFirst(ImageInfo.class);
if(imageInfo != null)
{
Glide.with(this).load(imageInfo.getImagePath()).diskCacheStrategy(DiskCacheStrategy.ALL).into(imageView);
}
/* Animation animation = AnimationUtils.loadAnimation(this,R.anim.scale);
imageView.startAnimation(animation);*/
AnimatorSet set = new AnimatorSet();
//ObjectAnimator.ofFloat(imageView, "scaleX", 1f, 1.12f)
set.playTogether(
ObjectAnimator.ofFloat(imageView,"alpha",0.88f,1f),
ObjectAnimator.ofFloat(imageView, "scaleX", 1f, 1.12f),
ObjectAnimator.ofFloat(imageView, "scaleY", 1f, 1.12f)
);
set.setDuration(2500);
set.start();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
}
},3000);
}
}
权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
依赖:
implementation 'com.github.bumptech.glide:glide:4.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'org.litepal.android:java:3.0.0'