Android开发小结2

1.html(js)和app的交互

参考:http://blog.csdn.net/fenggit/article/details/51028300

//绑定view
@BindView(R.id.web_webview)
 WebView web_webview;
//调用js方法,将参数传给js
  web_webview.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO Auto-generated method stub
                view.loadUrl(url);
                return false;
            }
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//待html加载结束后,传参
                onInvokeJs();
            }
        });

 /**
     * App调用JS代码
     */
    private void onInvokeJs() {
        String userPhone = ACache.get(getApplicationContext()).getAsString(CommonParams.USER_PHONE);
        //调用js中的函数:getInfoFromApp(msg)
        web_webview.loadUrl("javascript:getInfoFromApp(" + userPhone + ")");
    }

2.ProgressCircleView

参考:http://blog.csdn.net/ddwhan0123/article/details/47342609

3.SimpleDraweeView

图片加载引擎
参考:http://blog.csdn.net/qq_34997963/article/details/51785566
actualImageScaleType-加载成功的显示样式
roundAsCircle-绘制圆形
roundingBorderColor-圆形边框颜色
roundingBorderWidth-原型边框宽度
类型 描述
center 居中,无缩放
centerCrop 保持宽高比缩小或放大,使得两边都大于或等于显示边界。居中显示。
focusCrop 同centerCrop, 但居中点不是中点,而是指定的某个点
centerInside 使两边都在显示边界内,居中显示。如果图尺寸大于显示边界,则保持长宽比缩小图片。
fitCenter 保持宽高比,缩小或者放大,使得图片完全显示在显示边界内。居中显示
fitStart 同上。但不居中,和显示边界左上对齐
fitEnd 同fitCenter, 但不居中,和显示边界右下对齐
fitXY 不保存宽高比,填充满显示边界


ImageRequest requestLogo;
        requestLogo = ImageRequestBuilder.newBuilderWithSource(Uri.parse(houseApartmentDetailModel.getLogo()))
                .setResizeOptions(new ResizeOptions(SizeUtils.dp2px(72), SizeUtils.dp2px(72))).build();
        DraweeController draweeControllerLogo = Fresco.newDraweeControllerBuilder()
               .setImageRequest(requestLogo).setAutoPlayAnimations(true).build();
        house_apartment_descripe_img.setController(draweeControllerLogo);

4.百度地图

参考:http://blog.csdn.net/qq_26787115/article/details/50358037

