BannerView.java 16 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
package com.cnlive.goldenline.ui.widget;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cnlive.goldenline.Configs;
import com.cnlive.goldenline.R;
import com.cnlive.goldenline.api.CmsAPI;
import com.cnlive.goldenline.model.HomeProgramItem;
import com.cnlive.goldenline.model.admodel.AdItemChildBanner;
import com.cnlive.goldenline.model.admodel.AdParent;
import com.cnlive.goldenline.ui.base.SimplePagerAdapter;
import com.cnlive.goldenline.util.ADUtils;
import com.cnlive.goldenline.util.DensityUtils;
import com.cnlive.goldenline.util.DeviceUtils;
import com.cnlive.goldenline.util.FrescoUtils;
import com.cnlive.goldenline.util.RestAdapterUtils;
import com.cnlive.goldenline.util.SystemTools;
import com.cnlive.lib.analytics.CNLiveProbe;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.view.SimpleDraweeView;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

import static com.cnlive.goldenline.util.LogUtils.LOGD;
import static com.cnlive.goldenline.util.LogUtils.LOGE;


/**
 * Created by zuoxian on 2015/9/22.
 */
public class BannerView extends RelativeLayout {

    private static final long click_timeout = 110;
    private static long click_time = 0;
    private ViewPager mViewPager;
    private LinearLayout group;
    @Nullable
    private BannerAdapter bannerAdapter;
    private TextView title;
    private RelativeLayout mSearchLayout;
    private TextView mSearchButton;
    private ImageView icon;
    private RelativeLayout bannerTitle;
    @Nullable
    private List<HomeProgramItem> view_data;
    private ImageView[] indicators;
    private float click_x = 0;
    private boolean onTouch = false, onShowNext = true;

    private Context mContext;

    private int imageViewWidth = 0;
    private int imageViewHeight = 0;

    private static final String TAG = "BannerView";

