最近在做公司的东西,需要加入广告,之前也加得有广告,但是由于是第三方提供的SDK,鉴于项目需求,后台就写了一个广告系统,这样客户端就得改了。花了一点时间,把广告的Banner实现了,这里面主要牵涉到了一些简单的知识,异步下载(图片和APK文件)
以及安装下载完成的APK,下面直接上代码吧。
//一些简单的变量 可以根据你个人情况选择
private ViewPager viewPager; // android-support-v4中的滑动组件
private List<ImageView> imageViews; // 滑动的图片集合
private List<View> dots; // 图片标题正文的那些点
private int currentItem = 0; // 当前图片的索引号
private ScheduledExecutorService scheduledExecutorService;
private int len = 0;
private final String SAVE_PATH = Environment.getExternalStorageDirectory()
+ "/cheesedownload/";
private RelativeLayout adsLayout;
private RelativeLayout ads_banner;
// 切换当前显示的图片
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
viewPager.setCurrentItem(currentItem);// 切换当前显示的图片
};
};
//异步实现加载广告
class ShowAdsTask extends AsyncTask<String, Integer, String> {
List<AdsBean> list;
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
list = DataFetcher.getAds(context, "banner");
if (list != null && list.size() != 0) {
ads_banner.setVisibility(View.VISIBLE);
adsLayout.setVisibility(View.VISIBLE);
showAds(list);
}
}
//广告显示函数
private void showAds(final List<AdsBean> list) {
imageViews = new ArrayList<ImageView>();
for (int i = 0; i < list.size(); i++) {
final int index = i;
len = list.get(index).getAdsCount();
ImageView imageView = new ImageView(this);
Bitmap bitmap = downloadAdsPic(list.get(index).getAdsPicUrl());
imageView.setImageBitmap(bitmap);
imageView.setScaleType(ScaleType.CENTER_CROP);
imageView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
DownloadApkTask task = new DownloadApkTask(list.get(index)
.getAdsApkUrl(), list.get(index).getAdsName());
task.execute("");
}
});
imageViews.add(imageView);
}
dots = new ArrayList<View>();
LinearLayout layout = (LinearLayout) findViewById(R.id.ads_viewpage);
for (int i = 0; i < len; i++) {
View view = new View(this);
layout.addView(view);
dots.add(view);
}
viewPager = (ViewPager) findViewById(R.id.vp);
viewPager.setAdapter(new MyAdapter());// 设置填充ViewPager页面的适配器
// 设置一个监听器,当ViewPager中的页面改变时调用
viewPager.setOnPageChangeListener(new MyPageChangeListener());
}
/**
* 打开安装apk
*/
private Handler downloadHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if (msg.what == 1) {
openFile(new File(SAVE_PATH + msg.obj + ".apk"));
}
}
};
/**
* 广告apk下载task
*
*/
class DownloadApkTask extends AsyncTask<String, Integer, String> {
String urlPath;
String name;
public DownloadApkTask(String urlPath, String name) {
// TODO Auto-generated constructor stub
this.urlPath = urlPath;
this.name = name;
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
apkDownload(urlPath, name);
Message msg = downloadHandler.obtainMessage();
msg.what = 1;
msg.obj = name;
downloadHandler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
// 当Activity显示出来后,每两秒钟切换一次图片显示
scheduledExecutorService.scheduleAtFixedRate(new ScrollTask(), 1, 2,
TimeUnit.SECONDS);
super.onStart();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
scheduledExecutorService.shutdown();
}
/**
* 换行切换任务
*
* @author Administrator
*
*/
private class ScrollTask implements Runnable {
public void run() {
synchronized (viewPager) {
currentItem = (currentItem + 1) % imageViews.size();
handler.obtainMessage().sendToTarget(); // 通过Handler切换图片
}
}
}
/**
* 当ViewPager中页面的状态发生改变时调用
*
* @author Administrator
*
*/
private class MyPageChangeListener implements OnPageChangeListener {
private int oldPosition = 0;
/**
* This method will be invoked when a new page becomes selected.
* position: Position index of the new selected page.
*/
public void onPageSelected(int position) {
currentItem = position;
oldPosition = position;
}
public void onPageScrollStateChanged(int arg0) {
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
}
/**
* 填充ViewPager页面的适配器
*
* @author Administrator
*
*/
private class MyAdapter extends PagerAdapter {
@Override
public int getCount() {
return len;
}
@Override
public Object instantiateItem(View arg0, int arg1) {
((ViewPager) arg0).addView(imageViews.get(arg1));
return imageViews.get(arg1);
}
@Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
@Override
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public void finishUpdate(View arg0) {
}
}
/**
* apk文件下载
*
* @param url
* @param name
* @throws IOException
*/
public void apkDownload(String url, String name) throws IOException {
try {
byte[] buffer = new byte[1024];
int len = 0;
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response = client.execute(get);
StatusLine statusline = response.getStatusLine();
if (statusline.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
File file = new File(SAVE_PATH);
if (!file.exists()) {
file.mkdir();
}
File apk_file = new File(SAVE_PATH + name + ".apk");
if (!apk_file.exists())
apk_file.createNewFile();
FileOutputStream fos = new FileOutputStream(apk_file);
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
is.close();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 安装APK文件
*
* @param file
*/
private void openFile(File file) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
/**
* 下载广告图片
*
* @param urlPath
* @return
*/
private Bitmap downloadAdsPic(String urlPath) {
Bitmap bitmap = null;
try {
URL url = new URL(urlPath);
// 打开盖URL对应的资源的输入流
InputStream is = url.openStream();
// 从inputstream中解析图片
bitmap = BitmapFactory.decodeStream(is);
is.close();
// 再次打开URL对应的资源输入流
is = url.openStream();
// 打开手机对应文件的输出流
OutputStream os = openFileOutput("image.jpg", MODE_WORLD_READABLE);
byte[] buff = new byte[1024];
int hasread = 0;
// 将URL资源下载到本地
while ((hasread = is.read(buff)) > 0) {
os.write(buff, 0, hasread);
}
is.close();
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return bitmap;
}
ad_banner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ads_banner"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/adview_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal" >
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="50dip" >
<android.support.v4.view.ViewPager
android:id="@+id/vp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/ads_viewpage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dip"
android:gravity="center"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</RelativeLayout>