//导航
public void showNavi() {
        boolean gaodeInstall= AppUtils.isInstallApp("com.autonavi.minimap");
        boolean baiduInstall=AppUtils.isInstallApp("com.baidu.BaiduMap");
        String[] items;
        if (gaodeInstall && baiduInstall) {
            items=new String[]{"百度地图", "高德地图"};
        }
        else if (gaodeInstall) {
            items=new String[]{"高德地图"};
        }
        else if (baiduInstall) {
            items=new String[]{"百度地图"};
        }
        else {
            items=new String[]{};
        }
        if (items.length==0) {
            Toast.makeText(this, "请安装地图软件后再使用此功能", Toast.LENGTH_SHORT).show();
            return;
        }
        ActionSheetUtils.showList(getSupportFragmentManager(), "", items, i -> {
            if (items[i].equals("高德地图")) {
                CoordinateConverter coordinateConverter=new CoordinateConverter(MapHouseActivity.this);
                coordinateConverter.from(CoordinateConverter.CoordType.BAIDU);
                try {
                    coordinateConverter.coord(new DPoint(curLoc.latitude, curLoc.longitude));
                    DPoint d1=coordinateConverter.convert();
                    coordinateConverter.coord(new DPoint(lati, longti));
                    DPoint d2=coordinateConverter.convert();
                    com.house365.rent.utils.Utils.showRoute(MapHouseActivity.this, d1.getLatitude(), d1.getLongitude(), d2.getLatitude(), d2.getLongitude(), 2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            else if (items[i].equals("百度地图")) {
                Intent i1 = new Intent();
                i1.setData(Uri.parse("baidumap://map/direction?origin="+curLoc.latitude+","+curLoc.longitude+"&destination="+lati+","+longti+"&mode=driving"));
                startActivity(i1);
            }
        }, () -> {

        });
    }

/**
     * 判断App是否安装
     *
     * @param packageName 包名
     * @return {@code true}: 已安装
{@code false}: 未安装 */ public static boolean isInstallApp(String packageName) { return !isSpace(packageName) && IntentUtils.getLaunchAppIntent(packageName) != null; }
//路线
        PlanNode stNode = PlanNode.withLocation(getIntent().getParcelableExtra("startLatlng"));
        PlanNode enNode = PlanNode.withLocation(getIntent().getParcelableExtra("endLatlng"));
        if (getIntent().getSerializableExtra("trafficType") == TrafficType.Transit) {
            new Handler().postDelayed(() -> mSearch.transitSearch((new TransitRoutePlanOption()).city("南京")
                    .from(stNode).to(enNode)), 1000);
        }
        else if (getIntent().getSerializableExtra("trafficType") == TrafficType.Biking) {
            new Handler().postDelayed(() -> mSearch.bikingSearch((new BikingRoutePlanOption())
                    .from(stNode).to(enNode)), 1000);
        }
        else if (getIntent().getSerializableExtra("trafficType") == TrafficType.Driving) {
            new Handler().postDelayed(() -> mSearch.drivingSearch((new DrivingRoutePlanOption())
                    .from(stNode).to(enNode)), 1000);
        }
        else if (getIntent().getSerializableExtra("trafficType") == TrafficType.Walking) {
            new Handler().postDelayed(() -> mSearch.walkingSearch((new WalkingRoutePlanOption())
                    .from(stNode).to(enNode)), 1000);
        }

5.沉浸式



         

            

                

                    
                

                

                    
                
            
        

        

            
                

                    

                    

                    
                

        
    
//导航栏颜色
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
   getWindow().setStatusBarColor(Color.parseColor("#5a000000"));
}
appbar_houseapartment.addOnOffsetChangedListener(this);
 @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (verticalOffset == 0) {
            tv_nav_title.setVisibility(View.GONE);
            ib_nav_left.setImageResource(R.mipmap.img_arrow_white);
        } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
            findViewById(R.id.house_apartment_toolbar).setBackgroundColor(Color.WHITE);
            tv_nav_title.setVisibility(View.VISIBLE);
            ib_nav_left.setImageResource(R.mipmap.ic_black_left_arrow);
        } else {

        }

        ArgbEvaluator evaluator = new ArgbEvaluator();
        float percent = ((float) -verticalOffset) / appBarLayout.getTotalScrollRange();
        findViewById(R.id.house_apartment_toolbar).setBackgroundColor((Integer) evaluator.evaluate(percent, Color.TRANSPARENT, getResources().getColor(R.color.white)));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor((Integer) evaluator.evaluate(percent, Color.TRANSPARENT, getResources().getColor(R.color.white)));
        }
    }

