Android 實現多圖分享到微信朋友圈

1.初始的步驟可以先參考:
Android 實現微信分享好友和朋友圈
http://blog.csdn.net/unique_even/article/details/71717368

2.剛開始我採用微信開放平臺給出的接口來分享圖片,但是隻能分享一張,之後各種搜索,找到了新的思路(可以參考下:http://blog.csdn.net/qq_27030835/article/details/50828352),是先把圖片緩存下來,之後在去分享。

1.ShareActivity 類

public class ShareActivity  extends Activity{
    private Button mButtonGetValue; // 獲取數據按鈕
    private GridView mListView;// 數據展示列表
    private CheckboxAdapter listItemAdapter; // ListView數據展示適配器
    private ArrayList<HashMap<String, Object>> listData;// ListView展示數據源
    private WeChatShareUtil weChatShareUtil;
    Context context;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.z_shareactivity);
        context = this;
        initView();
        registerListener();
        listData = new ArrayList<HashMap<String, Object>>();
        initListViewData(listData);
        loadData();
        weChatShareUtil = WeChatShareUtil.getInstance(this);

    }

    /**
     * 初始化佈局
     */
    private void initView() {
        mButtonGetValue = (Button) findViewById(R.id.get_value);
        mListView = (GridView) findViewById(R.id.list);
    }

    private void registerListener() {
        mButtonGetValue.setOnClickListener((View.OnClickListener) new OnClickListenerImpl());
    }

    /**
     * 加載數據
     */
    private void loadData() {
        listItemAdapter = new CheckboxAdapter(this, listData);
        mListView.setAdapter(listItemAdapter);
    }

    /**
     * 初始化ListView數據源
     *
     * @param listData
     */
    private void initListViewData(ArrayList<HashMap<String, Object>> listData) {
        if (listData == null)
            listData = new ArrayList<HashMap<String, Object>>();
        for (int i = 0; i < 12; i++) {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("friend_image", "http://imgsrc.baidu.com/imgad/pic/item/b58f8c5494eef01f4b2237c5eafe9925bc317dff.jpg");
            map.put("selected", false);
            // 向容器添加數據
            listData.add(map);
        }
    }




    private class OnClickListenerImpl implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            new Thread(saveFileRunnable).start();
        }
    }

    private Runnable saveFileRunnable = new Runnable(){
        @Override
        public void run() {
            try {
                List<HashMap<String, Object> >sList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object>  s = new HashMap<String, Object>();
                    int IMAGE_NAME = 0;
                for(int i=0;i<listItemAdapter.getNumdata().size();i++){
                    IMAGE_NAME++;
                    String imageFileName = Integer.toString(IMAGE_NAME) + ".jpg";
                    s = listItemAdapter.getState().get(listItemAdapter.getNumdata().get(i).get("position"));
                    SavePhoto.downloadLyWithName((String)s.get("friend_image"),imageFileName, "phone", context);
                }
                // 遍歷 SD 卡下 .png 文件通過微信分享
                File file = new File(Environment.getExternalStorageDirectory() + "/BangMai/images/" + "phone");
                File[] files = file.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        if (pathname.getName().endsWith(".jpg")) {
                            return true;
                        }
                        return false;
                    }
                });

                Intent intent = new Intent();
                ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
                intent.setComponent(comp);
                intent.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent.setType("image/*");
                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                for (File f : files) {
                    imageUris.add(Uri.fromFile(f));
                }
                intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                intent.putExtra("Kdescription", "測試");  // 這裏可要可不要,這句話的意思是直接會顯示在發表時候的文字
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

CheckboxAdapter 類

public class CheckboxAdapter extends BaseAdapter{
    private Context context;
    private ArrayList<HashMap<String, Object>> listData;

    public ArrayList<HashMap<String, Object>> getNumdata() {
        return numdata;
    }

    public void setNumdata(ArrayList<HashMap<String, Object>> numdata) {
        this.numdata = numdata;
    }

    ArrayList<HashMap<String, Object>> numdata = new ArrayList<>();
    HashMap<String, Object>  num = new HashMap();




    public HashMap<Integer, HashMap<String, Object>> getState() {
        return state;
    }
//
    public void setState(HashMap<Integer, HashMap<String, Object>> state) {
        this.state = state;
    }

    //checkbox選中的數據
    HashMap<Integer, HashMap<String, Object>> state = new HashMap<Integer, HashMap<String, Object>>();

    // 構造方法初始化數據
    public CheckboxAdapter(Context context, ArrayList<HashMap<String, Object>> listData) {
        this.context = context;
        this.listData = listData;
    }

    @Override
    public int getCount() {
        return (listData != null && !listData.isEmpty())?listData.size():0;
    }

    @Override
    public Object getItem(int position) {
        return listData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        LayoutInflater mInflater = LayoutInflater.from(context);
        convertView = mInflater.inflate(R.layout.z_item_list, null);
        ImageView image = (ImageView) convertView.findViewById(R.id.friend_image);
        final HashMap<String, Object> viewData = listData.get(position);
        ImageLoaders.display(context, image, (String) viewData.get("friend_image"), R.drawable.add_nor);
        CheckBox check = (CheckBox) convertView.findViewById(R.id.selected);
        check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    state.put(position, viewData);
                    num.put("position",position);
                    numdata.add(num);

                } else {
                    state.remove(position);
                    num.remove(position);

                }
            }
        });
        check.setChecked((state.get(position) == null ? false : true));

        return convertView;
    }
}

SavePhoto類(保存圖片的)

public class SavePhoto {

    //保存帶名稱的圖片
    public static Boolean downloadLyWithName(String url, String imgName, String fileName, Context context) throws Exception {
        Bitmap bitmap = null;
        byte [] data = getImage(url);
        if(data!=null){
            bitmap = BitmapFactory.decodeByteArray(data,0,data.length);
            saveImgWithName(bitmap,imgName,fileName,context);
            return true;
        }else {
            return  false;

        }

    }


    public static byte[] getImage(String path) throws Exception {
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5*1000);
        conn.setRequestMethod("GET");
        InputStream inStream = conn.getInputStream();
        if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
            return readStream(inStream);
        }
            return null;


    }

    public static byte[] readStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    //保存圖片帶名稱
    private static void saveImgWithName(Bitmap bitmap, String imgName, String fileName, Context context) {
        if (bitmap != null) {
            File appDir = new File(Environment.getExternalStorageDirectory() + "/BangMai/");
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            if (fileName != null) {
                appDir = new File(Environment.getExternalStorageDirectory() + "/BangMai/images/" + fileName);
                if (!appDir.exists()) {
                    appDir.mkdirs();
                }
            }
            File file = null;
            file = new File(appDir, imgName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                if (null != fos) {
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                    fos.flush();
                    fos.close();
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

z_item_list 佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip"
    android:paddingRight="12dip" >

    <ImageView
        android:id="@+id/friend_image"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:paddingLeft="2dip"
        android:paddingTop="6dip" />

    <CheckBox
        android:id="@+id/selected"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="36dip"
        android:focusable="false" />



</RelativeLayout>

z_shareactivity 佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/get_value"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="微信分享" />


    <GridView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:numColumns="3"
        />

</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章