1+x移动应用开发(中级) 账号服务集成 推送服务 定位服务 机器学习服务(文本识别)

项目级环境搭建

// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    repositories {
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'}
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"
        classpath 'com.huawei.agconnect:agcp:1.9.0.300'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'}
    }
}

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

模块级环境搭建

plugins {
    id 'com.android.application'
    id 'com.huawei.agconnect'
}

android {
    compileSdkVersion 33
    buildToolsVersion "30.0.2"

    defaultConfig {
        applicationId "com.st.hms_051301_sh"
        minSdkVersion 19
        targetSdkVersion 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    signingConfigs{
        release{
            storeFile file("hms_051301_sh.jks")
            keyAlias "key0"
            keyPassword "123456"
            storePassword "123456"
            v1SigningEnabled true
            v2SigningEnabled true
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug{
            signingConfig signingConfigs.release
            debuggable true
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

dependencies {
    //文本识别依赖
    implementation 'com.huawei.hms:ml-computer-vision-ocr:3.11.0.301'
    implementation 'com.huawei.hms:ml-computer-vision-ocr-cn-model:3.11.0.301'
    //定位依赖
    implementation 'com.huawei.hms:location:6.4.0.300'
    //推送依赖
    implementation 'com.huawei.hms:push:6.9.0.300'
    //账号登陆依赖
    implementation 'com.huawei.hms:hwid:6.9.0.301'
    implementation 'com.huawei.hms:hmscoreinstaller:6.6.0.300'
    //hms集成依赖
    implementation 'com.huawei.agconnect:agconnect-core:1.9.0.300'



    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
 

在华为开发者联盟创建项目并将agconnect-services.json文件放入app目录下

 

然后在Build选项中配置指纹签名放入app目录下并在绑定项目

AndroidManifest.xml配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.st.hms_051301_sh">
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        tools:replace="android:allowBackup"
        android:theme="@style/Theme.Hms_051301_sh">
        <service android:name=".MyHmsMessageService" android:exported="false"
            tools:ignore="Instantiatable">
            <intent-filter>
                <action android:name="com.huawei.push.action.MESSAGING_EVENT"/>
            </intent-filter>
        </service>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main.xml布局代码

<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.LinearLayoutCompat xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_authcode"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="账号验证登陆" />

    <Button
        android:id="@+id/btn_idtoken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="idtoken登陆" />

    <Button
        android:id="@+id/btn_silent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="静默登陆" />

    <Button
        android:id="@+id/btn_signout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="退出" />

    <Button
        android:id="@+id/btn_cancelauth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消授权" />

    <Button
        android:id="@+id/btn_requestLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启定位" />

    <Button
        android:id="@+id/btn_removeLocation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        android:text="移除定位" />

    <Button
        android:id="@+id/btn_localText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文本识别" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:srcCompat="@drawable/ic_launcher_background"
        tools:ignore="VectorDrawableCompat" />


</androidx.appcompat.widget.LinearLayoutCompat>

MainActivity代码

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import android.os.Looper;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.huawei.hmf.tasks.OnCompleteListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.location.FusedLocationProviderClient;
import com.huawei.hms.location.LocationCallback;
import com.huawei.hms.location.LocationRequest;
import com.huawei.hms.location.LocationResult;
import com.huawei.hms.location.LocationServices;
import com.huawei.hms.mlsdk.MLAnalyzerFactory;
import com.huawei.hms.mlsdk.common.MLFrame;
import com.huawei.hms.mlsdk.text.MLLocalTextSetting;
import com.huawei.hms.mlsdk.text.MLText;
import com.huawei.hms.mlsdk.text.MLTextAnalyzer;
import com.huawei.hms.support.account.AccountAuthManager;
import com.huawei.hms.support.account.request.AccountAuthParams;
import com.huawei.hms.support.account.request.AccountAuthParamsHelper;
import com.huawei.hms.support.account.result.AuthAccount;
import com.huawei.hms.support.account.service.AccountAuthService;

import java.io.IOException;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //声明变量
    private Button btnAuthcode;
    private Button btnIdtoken;
    private Button btnSilent;
    private Button btnSignout;
    private Button btnCancelauth;
    private Button btnRequestLocation;
    private Button btnRemoveLocation;
    private Button btnLocalText;
    private ImageView imageView;

    //初始化账号服务
    private AccountAuthService service;
    //初始化定位
    private LocationCallback locationCallback;
    private FusedLocationProviderClient fusedLocationProviderClient;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Context context = MainActivity.this;
        //调用MyMessageService.getToken获取token
        MyMessageService.getToken(context);

        initView();
    }

    private void initView() {
        //绑定按钮
        btnAuthcode = findViewById(R.id.btn_authcode);
        btnIdtoken = findViewById(R.id.btn_idtoken);
        btnSilent = findViewById(R.id.btn_silent);
        btnSignout = findViewById(R.id.btn_signout);
        btnCancelauth = findViewById(R.id.btn_cancelauth);
        btnRequestLocation = findViewById(R.id.btn_requestLocation);
        btnRemoveLocation = findViewById(R.id.btn_removeLocation);
        btnLocalText = findViewById(R.id.btn_localText);
        imageView = findViewById(R.id.imageView);


        //给按钮设置监听事件
        btnAuthcode.setOnClickListener(this);
        btnIdtoken.setOnClickListener(this);
        btnSilent.setOnClickListener(this);
        btnSignout.setOnClickListener(this);
        btnCancelauth.setOnClickListener(this);
        btnRequestLocation.setOnClickListener(this);
        btnRemoveLocation.setOnClickListener(this);
        btnLocalText.setOnClickListener(this);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_authcode:
                authcodeSignIn();
                break;
            case R.id.btn_idtoken:
                idTokenSignIn();
                break;
            case R.id.btn_silent:
                SilentSignIn();
                break;
            case R.id.btn_signout:
                authSignOut();
                break;
            case R.id.btn_cancelauth:
                cancelAuth();
                break;
            case R.id.btn_requestLocation:
                requestLocation();
                break;
            case R.id.btn_removeLocation:
                removeLocation();
                break;
            case R.id.btn_localText:
                analyseText();
                break;
        }
    }
    //账号验证登陆
    private void authcodeSignIn() {
        //通过AuthorizationCode的方式创建并获取账号认证参数params
        AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
        //根据账号认证管理的参数得到账号授权服务
        service = AccountAuthManager.getService(this, params);
        //开启一个页面获取获取账号授权服务的结果
        startActivityForResult(service.getSignInIntent(),7777);
    }
    //idtoken登陆
    private void idTokenSignIn(){
        //通过idtoken的方式创建并获取账号认证参数Params
        AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
        //根据账号认证管理的参数得到账号授权服务
         service = AccountAuthManager.getService(this, params);
         //开启一个页面获取账号授权服务的结果
        startActivityForResult(service.getSignInIntent(),8888);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //判断请求码
        if(requestCode==7777){
            //根据账号授权管理的结果去获取一个会话task
            Task<AuthAccount> task = AccountAuthManager.parseAuthResultFromIntent(data);
            //为task设置监听事件
            task.addOnCompleteListener(new OnCompleteListener<AuthAccount>() {
                @Override
                //判断task是否成功
                public void onComplete(Task<AuthAccount> task) {
                    if (task.isSuccessful()) {
                        //成功打印返回的账号信息
                        System.out.println("===="+task.getResult().toString());
                    }else{
                        //失败打印异常信息
                        System.out.println("===="+task.getException().toString());
                    }
                }
            });
        }
        //注释同上
        if (requestCode==8888){
            Task<AuthAccount> task = AccountAuthManager.parseAuthResultFromIntent(data);
            task.addOnCompleteListener(new OnCompleteListener<AuthAccount>() {
                @Override
                public void onComplete(Task<AuthAccount> task) {
                    if (task.isSuccessful()) {
                        System.out.println("===="+task.getResult().toString());
                    }else{
                        System.out.println("===="+task.getException().toString());
                    }
                }
            });
        }
    }
    //静默登陆
    private void SilentSignIn(){
        //获取账号认证的参数params
        AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
        service = AccountAuthManager.getService(this, params);
        Task<AuthAccount> task = service.silentSignIn();
        task.addOnCompleteListener(new OnCompleteListener<AuthAccount>() {
            @Override
            public void onComplete(Task<AuthAccount> task) {
                if (task.isSuccessful()) {
                    System.out.println("===="+task.getResult().toString());
                }else{
                    System.out.println("===="+task.getException().toString());
                }
            }
        });
    }
    //退出登陆
    private void authSignOut(){
        //通过账号授权服务提供的退出登陆方法来得到一个会话
        Task<Void> task = service.signOut();
        //为会话task设置一个监听事件
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            //判断会话的成功与否来打印提示信息
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    System.out.println("====Sign out successful");
                }else{
                    System.out.println("====Sign out failure");
                }
            }
        });
    }
    //取消授权
    private void cancelAuth(){
        //通过账号授权服务提供的取消授权方法来得到一个会话
        Task<Void> task = service.cancelAuthorization();
        //为task设置监听事件
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            //判断会话的成功与否来打印提示信息
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    System.out.println("==== cancelAuth successful");
                }else{
                    System.out.println("==== cancelAuth failure");
                }
            }
        });
    }
    //获取定位
    private void requestLocation(){
        //使用定位服务获取fusedLocationProviderClient对象
         fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
        //设置请求参数
        LocationRequest locationRequest = new LocationRequest()
                //设置位置更新间隔的时间
                .setInterval(3000)
                //设置定位的类型
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
         locationCallback = new LocationCallback(){
             @Override
             //重写定位返回的结果
             public void onLocationResult(LocationResult locationResult) {
                 //打印当前定位信息
                 System.out.println("====location "+locationResult.getLocations().toString());
             }
         };
         //根据上面location 和 locationCallback参数使用fusedLocationProviderClient对象获取定位信息
         fusedLocationProviderClient.requestLocationUpdates(locationRequest ,locationCallback, Looper.myLooper())
                 .addOnCompleteListener(new OnCompleteListener<Void>() {
                     @Override
                     public void onComplete(Task<Void> task) {
                         if (task.isSuccessful()) {
                             System.out.println("====request location successful ");
                         }else{
                             System.out.println("====request location failure");
                         }
                     }
                 });
    }
    //移除定位
    private void removeLocation(){
        //使用fusedLocationProviderClient对象的移除定位方法来返回一个会话
        Task<Void> task = fusedLocationProviderClient.removeLocationUpdates(locationCallback);
        //为task会话设置监听事件
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    System.out.println("====remove location successful");
                }else{
                    System.out.println("====remove location failure");
                }
            }
        });
    }
    //文本识别
    private void analyseText() {
        //使用自定义参数MLLocalTextSetting配置端侧文本分析器
        MLLocalTextSetting mlLocalTextSetting = new MLLocalTextSetting.Factory()
                //设置一个OCRMode常量
                .setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
                //设置识别语种
                .setLanguage("zh")
                .create();

        MLTextAnalyzer localTextAnalyzer = MLAnalyzerFactory
                .getInstance()
                .getLocalTextAnalyzer(mlLocalTextSetting);
        // 通过bitmap创建MLFrame,bitmap为输入的Bitmap格式图片数据
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text);
        imageView.setImageBitmap(bitmap);
        MLFrame mlFrame = MLFrame.fromBitmap(bitmap);

        Task<MLText> mlTextTask = localTextAnalyzer.asyncAnalyseFrame(mlFrame);
        mlTextTask.addOnCompleteListener(new OnCompleteListener<MLText>() {
            @Override
            public void onComplete(Task<MLText> task) {
                if (task.isSuccessful()) {
                    System.out.println("==== successful" + task.getResult().getStringValue());
                } else {
                    System.out.println("==== failure" + task.getException().toString());
                }
            }
        });
        try {
            localTextAnalyzer.stop();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

MyHmsMessageService页面代码

import android.content.Context;

import com.huawei.agconnect.config.AGConnectServicesConfig;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.huawei.hms.push.HmsMessageService;
public class MyHmsMessageService {
    public static void getToken(Context context){
        //开启一个线程
        new Thread(){
            @Override
            public void run() {

                try {
                    //从agconnect-services.json文件中读取app_id
                    String app_id= "108280109";
                    //输入token标识HCM
                    String tokenScope="HCM";
                    //获取到token
                    String token = HmsInstanceId.getInstance(context).getToken(app_id, tokenScope);
                    //打印token
                    System.out.println("=====token"+token);
                } catch (ApiException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}

最终在模拟器上的效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值