6.GridLayout


 grid_house_detail_conf.removeAllViews();
        for (int i = 0; i < confInfos.length; i++) {
            //10 12配置文件暂时没有 不展示
            if (!(StringUtils.isEmpty(confInfos[i]) || confInfos[i].equals("10") || confInfos[i].equals("12"))) {
                View view = LayoutInflater.from(this).inflate(R.layout.view_house_detail_conf, null, false);
                SimpleDraweeView iv_house_conf_pic = (SimpleDraweeView) view.findViewById(R.id.iv_house_conf_pic);
                TextView tv_house_conf_name = (TextView) view.findViewById(R.id.tv_house_conf_name);
                for (RentAllConfigBean.RoomFacilitiesBean roomFacilitiesBean : houseDetailConfigBean.getRoom_facilities()) {
                    if (confInfos[i].equals(roomFacilitiesBean.getKey() + "")) {
                        if (!StringUtils.isEmpty(roomFacilitiesBean.getValue())) {
                            tv_house_conf_name.setText(roomFacilitiesBean.getValue());
                            ImageRequest request = ImageRequestBuilder.newBuilderWithSource(Uri.parse(roomFacilitiesBean.getIcon()))
                                    .setResizeOptions(new ResizeOptions(SizeUtils.dp2px(30), SizeUtils.dp2px(30))).build();
                            DraweeController draweeController = Fresco.newDraweeControllerBuilder()
                                    .setImageRequest(request).setAutoPlayAnimations(true).build();
                            iv_house_conf_pic.setController(draweeController);
                        }
                    }
                }
                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.width = grid_house_detail_conf.getMeasuredWidth() / 5;
                params.height = grid_house_detail_conf.getMeasuredWidth() / 5;
                grid_house_detail_conf.addView(view, params);
            }

7.popWindow及分享(QQ、微信、微博)




    
    

        

        
    
    
    
    

        

        
    
    
    
    

        

        
    

/**
     * 初始化 pop “分享”“收藏”“举报”
     */
    private void initPop() {
        View popView = LayoutInflater.from(this).inflate(R.layout.pop_house_detail, null, false);
        pop_house_share_rl = (RelativeLayout) popView.findViewById(R.id.pop_house_share_rl);
        pop_house_fav_rl = (RelativeLayout) popView.findViewById(R.id.pop_house_fav_rl);
        pop_house_fav_img = (ImageView) popView.findViewById(R.id.pop_house_fav_img);
        pop_house_report_rl = (RelativeLayout) popView.findViewById(R.id.pop_house_report_rl);
        if (houseDetailModel.getHasCollected() == 0) {
            pop_house_fav_img.setImageResource(R.mipmap.img_collect);
            collect_status = 0;
        } else {
            pop_house_fav_img.setImageResource(R.mipmap.img_collected);
            collect_status = 1;
        }

        //分享
        pop_house_share_rl.setOnClickListener(view -> {
//            if (goSignIn()) return;
            ActionSheetFragment.build(getSupportFragmentManager()).setChoice(ActionSheetFragment.CHOICE.GRID).setTitle("分享至")
                    .setGridItems(new String[]{"微信好友", "朋友圈", "QQ好友", "微博"},
                            new int[]{R.mipmap.img_share_wechat, R.mipmap.img_share_circle, R.mipmap.img_share_qq, R.mipmap.img_share_weibo}, new ActionSheetFragment.OnItemClickListener() {
                                @Override
                                public void onItemClick(int position) {
                                    switch (position) {
                                        case 0:
                                            //分享微信好友
//                                            if (goSignIn()) return;
                                            setHouseShare("1", "0");//调用接口 1 微信 2 QQ 3 微博 4 电话其他待定义
                                            SendWeixin.sendWeixin(HouseDetail1Activity.this, description,
                                                    houseDetailModel.getTouchUrl(), houseDetailModel.getHouse_title(), shareFile == null ? "" : shareFile.getPath(), false);
                                            break;
                                        case 1:
                                            //分享微信朋友圈
//                                            if (goSignIn()) return;
                                            setHouseShare("1", "0");//调用接口 1 微信 2 QQ 3 微博 4 电话其他待定义
                                            SendWeixin.sendWeixin(HouseDetail1Activity.this, description,
                                                    houseDetailModel.getTouchUrl(), houseDetailModel.getHouse_title(), shareFile == null ? "" : shareFile.getPath(), true);
                                            break;
                                        case 2:
                                            //分享qq好友
//                                            if (goSignIn()) return;
                                            setHouseShare("2", "0");//调用接口 1 微信 2 QQ 3 微博 4 电话其他待定义
                                            Intent intent_qq = new Intent(HouseDetail1Activity.this, QQShareActivity.class);
                                            Bundle bundle_qq = new Bundle();
                                            bundle_qq.putString("text", description);
                                            String[] images;
                                            if (!StringUtils.isEmpty(houseDetailModel.getR_detail_images())) {
                                                images = houseDetailModel.getR_detail_images().split(",");
                                            } else {
                                                images = new String[]{"http://7b1g8u.com1.z0.glb.clouddn.com/ic_launcher_azn.png"};
                                            }
                                            bundle_qq.putString("imageUrl", images[0]);
                                            bundle_qq.putString("title", houseDetailModel.getHouse_title());
                                            bundle_qq.putString("url", houseDetailModel.getTouchUrl());
                                            bundle_qq.putBoolean("isQQZone", false);
                                            bundle_qq.putInt("type", 1);
                                            intent_qq.putExtras(bundle_qq);
                                            startActivity(intent_qq);
                                            break;
                                        case 3:
                                            //分享微博
//                                            if (goSignIn()) return;
                                            setHouseShare("3", "0");//调用接口 1 微信 2 QQ 3 微博 其他待定义
                                            Intent intent_sina = new Intent(HouseDetail1Activity.this, WBMainActivity.class);
                                            intent_sina.putExtra("shareText", houseDetailModel.getHouse_title() + "\n" + description);
                                            intent_sina.putExtra("filePath", shareBigFile == null ? "" : shareBigFile.getPath());
                                            startActivity(intent_sina);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                            }).show();
            if (pop != null && pop.isShowing()) {
                pop.dismiss();
            }
        });
 pop = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        pop.setTouchable(true);
        pop.setOutsideTouchable(true);
//微信分享
public static boolean sendWeixin(Context context, String text, String url, String title, String path, boolean isFriend) {
        IWXAPI api= WXAPIFactory.createWXAPI(context, CommonParams.weixinAppID);
        int wxSdkVersion = api.getWXAppSupportAPI();
        if (api.isWXAppInstalled()) {
            if (wxSdkVersion==0) {
                api.openWXApp();
                return false;
            }
            if (wxSdkVersion >= 0x21020001 || wxSdkVersion==0) {
                api.registerApp(CommonParams.weixinAppID);
                WXWebpageObject webpage=new WXWebpageObject();
                webpage.webpageUrl=url;
                WXMediaMessage msg=new WXMediaMessage(webpage);
                msg.title=title;
                msg.description=text;
                if (TextUtils.isEmpty(path)) {
                    msg.thumbData=Bitmap2Bytes(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher));
                }
                else {
                    msg.thumbData=Bitmap2Bytes(BitmapFactory.decodeFile(path));
                }
                SendMessageToWX.Req req=new SendMessageToWX.Req();
                req.transaction=buildTransaction("webpage");
                req.message=msg;
                req.scene=isFriend? SendMessageToWX.Req.WXSceneTimeline: SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);
                return true;
            }
            else {
                Toast.makeText(context, "您当前使用的微信版本过低,分享失败", Toast.LENGTH_LONG).show();
                return false;
            }
        }
        else {
            Toast.makeText(context, "您未安装微信,分享失败", Toast.LENGTH_LONG).show();
            return false;
        }
    }

    public static void sendWeixinImage(Context context, boolean isFriend, String path) {
        int THUMB_SIZE = 150;
        IWXAPI api= WXAPIFactory.createWXAPI(context, CommonParams.weixinAppID);
        int wxSdkVersion = api.getWXAppSupportAPI();
        if (api.isWXAppInstalled()) {
            if (wxSdkVersion==0) {
                api.openWXApp();
            }
            if (wxSdkVersion >= 0x21020001 || wxSdkVersion==0) {
                Bitmap bmp = BitmapFactory.decodeFile(path);
                WXImageObject imgObj = new WXImageObject(bmp);
                WXMediaMessage msg = new WXMediaMessage();
                msg.mediaObject = imgObj;
                Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, (int) (THUMB_SIZE/(ScreenUtils.getScreenHeight()*1.0f/ScreenUtils.getScreenWidth())), THUMB_SIZE, true);
                bmp.recycle();
                msg.thumbData = bmpToByteArray(thumbBmp, true);  // 设置缩略图
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("img");
                req.message = msg;
                req.scene = isFriend ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
                api.sendReq(req);
            }
            else {
                Toast.makeText(context, "您当前使用的微信版本过低,分享失败", Toast.LENGTH_LONG).show();
            }
        }
        else {
            Toast.makeText(context, "您未安装微信,分享失败", Toast.LENGTH_LONG).show();
        }
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }
//qq分享
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        mTencent= Tencent.createInstance(CommonParams.QQAppid, getApplicationContext());
        if(!mTencent.isSupportSSOLogin(QQShareActivity.this)) {
            Toast.makeText(this, "您的手机没有安装QQ", Toast.LENGTH_SHORT).show();
            finish();
            return ;
        }

        if (getIntent().getExtras().getInt("type")==1) {
            share(getIntent().getExtras().getString("text"), getIntent().getExtras().getString("imageUrl"), getIntent().getExtras().getString("title"),
                    getIntent().getExtras().getString("url"), getIntent().getExtras().getBoolean("isQQZone"));
        }
        else if (getIntent().getExtras().getInt("type")==2) {
            shareImage(getIntent().getExtras().getString("imageUrl"), getIntent().getExtras().getBoolean("isQQZone"));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // must call mTencent.onActivityResult.
        if (requestCode == Constants.REQUEST_QQ_SHARE) {
            Tencent.onActivityResultData(requestCode, resultCode, data, qqShareListener);
        }
    }

    public void share(String text, String imageUrl, String title, String url, boolean isQQZone) {
        final Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, text);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "爱租哪");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        if (isQQZone) {
            mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN;
        }
        else {
            mExtarFlag &= (0xFFFFFFFF - QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        }
        if (!isQQZone) {
            mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE;
        } else {
            mExtarFlag &= (0xFFFFFFFF - QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        }
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, mExtarFlag);
        // QQ分享要在主线程做
        ThreadManager.getMainHandler().post(() -> mTencent.shareToQQ(QQShareActivity.this, params, qqShareListener));
    }

    public void shareImage(String path, boolean isQQZone) {
        final Bundle params = new Bundle();
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, path);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "爱租哪");
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE);
        if (isQQZone) {
            mExtarFlag |= QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN;
        }
        else {
            mExtarFlag &= (0xFFFFFFFF - QQShare.SHARE_TO_QQ_FLAG_QZONE_AUTO_OPEN);
        }
        params.putInt(QQShare.SHARE_TO_QQ_EXT_INT, mExtarFlag);
        // QQ分享要在主线程做
        ThreadManager.getMainHandler().post(() -> mTencent.shareToQQ(QQShareActivity.this, params, qqShareListener));
    }

    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {
            Log.d("QQShareActivity", "onCancel");
            Toast.makeText(QQShareActivity.this, "用户取消", Toast.LENGTH_SHORT).show();
            finish();
        }
        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub
            Log.d("QQShareActivity", "onComplete: " + response.toString());
            Toast.makeText(QQShareActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            finish();
        }
        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub
            Log.d("QQShareActivity", "onError: " + e.errorMessage);
            Toast.makeText(QQShareActivity.this, "QQ分享失败"+e.errorMessage+",请稍后再试", Toast.LENGTH_SHORT).show();
            finish();
        }
    };
