欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

新浪微博分享

程序员文章站 2022-06-26 15:19:41
...

新浪微博分享

//这里张某分享一种不怎么繁杂的方式,去掉了一些不怎么用得到的方法以及代码
第一步:申请你 App key

到微博开发平台上,我的应用页面 ,通过开发者身份验证审核完善应用信息将该应用提交审核,只有审核通过的应用才能进行开发。

第二步:注册应用程序的包名以及签名
包名和签名未注册,或者签名注册不正确,都会导致无发授权报错

在进程的build.gradle中添加自己所需的依赖

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        //为了方便一点,这里我直接把自己里的依赖全部导入进来的,其实进程中的依赖就两句代码     这里打删除线的就是所需要的依赖,

    ~~maven { url'https://dl.bintray.com/thelasterstar/maven/'}
        maven { url'https://dl.bintray.com/umsdk/release' }~~ 

        maven { url'https://dl.bintray.com/thelasterstar/maven/'}

        maven { url'https://dl.bintray.com/umsdk/release' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
    //到了这里我们再把上面导入的依赖再倒入一遍
        maven { url'https://dl.bintray.com/thelasterstar/maven/'}

        maven { url'https://dl.bintray.com/umsdk/release' }
        google()
        jcenter()

    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

接下来就是在自己项目里导入所需的依赖

plugins {
    id 'com.android.application'
}

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.cs"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
	//这里导入的依赖比较的繁琐,所以我还是把我应用内的所有依赖导入进来

    // ndk{
//这里我们看到,所注释的代码就是我们要导入的依赖
     //       abiFilters'armeabi' //, 'armeabi-v7a','arm64-v8a'

    //    }


        ndk{

            abiFilters'armeabi' //, 'armeabi-v7a','arm64-v8a'

        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'



    implementation'com.sina.weibo.sdk:core:9.12.0:[email protected]'

    implementation"com.umeng.umsdk:common:9.1.0"

	// asms包依赖(必选)
    implementation"com.umeng.umsdk:asms:1.1.3" 
	 // native crash包依赖(必选
    implementation"com.umeng.umsdk:crash:0.0.4"
}

在AndroidManifest.xml中添加权限:

//网络权限以及写
   <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

走到这里我们所需要的配置基本以及配置完毕。
初始化代码如下:

public class MainActivity extends AppCompatActivity {
   private static final String APP_KY = "在微博开发平台申请的App的key";
    private static final String REDIRECT_URL = "在微博开发平台的回调路径";
    //http://www.sina.com
    private static final String SCOPE ="在微博开发平台申请的高级权限";
    //"email,direct_messages_read,direct_messages_write,"
                    + "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
                    + "follow_app_official_microblog," + "invitation_write"

    private IWBAPI mWBAPI;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initSdk();
        initView();
    }

    private void initView() {
        Button bnt = findViewById(R.id.bnt);
        bnt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              doWeiboShare();
             //   initSdk();
            }
        });
    }

    private void initSdk() {
        AuthInfo authInfo = new AuthInfo(this, APP_KY, REDIRECT_URL, SCOPE);
        mWBAPI = WBAPIFactory.createWBAPI(this);
        mWBAPI.registerApp(this, authInfo);
    }
    private void startAuth() {
        //auth
        mWBAPI.authorize(new WbAuthListener() {
            @Override
            public void onComplete(Oauth2AccessToken token) {
                Toast.makeText(MainActivity.this, "微博授权成功", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onError(UiError error) {
                Toast.makeText(MainActivity.this, "微博授权出错",Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onCancel() {
                Toast.makeText(MainActivity.this, "微博授权出错", Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mWBAPI != null) {
            mWBAPI.doResultIntent(data,new ShareCallback());
        }
    }

    //
    private  class ShareCallback implements WbShareCallback {
        @Override
        public void onComplete() {
            Toast.makeText(MainActivity.this, "分享成功",Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onError(UiError error) {
            Toast.makeText(MainActivity.this, "分享失败" + error.errorMessage, Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onCancel() {
            Toast.makeText(MainActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
        }
    }



    private void doWeiboShare() {
        WeiboMultiMessage message = new WeiboMultiMessage();
        TextObject textObject = new TextObject();
        String text = "测试";
        textObject.text = text;
        message.textObject = textObject;
        mWBAPI.shareMessage(message, true);
    }

}

微博不止一种分享方式
下面:

 private void doWeiboShare() {
 WeiboMultiMessage message = new WeiboMultiMessage();
 
//分享单图
 if (mShareImage.isChecked()) {
 ImageObject imageObject = new ImageObject();
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.share_image);
 imageObject.setImageData(bitmap);
 message.imageObject = imageObject;
 
//分享网页
 if (mShareUrl.isChecked()) {
 WebpageObject webObject = new WebpageObject();
 webObject.identify = UUID.randomUUID().toString();
 webObject.title = "标题"
 webObject.description = "描述"
 Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo);
 ByteArrayOutputStream os = null;
 try {
 os = new ByteArrayOutputStream();
 bitmap.compress(Bitmap.CompressFormat.JPEG, 85, os);
 webObject.thumbData = os.toByteArray();
 } catch (Exception e) {
微博SDK 2019/12/11, 11:16
http://localhost:8081/#/docs/user-guide/instruction-android Page 8 of 9
 e.printStackTrace();
 } finally {
 try {
 if (os != null) {
 os.close();
 }
 } catch (IOException e) {
 e.printStackTrace();
        }
     }
 }
 webObject.actionUrl = "https://weibo.com";
 webObject.defaultText = "分享网页";
 message.mediaObject = webObject;
 }
//分享多图

 if (mShareMultiImage.isChecked()) {
 MultiImageObject multiImageObject = new MultiImageObject();
 List<Uri> list = new ArayList<Uri>()Ҕ
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/aaa.png")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/ccc.JPG")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/ddd.jpg")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/fff.jpg")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/ggg.JPG")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/eee.jpg")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/hhhh.jpg")));
 list.add(Uri.fromFile(new File(getExternalFilesDir(null) + "/kkk.JPG")));
 multiImageObject.imageList = list;
 message.multiImageObject = multiImageObject;
 }
//分享视频

 if (mShareVideo.isChecked()) {
 VideoSourceObject videoObject = new VideoSourceObject();
 videoObject.videoPath = Uri.fromFile(new File(getExternalFilesDir(null) + "/eeee.mp4"));
 message.videoSourceObject = videoObject;
 }

// mShareClientOnly.isChecked()表示是否只通过微博客户端分享
mWBAPI.shareMessage(message, mShareClientOnly.isChecked());