android基础知识----自带的分享

我一直都在sharesdk分享,没怎么用,今天这里就用下,顺便记录下挺简单的。
最主要的三种
1. 分享文本

Intent intent1=new Intent(Intent.ACTION_SEND);
                intent1.putExtra(Intent.EXTRA_TEXT,"This is my text to send");
                intent1.setType("text/plain");
                startActivity(Intent.createChooser(intent1,"文本分享"));
  1. 分享单张图片
Intent intent2=new Intent(Intent.ACTION_SEND);
                Uri uri= Uri.parse(picturePath);
                intent2.setType("image/*");
                intent2.putExtra(Intent.EXTRA_STREAM,uri);
                startActivity(Intent.createChooser(intent2,"单图片分享"));
  1. 分享多张图片
 ArrayList<Uri> imageUris = new ArrayList<Uri>();
                Uri imageUri1 = Uri.parse(picturePath);
                Uri imageUri2 = Uri.parse(picturePath);
                imageUris.add(imageUri1);
                imageUris.add(imageUri2);

                Intent intent3 = new Intent();
                intent3.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent3.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                intent3.setType("image/*");
                startActivity(Intent.createChooser(intent3, "多图片分享"));

如果你要传文件的话就设置

   intent4.setType("*/*");

当然我们还可以设置指向qq或者微信分享

QQ

Intent qqIntent = new Intent(Intent.ACTION_SEND);
                qqIntent.setPackage("com.tencent.mobileqq");
                qqIntent.setType("text/plain");
                qqIntent.putExtra(Intent.EXTRA_TEXT, "分享到微信的内容");
                startActivity(qqIntent);

微信

  Intent wechatIntent = new Intent(Intent.ACTION_SEND);
                wechatIntent.setPackage("com.tencent.mm");
                wechatIntent.setType("text/plain");
                wechatIntent.putExtra(Intent.EXTRA_TEXT, "分享到微信的内容");
                startActivity(wechatIntent);