//微博分享
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 创建微博实例
        mWeiboShareAPI= WeiboShareSDK.createWeiboAPI(this, CommonParams.weiboAppId);
        // 注册第三方应用到微博客户端中,注册成功后该应用将显示在微博的应用列表中。
        // 但该附件栏集成分享权限需要合作申请,详情请查看 Demo 提示
        // NOTE:请务必提前注册,即界面初始化的时候或是应用程序初始化时,进行注册
        mWeiboShareAPI.registerApp();
        // 当 Activity 被重新初始化时(该 Activity 处于后台时,可能会由于内存不足被杀掉了),
        // 需要调用 {@link IWeiboShareAPI#handleWeiboResponse} 来接收微博客户端返回的数据。
        // 执行成功,返回 true,并调用 {@link IWeiboHandler.Response#onResponse};
        // 失败返回 false,不调用上述回调
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }

        boolean isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        if (isInstalledWeibo) {
            sendMultiMessage(getIntent().getStringExtra("shareText"), getIntent().getStringExtra("filePath"));
        }
        else {
            Toast.makeText(this, "请安装新浪微博客户端后方可分享", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (isCallBack) {
            handler.postDelayed(runnable, 1000);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();

        isCallBack=true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后,返回到当前应用时,需要在此处调用该函数
        // 来接收微博客户端返回的数据;执行成功,返回 true,并调用
        // {@link IWeiboHandler.Response#onResponse};失败返回 false,不调用上述回调
        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        handler.removeCallbacks(runnable);
        switch (baseResponse.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Log.d("WBMainActivity", "ERR_OK");
                Toast.makeText(WBMainActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Log.d("WBMainActivity", "ERR_CANCEL");
                Toast.makeText(WBMainActivity.this, "已取消", Toast.LENGTH_SHORT).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Log.d("WBMainActivity", baseResponse.errMsg);
                Toast.makeText(WBMainActivity.this, "微博分享失败"+baseResponse.errMsg+",请稍后再试", Toast.LENGTH_SHORT).show();
                break;
        }
        finish();
    }

    /**
     * 第三方应用发送请求消息到微博,唤起微博分享界面。
     */
    private void sendMultiMessage(String shareText, String filePath) {
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(shareText);
        weiboMessage.imageObject = getImageObj(filePath);
        // 2. 初始化从第三方到微博的消息请求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一标识一个请求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        // 3. 发送请求消息到微博,唤起微博分享界面
        AuthInfo authInfo = new AuthInfo(this, CommonParams.weiboAppId,
                "https://api.weibo.com/oauth2/default.html", SCOPE);
        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
        String token = "";
        if (accessToken != null) {
            token = accessToken.getToken();
        }
        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {

            @Override
            public void onWeiboException( WeiboException arg0 ) {
            }

            @Override
            public void onComplete( Bundle bundle ) {
                // TODO Auto-generated method stub
                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
            }

            @Override
            public void onCancel() {
            }
        });
    }

    /**
     * 创建文本消息对象。
     * @return 文本消息对象。
     */
    private TextObject getTextObj(String shareText) {
        TextObject textObject = new TextObject();
        textObject.text = shareText;
        return textObject;
    }

    /**
     * 创建图片消息对象。
     *
     * @return 图片消息对象。
     */
    private ImageObject getImageObj(String filePath) {
        ImageObject imageObject = new ImageObject();
        //设置缩略图。 注意:最终压缩过的缩略图大小不得超过 2M。
        if (TextUtils.isEmpty(filePath)) {
            shareBitmap=BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        }
        else {
            shareBitmap=BitmapFactory.decodeFile(filePath);
        }
        imageObject.setImageObject(shareBitmap);
        return imageObject;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (shareBitmap!=null && !shareBitmap.isRecycled()) {
            shareBitmap.recycle();
            shareBitmap=null;
        }
    }

你可能感兴趣的:(Android开发小结2)