华为1+x 四项服务的创建

配置环境

build.gradle(app)

plugins {
    id 'com.android.application'
    id 'com.huawei.agconnect'
}
 signingConfigs {
            release {
                storeFile file('gsy06.jks')
                keyAlias 'key0'
                keyPassword '123456'
                storePassword '123456'
                v1SigningEnabled true
                v2SigningEnabled true
            }
        }
buildTypes {
            release {
                signingConfig signingConfigs.release
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
            debug {
                signingConfig signingConfigs.release
                debuggable true
            }
        }
 dependencies {
        implementation 'com.huawei.agconnect:agconnect-core:1.9.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'

        implementation 'com.huawei.hms:location:6.4.0.300'

        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 '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'
    }

build.gradle

buildscript {
    repositories {
        google()
        jcenter()
        //需要插入的代码
        maven { url 'https://developer.huawei.com/repo/' }
    }
 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
        //需要插入的代码
        classpath 'com.huawei.agconnect:agcp:1.9.0.300'
    }

验证码登录        idtoken登录        静默登录        定位服务        机器学习服务        

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="验证码登录"
        tools:layout_editor_absoluteX="121dp"
        tools:layout_editor_absoluteY="115dp" />

    <Button
        android:id="@+id/btn_idtoken"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="idtoken"
        tools:layout_editor_absoluteX="145dp"
        tools:layout_editor_absoluteY="330dp" />

    <Button
        android:id="@+id/btn_silent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="静默登录"
        tools:layout_editor_absoluteX="175dp"
        tools:layout_editor_absoluteY="240dp" />

    <Button
        android:id="@+id/btn_signout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消授权"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="493dp" />
    <Button
        android:id="@+id/btn_cancelauth"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="退出"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="493dp" />
    <Button
        android:id="@+id/btn_request_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启定位"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="493dp" />
    <Button
        android:id="@+id/btn_remove_location"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭定位"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="493dp" />
    <Button
        android:id="@+id/btn_local_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="文本识别"
        tools:layout_editor_absoluteX="140dp"
        tools:layout_editor_absoluteY="493dp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:srcCompat="@tools:sample/avatars" />
</androidx.appcompat.widget.LinearLayoutCompat>

AndroidManifest.xml

    <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" />

    tools:replace="android:allowBackup"
    
    <service android:name=".MyHmsMessageService" android:exported="false">
            <intent-filter>
                <action android:name="com.huawei.push.action.MESAGING_EVENT"/>
            </intent-filter>
    </service>

MainActity.java


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 AccountAuthService services;

    private LocationCallback locationCallback;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private ImageView imageView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();

        
        Context context = MainActivity.this;
        MyHmsMessageService.getToken(context);
    }

    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_request_location);
        btnRemoveLocation = findViewById(R.id.btn_remove_location);
        btnLocalText = findViewById(R.id.btn_local_text);
        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);

        services = getAuthCodeSignInServices();

        locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                System.out.println("======= location" + locationResult.getLocations().toString());
            }
        };

        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);

    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_authcode:
                authcode(services);
                break;
            case R.id.btn_idtoken:
                idtokend();
                break;
            case R.id.btn_silent:
                silent();
                break;
            case R.id.btn_signout:
                signout(services);
                break;
            case R.id.btn_cancelauth:
                cancelauth(services);
                break;
            case R.id.btn_request_location:
                request();
                break;
            case R.id.btn_remove_location:
                remove();
                break;
            case R.id.btn_local_text:
                analyText();
                break;
        }

    }


    private AccountAuthService getAuthCodeSignInServices() {
        AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
        AccountAuthService service = AccountAuthManager.getService(this, params);
        return service;
    }


    private void authcode(AccountAuthService services) {
        startActivityForResult(services.getSignInIntent(), 8888);

    }

    private void idtokend() {
        AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
        AccountAuthService service = AccountAuthManager.getService(this, params);
        startActivityForResult(service.getSignInIntent(), 7777);
    }

    private void silent() {
        AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
        AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
        Task<AuthAccount> task = services.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 signout(AccountAuthService services) {
        Task<Void> task = services.cancelAuthorization();
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                System.out.println("=====================取消授权成功");
            }
        });
    }

    private void cancelauth(AccountAuthService services) {
        Task<Void> task = services.signOut();
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                System.out.println("=====================退出成功");
            }
        });
    }


    private void request() {
        LocationRequest locationRequest = new LocationRequest()
                .setInterval(3000)
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


        Task<Void> task = fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());

        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    System.out.println("=============成功");
                } else {
                    System.out.println("=============失败");
                }

            }
        });

    }

    private void remove() {
        Task<Void> task = fusedLocationProviderClient.removeLocationUpdates(locationCallback);
        task.addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(Task<Void> task) {
                if (task.isSuccessful()) {
                    System.out.println("=============成功");
                } else {
                    System.out.println("=============失败");
                }

            }
        });
    }

    private void analyText() {
        MLLocalTextSetting zh = new MLLocalTextSetting.Factory()
                .setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
                .setLanguage("zh")
                .create();

        MLTextAnalyzer localTextAnalyzer = MLAnalyzerFactory
                .getInstance()
                .getLocalTextAnalyzer();

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text);

        imageView.setImageBitmap(bitmap);


        MLFrame frame = MLFrame.fromBitmap(bitmap);

        Task<MLText> task = localTextAnalyzer.asyncAnalyseFrame(frame);

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        //授权登录结果处理,从AuthAccount中获取Authorization Code
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 8888) {
            Task<AuthAccount> task = AccountAuthManager.parseAuthResultFromIntent(data);
            if (task.isSuccessful()) {
                System.out.println("=====================" + task.getResult().toString());
            } else {
                System.out.println("===========================" + task.getException().toString());
            }
        }

        if (requestCode == 7777) {
            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());
                    }
                }
            });

        }

    }

}

MyHmsMessageService.java
public class MyHmsMessageService  extends HmsMessageService {
     public static void getToken(Context context){
         new Thread(){
             @Override
             public void run() {


                 try {
                     String app_id="108267651";
                     String tokenScope = "HCM";
                     String token = HmsInstanceId.getInstance(context).getToken(app_id, tokenScope);
                     System.out.println("============="+token);
                 } catch (ApiException e) {
                     e.printStackTrace();
                 }
             }
         }.start();
     }
}

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

执初初

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值