好了,但是这里有个问题,就是如果你没有装微信或者QQ的话,那么你指向分享会报错崩溃,这是不被允许的错误,所以要加上判断。

 /**
     *判断微信是否可用  true可用
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

然后给出我的测试代码

package com.example.admin.fenxiang;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

import static android.os.Environment.getExternalStorageDirectory;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    private Button btnText;
    private Button btnDan;
    private Button btnDuo;
    private Button btnFile;
    private Button btnQq;
    private Button btnWexin;
    private Button btnTuwen;
    private  final int REQUEST_WRITE=1;//申请权限的请求码
    private File path;
    private Uri file;//存放图片的文件名
    String picturePath;//图片路径
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
    }
    public void initView(){
        btnText = (Button) findViewById(R.id.btn_text);
        btnDan = (Button) findViewById(R.id.btn_dan);
        btnDuo = (Button) findViewById(R.id.btn_duo);
        btnFile = (Button) findViewById(R.id.btn_file);
        btnQq = (Button) findViewById(R.id.btn_qq);
        btnWexin = (Button) findViewById(R.id.btn_wexin);
        btnTuwen = (Button) findViewById(R.id.btn_tuwen);
        btnText.setOnClickListener(this);
        btnDan.setOnClickListener(this);
        btnDuo.setOnClickListener(this);
        btnFile.setOnClickListener(this);
        btnQq.setOnClickListener(this);
        btnWexin.setOnClickListener(this);
        btnTuwen.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_text:
                Intent intent1=new Intent(Intent.ACTION_SEND);
                intent1.putExtra(Intent.EXTRA_TEXT,"This is my text to send");
                intent1.setType("text/plain");
                startActivity(Intent.createChooser(intent1,"文本分享"));
                break;
            case R.id.btn_dan:
                if (picturePath==null){
                    Toast.makeText(MainActivity.this,"先获取分享的图片",Toast.LENGTH_SHORT).show();
                    return;
                }
                Intent intent2=new Intent(Intent.ACTION_SEND);
                Uri uri= Uri.parse(picturePath);
                intent2.setType("image/*");
                intent2.putExtra(Intent.EXTRA_STREAM,uri);
                startActivity(Intent.createChooser(intent2,"单图片分享"));
                break;
            case R.id.btn_duo:
                if (picturePath==null){
                    Toast.makeText(MainActivity.this,"先获取分享的图片",Toast.LENGTH_SHORT).show();
                    return;
                }
                ArrayList<Uri> imageUris = new ArrayList<Uri>();
                Uri imageUri1 = Uri.parse(picturePath);
                Uri imageUri2 = Uri.parse(picturePath);
                imageUris.add(imageUri1);
                imageUris.add(imageUri2);

                Intent intent3 = new Intent();
                intent3.setAction(Intent.ACTION_SEND_MULTIPLE);
                intent3.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imageUris);
                intent3.setType("image/*");
                startActivity(Intent.createChooser(intent3, "多图片分享"));
                break;
            case R.id.btn_file:
                applyPermission();
                Intent intent4=new Intent(Intent.ACTION_SEND);
                Uri uri4= Uri.parse(path.getAbsolutePath());//  Uri u = Uri.fromFile(f);
                intent4.putExtra(Intent.EXTRA_STREAM,uri4);
                intent4.setType("*/*");
                startActivity(Intent.createChooser(intent4,"单文件分享"));
                break;
            case R.id.btn_qq:
                if (isQQClientAvailable(MainActivity.this)){
                    Intent qqIntent = new Intent(Intent.ACTION_SEND);
                    qqIntent.setPackage("com.tencent.mobileqq");
                    qqIntent.setType("text/plain");
                    qqIntent.putExtra(Intent.EXTRA_TEXT, "分享到QQ的内容");
                    startActivity(qqIntent);
                }else {
                    Toast.makeText(MainActivity.this,"手机没有安装QQ",Toast.LENGTH_SHORT).show();
                }


                break;
            case R.id.btn_wexin:
                if (isWeixinAvilible(MainActivity.this)){
                    Intent wechatIntent = new Intent(Intent.ACTION_SEND);
                    wechatIntent.setPackage("com.tencent.mm");
                    wechatIntent.setType("text/plain");
                    wechatIntent.putExtra(Intent.EXTRA_TEXT, "分享到微信的内容");
                    startActivity(wechatIntent);
                }else {
                    Toast.makeText(MainActivity.this,"手机没有安装微信",Toast.LENGTH_SHORT).show();
                }

                break;
            case R.id.btn_tuwen:

                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, 1001);
                break;
        }
    }

    /**
     * res中的图片转变为uri
     * @param id
     * @return
     */
    private String getResourcesUri(@DrawableRes int id) {
        Resources resources = getResources();
        String uriPath = ContentResolver.SCHEME_ANDROID_RESOURCE + "://" +
                resources.getResourcePackageName(id) + "/" +
                resources.getResourceTypeName(id) + "/" +
                resources.getResourceEntryName(id);
        Toast.makeText(this, "Uri:" + uriPath, Toast.LENGTH_SHORT).show();
        return uriPath;
    }
    //写数据
    public void writeToSdCard(){
        //1、判断sd卡是否可用
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
            //sd卡可用
            //2、获取sd卡路径
            File sdFile= getExternalStorageDirectory();
            path=new File(sdFile,"a.txt");//sd卡下面的a.txt文件  参数 前面 是目录 后面是文件
            try {
                FileOutputStream fileOutputStream=new FileOutputStream(path);
                fileOutputStream.write("我要SSR".getBytes());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /*
    考虑android6.0的权限问题
     */
    public void applyPermission(){
        //判断是否6.0以上的手机   不是就不用
        if(Build.VERSION.SDK_INT>=23){
            //判断是否有这个权限
            if(ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                    //2、申请权限: 参数二:权限的数组;参数三:请求码
                    ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_WRITE);
            }else {
                writeToSdCard();
            }
        } else{
            writeToSdCard();
        }
    }

    //判断授权的方法  授权成功直接调用写入方法  这是监听的回调
    //参数  上下文   授权结果的数组   申请授权的数组
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==REQUEST_WRITE&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
            writeToSdCard();
        }

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//
        if (resultCode==RESULT_OK){
            switch (requestCode) {
                case 1001:
                    //相册选择
                    if (data != null) {
                        String[] filePathColumn = { MediaStore.Images.Media.DATA };

                        Cursor cursor = getContentResolver().query(data.getData(),
                                filePathColumn, null, null, null);
                        cursor.moveToFirst();

                        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                        picturePath = cursor.getString(columnIndex);
                        cursor.close();
                        Log.e("====",picturePath);
                    }
                    break;

            }
        }
    }

    /**
     *判断微信是否可用  true可用
     * @param context
     * @return
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 判断qq是否可用
     *
     * @param context
     * @return
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

}

好了,到此为止。。。。。祝大家五一快乐。

发布了116 篇原创文章 · 获赞 30 · 访问量 19万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章