Android開發(fā)小結(jié)2

1.html(js)和app的交互

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

//綁定view
@BindView(R.id.web_webview)
 WebView web_webview;
//調(diào)用js方法宣吱,將參數(shù)傳給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加載結(jié)束后足绅,傳參
                onInvokeJs();
            }
        });

 /**
     * App調(diào)用JS代碼
     */
    private void onInvokeJs() {
        String userPhone = ACache.get(getApplicationContext()).getAsString(CommonParams.USER_PHONE);
        //調(diào)用js中的函數(shù):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-原型邊框?qū)挾?br> 類型 描述
center 居中攻泼,無(wú)縮放
centerCrop 保持寬高比縮小或放大商源,使得兩邊都大于或等于顯示邊界。居中顯示为流。
focusCrop 同centerCrop, 但居中點(diǎn)不是中點(diǎn)毁枯,而是指定的某個(gè)點(diǎn)
centerInside 使兩邊都在顯示邊界內(nèi)业扒,居中顯示减途。如果圖尺寸大于顯示邊界,則保持長(zhǎng)寬比縮小圖片曹洽。
fitCenter 保持寬高比鳍置,縮小或者放大,使得圖片完全顯示在顯示邊界內(nèi)送淆。居中顯示
fitStart 同上税产。但不居中,和顯示邊界左上對(duì)齊
fitEnd 同fitCenter偷崩, 但不居中辟拷,和顯示邊界右下對(duì)齊
fitXY 不保存寬高比,填充滿顯示邊界

<com.facebook.drawee.view.SimpleDraweeView xmlns:fresco="http://schemas.android.com/apk/res-auto"
                        android:id="@+id/house_apartment_descripe_img"
                        android:layout_width="72dp"
                        android:layout_height="72dp"
                        android:layout_alignParentRight="true"
                        fresco:actualImageScaleType="centerInside"
                        fresco:failureImage="@mipmap/img_logo_gray"
                        fresco:failureImageScaleType="focusCrop"
                        fresco:placeholderImage="@mipmap/img_logo_gray"
                        fresco:placeholderImageScaleType="focusCrop"
                        fresco:retryImage="@mipmap/img_logo_gray"
                        fresco:retryImageScaleType="focusCrop"
                        fresco:roundAsCircle="true"
                        fresco:roundingBorderColor="@color/text_common_5"
                        fresco:roundingBorderWidth="0.5dp" />
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

//導(dǎo)航
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, "請(qǐng)安裝地圖軟件后再使用此功能", 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}: 已安裝<br>{@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.沉浸式

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/white"
        android:fitsSystemWindows="true">

         <android.support.design.widget.AppBarLayout xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/appbar_houseapartment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true">

            <android.support.design.widget.CollapsingToolbarLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom"
                    android:background="@mipmap/img_bj_bottom"
                    android:fitsSystemWindows="true">

                    <com.facebook.drawee.view.SimpleDraweeView xmlns:fresco="http://schemas.android.com/apk/res-auto"
                        android:id="@+id/house_apartment_top_img"
                        android:layout_width="match_parent"
                        android:layout_height="220dp"
                        fresco:actualImageScaleType="focusCrop"
                        fresco:failureImage="@mipmap/img_detail_bg"
                        fresco:failureImageScaleType="focusCrop"
                        fresco:placeholderImage="@mipmap/img_detail_bg"
                        fresco:placeholderImageScaleType="focusCrop"
                        fresco:retryImage="@mipmap/img_detail_bg"
                        fresco:retryImageScaleType="focusCrop" />
                </RelativeLayout>

                <android.support.v7.widget.Toolbar
                    android:id="@+id/house_apartment_toolbar"
                    style="@style/GroupToolbarStyle"
                    android:layout_width="match_parent"
                    android:layout_height="50dip"
                    android:background="@android:color/transparent"
                    app:layout_collapseMode="pin">

                    <include layout="@layout/view_nav"></include>
                </android.support.v7.widget.Toolbar>
            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="-36dp"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

            <!-- 布局-->
                <LinearLayout
                    android:id="@+id/house_apartment_houseresource_ll"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginBottom="15dp"
                    android:layout_marginTop="15dp"
                    android:orientation="vertical">

                    <TextView
                        android:id="@+id/house_apartment_houseresource_tx"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginBottom="10dp"
                        android:text="- 最新房源 -"
                        android:textColor="@color/text_common_1"
                        android:textSize="14sp" />

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/rv_house_apartment"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>

                    <TextView
                        android:id="@+id/house_apartment_houseresource_more"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center_horizontal"
                        android:layout_marginTop="10dp"
                        android:background="@drawable/shape_rounded_corner_orange4"
                        android:padding="2dp"
                        android:text="查看全部房源"
                        android:textColor="@color/text_common_4"
                        android:textSize="14sp"
                        android:visibility="gone" />
                </LinearLayout>

        </android.support.v4.widget.NestedScrollView>
    </android.support.design.widget.CoordinatorLayout>
//導(dǎo)航欄顏色
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

<android.support.v7.widget.GridLayout xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:id="@+id/grid_house_detail_conf"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@id/house_detail_conf"
                    app:columnCount="5"></android.support.v7.widget.GridLayout>
 grid_house_detail_conf.removeAllViews();
        for (int i = 0; i < confInfos.length; i++) {
            //10 12配置文件暫時(shí)沒有 不展示
            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阐斜、微信衫冻、微博)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@mipmap/bj_house_pip">

    <!-- 分享 -->
    <RelativeLayout
        android:id="@+id/pop_house_share_rl"
        android:layout_width="120dp"
        android:layout_height="41dp"
        android:layout_marginTop="10dp"
        android:gravity="center">

        <ImageView
            android:id="@+id/pop_house_share_img"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:background="@mipmap/img_share" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/pop_house_share_img"
            android:layout_marginLeft="10dp"
            android:layout_centerVertical="true"
            android:text="分享"
            android:textColor="@color/white"
            android:textSize="14sp" />
    </RelativeLayout>
    <View
        android:id="@+id/view_set_staff"
        android:layout_width="match_parent"
        android:layout_height="0.5dip"
        android:background="@color/text_common_3"></View>
    <!-- 收藏 -->
    <RelativeLayout
        android:id="@+id/pop_house_fav_rl"
        android:layout_width="120dp"
        android:layout_height="41dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:gravity="center">

        <ImageView
            android:id="@+id/pop_house_fav_img"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:background="@mipmap/img_collect" />

        <TextView
            android:id="@+id/pop_house_fav_tx"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/pop_house_fav_img"
            android:layout_marginLeft="10dp"
            android:layout_centerVertical="true"
            android:text="收藏"
            android:textColor="@color/white"
            android:textSize="14sp" />
    </RelativeLayout>
    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dip"
        android:background="@color/text_common_3"></View>
    <!-- 舉報(bào) -->
    <RelativeLayout
        android:id="@+id/pop_house_report_rl"
        android:layout_width="120dp"
        android:layout_height="41dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:gravity="center">

        <ImageView
            android:id="@+id/pop_house_report_img"
            android:layout_width="20dp"
            android:layout_height="20dp"
            android:layout_centerVertical="true"
            android:background="@mipmap/img_report" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/pop_house_report_img"
            android:layout_marginLeft="10dp"
            android:layout_centerVertical="true"
            android:text="舉報(bào)"
            android:textColor="@color/white"
            android:textSize="14sp" />
    </RelativeLayout>
</LinearLayout>
/**
     * 初始化 pop “分享”“收藏”“舉報(bào)”
     */
    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");//調(diào)用接口 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");//調(diào)用接口 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");//調(diào)用接口 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");//調(diào)用接口 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, "您當(dāng)前使用的微信版本過低,分享失敗", 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);  // 設(shè)置縮略圖
                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, "您當(dāng)前使用的微信版本過低叨橱,分享失敗", 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, "您的手機(jī)沒有安裝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+",請(qǐng)稍后再試", Toast.LENGTH_SHORT).show();
            finish();
        }
    };