    @NonNull
    private ViewPager.SimpleOnPageChangeListener pagerChangeListener = new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            for (int i = 0; i < indicators.length; i++) {
                //                indicators[i].setBackgroundColor(getResources().getColor((position % view_data.size() != i)
                //                        ? android.R.color.white : R.color.banner_icon));
                int margin = SystemTools.dip2px(getContext(), 3);
                int border = SystemTools.dip2px(getContext(), 6);
                LinearLayout.LayoutParams lp = null;
                //                if (position % view_data.size() == i) {
                //                    lp = new LinearLayout.LayoutParams(border, border);
                //
                //                } else {
                //                    lp = new LinearLayout.LayoutParams(margin, margin);
                //                }

                lp = new LinearLayout.LayoutParams(border, border);
                lp.setMargins(margin, 0, margin, 0);
                indicators[i].setLayoutParams(lp);
                //                indicators[i].setBackgroundResource(R.drawable.banner_select);
                indicators[i].setImageResource(R.mipmap.banner_nor);
                if (position % view_data.size() == i) {
                    indicators[i].setImageResource(R.mipmap.banner_select);
                }
            }
            HomeProgramItem item = view_data.get(position % view_data.size());
            title.setText(item.getTitle());

        }
    };

    public BannerView(Context context) {
        this(context, null);
        this.mContext = context;
    }

    public BannerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BannerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;
        init();
    }

    public void showNextPage() {
        if (!onShowNext) {
            if (!onTouch)
                onShowNext = true;
        } else if (null != mViewPager && null != bannerAdapter && bannerAdapter.getList().size() > 1) {
            mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
        }
    }

    @Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                click_time = System.currentTimeMillis();
                click_x = event.getX();
                onTouch = true;
                onShowNext = false;
                break;
            case MotionEvent.ACTION_UP:
                onTouch = false;

                break;
        }
        return super.dispatchTouchEvent(event);
    }


    private void init() {
        int width = Math.min(
                getResources().getDisplayMetrics().widthPixels,
                getResources().getDisplayMetrics().heightPixels);
        LayoutInflater.from(getContext()).inflate(R.layout.banner_home, this);
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mViewPager.getLayoutParams().width = width;
        mViewPager.getLayoutParams().height = (int) (width / 1.9);
        imageViewWidth = DeviceUtils.getScreenWidth(mContext);
        imageViewHeight = DensityUtils.dp2px(mContext, 221);
        group = (LinearLayout) findViewById(R.id.viewGroup);


        title = (TextView) findViewById(R.id.title);
        bannerTitle = (RelativeLayout) findViewById(R.id.bannertitle);
    }

    @Nullable
    public View getBannerTitle() {
        if (null != bannerTitle)
            return bannerTitle;
        else
            return null;
    }

    @Nullable
    public View getSearchLayout() {
        if (null != mSearchLayout)
            return mSearchLayout;
        else
            return null;
    }

    @Nullable
    public View getSearchButton() {
        if (null != mSearchButton)
            return mSearchButton;
        else
            return null;
    }

    public void setData(@Nullable List<HomeProgramItem> list) {
        if (list != null && list.size() > 0) {
            view_data = list;
            title.setText(view_data.get(0).getTitle());

            addIndicator(view_data.size());
            mViewPager.setAdapter(bannerAdapter = new BannerAdapter(view_data));
            mViewPager.setOnPageChangeListener(pagerChangeListener);
            mViewPager.setCurrentItem(500 - 500 % view_data.size());
        } else {
            mViewPager.getLayoutParams().height = 1;
        }
    }

    private void addIndicator(int count) {
        indicators = new ImageView[count];
        group.removeAllViews();
        int margin = SystemTools.dip2px(getContext(), 3);
        int border = SystemTools.dip2px(getContext(), 6);
        for (int i = 0; i < count; i++) {
            ImageView textView = new ImageView(getContext());

            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(border, border);
            lp.setMargins(margin, 0, margin, 0);
            textView.setLayoutParams(lp);

            indicators[i] = textView;

            //            indicators[i].setBackgroundColor(getResources().getColor((i == 0) ?
            //                    R.color.banner_icon : android.R.color.white));
            //            indicators[i].setBackgroundResource(R.drawable.banner_nor);
            //            indicators[i].setImageResource(R.drawable.banner_nor);
            textView.setImageResource(R.mipmap.banner_select);
            group.addView(textView);
        }
    }

    private class BannerAdapter extends SimplePagerAdapter<HomeProgramItem> {

        public BannerAdapter(List<HomeProgramItem> list) {
            super(list);
        }

        @Override
        public int getCount() {
            if (getList() != null && getList().size() > 0) {
                return Integer.MAX_VALUE;
            } else {
                return 0;
            }
        }


        @NonNull
        @Override
        public View getItemView(ViewGroup container, int position) {
            final int index = position % getList().size();
            final HomeProgramItem item = view_data.get(index);
            final SimpleDraweeView imageview = new SimpleDraweeView(getContext());

            GenericDraweeHierarchy hierarchy = imageview.getHierarchy();
            hierarchy.setPlaceholderImage(R.drawable.click_refresh);

            imageview.setLayoutParams(
                    new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT));
            imageview.setBackgroundResource(R.drawable.click_refresh);
            imageview.setScaleType(ImageView.ScaleType.FIT_XY);
            if (item.getExtend1().equals("6")) {
                DisplayMetrics metrics = new DisplayMetrics();
                //                        this.mContext.getWindowManager().getDefaultDisplay().getMetrics(metrics);

                WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
                int width = manager.getDefaultDisplay().getWidth();
                int height = manager.getDefaultDisplay().getHeight();
                CmsAPI cmsAPI = RestAdapterUtils.getRestAPI(Configs.Advertisement, CmsAPI.class);
                cmsAPI.getAdBannerData("1",   //广告类型
                        "android",          //当前系统
                        android.os.Build.VERSION.RELEASE,    //设备操作系统版本号
                        "46000",  //运营商类型
                        "2",      //设备类型
                        "2",   //网络类型
                        "18205253727",  //手机号码
                        ADUtils.getLocalIpAddress(mContext),  //ip
                        ADUtils.getMacAddress(mContext),    //安卓手机mac码
                        android.os.Build.MANUFACTURER,     //制造商
                        android.os.Build.MODEL,      //设备型号
                        height + "",  //设备屏幕高度
                        width + "",  //设备屏幕宽度
                        ADUtils.getUA(mContext),     //用户浏览器信息
                        ADUtils.getDeviceId(mContext),    //imei
                        new Callback<AdParent>() {
                            @Override
                            public void success(@NonNull AdParent data, Response response) {
                                if (data.getSeats() == null) {
//                                    SystemTools.show_msg(mContext, "广告获取失败");
                                    LOGE("广告获取失败");
                                } else {
                                    handleAds(imageview, data);
                                }


                            }

                            @Override
                            public void failure(@NonNull RetrofitError error) {
                                SystemTools.show_msg(mContext, "error:" + error.getMessage().toString());
                            }
                        });

            } else {
                if (!TextUtils.isEmpty(item.getImg()))
                    FrescoUtils.setImageNetworkResource(imageview, Uri.parse(item.getImg()), imageViewWidth, imageViewHeight);
                imageview.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if ("5".equals(item.getExtend1())) {
                            LOGE(TAG + " go htmlAcivity ");
//                            Intent intent = new Intent(mContext, HtmlActivity.class);
//                            mContext.start(intent);
                        } else {
                            String itemContid;
                            if ("4".equals(item.getExtend1())) {
                                itemContid = item.getUrl();
                            } else {
                                if ("2".equals(item.getExtend1())) {
                                    CNLiveProbe.onEvent("GSBMasterAndroid");

                                } else if ("1".equals(item.getExtend1())) {
                                    CNLiveProbe.onEvent("GSBLivingAndroid");
                                } else if ("0".equals(item.getExtend1())) {
                                    CNLiveProbe.onEvent("GSBDemandAndroid");
                                }
                                itemContid = item.getContid();
                            }
                            LOGE(TAG + " 跳转页面 ");
//                            ActivityJumper.JumpToDemandAcitviy(getContext(), itemContid, item.getTitle(), item.getUv(), item.getImg(), item.getExtend1(), item.getExtend());
                        }
                    }
                });
            }
            return imageview;
        }


    }

    private void handleAds(@NonNull SimpleDraweeView longImg, @NonNull AdParent data) {
        LOGD("广告成功了");
        String image;
        LOGD("adsData1=" + data);
        LOGD("adsData2=" + data.getSeats().get(0).getAds().get(0).getBanner().getImage().isEmpty());
        if (!data.getSeats().get(0).getAds().get(0).getBanner().getImage().isEmpty()) {
            image = data.getSeats().get(0).getAds().get(0).getBanner().getImage();
            FrescoUtils.setImageNetworkResource(longImg, Uri.parse(image));
        } else {
            FrescoUtils.setImageNetworkResource(longImg, Uri.parse(""));
        }


        if (data.getSeats() != null) {
            final AdItemChildBanner banner = data.getSeats().get(0).getAds().get(0).getBanner();
            showAds(banner);
            longImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickAds(banner);
                    openUrl(banner.getLandingurl());
                }
            });
        } else {
            LOGE("广告点击失败");
        }

    }

    private void showAds(@NonNull AdItemChildBanner banner) {
        List<String> impressurl = banner.getImpressurl();
        for (int i = 0; i < impressurl.size(); i++) {
            requestAdsUrl(impressurl.get(i));
        }
    }

    private void openUrl(@Nullable String landingurl) {
        if (landingurl != null) {
            Intent intent = new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(landingurl);
            intent.setData(content_url);
//            intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
            mContext.startActivity(intent);
        } else {
            LOGE("广告点击失败");
        }
    }

    private void clickAds(@NonNull AdItemChildBanner banner) {
        List<String> clickurl = banner.getClickurl();
        for (int i = 0; i < clickurl.size(); i++) {
            requestAdsUrl(clickurl.get(i));
        }
    }


    private void requestAdsUrl(@NonNull String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                LOGD("xk===" + "广告请求失败");
            }

            @Override
            public void onResponse(com.squareup.okhttp.Response response) throws IOException {
                LOGD("xk===" + "广告请求成功");
            }
        });
    }

}