//微博分享
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 創(chuàng)建微博實(shí)例
        mWeiboShareAPI= WeiboShareSDK.createWeiboAPI(this, CommonParams.weiboAppId);
        // 注冊(cè)第三方應(yīng)用到微博客戶端中为居,注冊(cè)成功后該應(yīng)用將顯示在微博的應(yīng)用列表中。
        // 但該附件欄集成分享權(quán)限需要合作申請(qǐng)杀狡,詳情請(qǐng)查看 Demo 提示
        // NOTE:請(qǐng)務(wù)必提前注冊(cè)蒙畴,即界面初始化的時(shí)候或是應(yīng)用程序初始化時(shí),進(jìn)行注冊(cè)
        mWeiboShareAPI.registerApp();
        // 當(dāng) Activity 被重新初始化時(shí)(該 Activity 處于后臺(tái)時(shí)捣卤,可能會(huì)由于內(nèi)存不足被殺掉了)忍抽,
        // 需要調(diào)用 {@link IWeiboShareAPI#handleWeiboResponse} 來(lái)接收微博客戶端返回的數(shù)據(jù)。
        // 執(zhí)行成功董朝,返回 true鸠项,并調(diào)用 {@link IWeiboHandler.Response#onResponse};
        // 失敗返回 false子姜,不調(diào)用上述回調(diào)
        if (savedInstanceState != null) {
            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
        }

        boolean isInstalledWeibo = mWeiboShareAPI.isWeiboAppInstalled();
        if (isInstalledWeibo) {
            sendMultiMessage(getIntent().getStringExtra("shareText"), getIntent().getStringExtra("filePath"));
        }
        else {
            Toast.makeText(this, "請(qǐng)安裝新浪微博客戶端后方可分享", 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);
        // 從當(dāng)前應(yīng)用喚起微博并進(jìn)行分享后祟绊,返回到當(dāng)前應(yīng)用時(shí),需要在此處調(diào)用該函數(shù)
        // 來(lái)接收微博客戶端返回的數(shù)據(jù)哥捕;執(zhí)行成功牧抽,返回 true,并調(diào)用
        // {@link IWeiboHandler.Response#onResponse}遥赚;失敗返回 false扬舒,不調(diào)用上述回調(diào)
        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+",請(qǐng)稍后再試", Toast.LENGTH_SHORT).show();
                break;
        }
        finish();
    }

    /**
     * 第三方應(yīng)用發(fā)送請(qǐng)求消息到微博凫佛,喚起微博分享界面讲坎。
     */
    private void sendMultiMessage(String shareText, String filePath) {
        // 1. 初始化微博的分享消息
        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        weiboMessage.textObject = getTextObj(shareText);
        weiboMessage.imageObject = getImageObj(filePath);
        // 2. 初始化從第三方到微博的消息請(qǐng)求
        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
        // 用transaction唯一標(biāo)識(shí)一個(gè)請(qǐng)求
        request.transaction = String.valueOf(System.currentTimeMillis());
        request.multiMessage = weiboMessage;
        // 3. 發(fā)送請(qǐng)求消息到微博孕惜,喚起微博分享界面
        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() {
            }
        });
    }

    /**
     * 創(chuàng)建文本消息對(duì)象。
     * @return 文本消息對(duì)象晨炕。
     */
    private TextObject getTextObj(String shareText) {
        TextObject textObject = new TextObject();
        textObject.text = shareText;
        return textObject;
    }

    /**
     * 創(chuàng)建圖片消息對(duì)象衫画。
     *
     * @return 圖片消息對(duì)象。
     */
    private ImageObject getImageObj(String filePath) {
        ImageObject imageObject = new ImageObject();
        //設(shè)置縮略圖瓮栗。 注意:最終壓縮過的縮略圖大小不得超過 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;
        }
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市费奸,隨后出現(xiàn)的幾起案子弥激,更是在濱河造成了極大的恐慌,老刑警劉巖货邓,帶你破解...
    沈念sama閱讀 221,695評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件秆撮,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡换况,警方通過查閱死者的電腦和手機(jī)职辨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)戈二,“玉大人舒裤,你說我怎么就攤上這事【蹩裕” “怎么了腾供?”我有些...
    開封第一講書人閱讀 168,130評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)鲜滩。 經(jīng)常有香客問我伴鳖,道長(zhǎng),這世上最難降的妖魔是什么徙硅? 我笑而不...
    開封第一講書人閱讀 59,648評(píng)論 1 297
  • 正文 為了忘掉前任榜聂,我火速辦了婚禮,結(jié)果婚禮上嗓蘑,老公的妹妹穿的比我還像新娘须肆。我一直安慰自己,他們只是感情好桩皿,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評(píng)論 6 397
  • 文/花漫 我一把揭開白布豌汇。 她就那樣靜靜地躺著,像睡著了一般泄隔。 火紅的嫁衣襯著肌膚如雪拒贱。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評(píng)論 1 309
  • 那天佛嬉,我揣著相機(jī)與錄音柜思,去河邊找鬼岩调。 笑死,一個(gè)胖子當(dāng)著我的面吹牛赡盘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播缰揪,決...
    沈念sama閱讀 40,835評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼陨享,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了钝腺?” 一聲冷哼從身側(cè)響起抛姑,我...
    開封第一講書人閱讀 39,740評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎艳狐,沒想到半個(gè)月后定硝,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡毫目,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評(píng)論 3 340
  • 正文 我和宋清朗相戀三年蔬啡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片镀虐。...
    茶點(diǎn)故事閱讀 40,505評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡箱蟆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出刮便,到底是詐尸還是另有隱情空猜,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評(píng)論 5 350
  • 正文 年R本政府宣布恨旱,位于F島的核電站辈毯,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏搜贤。R本人自食惡果不足惜谆沃,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評(píng)論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望入客。 院中可真熱鬧管毙,春花似錦、人聲如沸桌硫。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)铆隘。三九已至卓舵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間膀钠,已是汗流浹背掏湾。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工裹虫, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人融击。 一個(gè)月前我還...
    沈念sama閱讀 48,921評(píng)論 3 376
  • 正文 我出身青樓筑公,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親尊浪。 傳聞我的和親對(duì)象是個(gè)殘疾皇子匣屡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容