xrtqh1+x:登陆、定位、推送、机器人学习
创建项目:api:24
在华为开发者联盟中创建一个项目。并将.json文件下载,移动到当前目录app文件夹下。
打开android studio (海豚版本)。
项目级(build.gradle):
// 最顶部
buildscript {
dependencies {
//增加Android Gradle插件版本号配置,{version}为实际的Gradle插件版本号,例如7.3.1。
classpath 'com.android.tools.build:gradle:7.3.1'
//增加AGC插件配置,请您参见AGC插件依赖关系选择合适的AGC插件版本。
classpath 'com.huawei.agconnect:agcp:1.9.0.300'
}
}
设置(build.gradle):
// mavenCentral()下面
maven { url 'https://developer.huawei.com/repo/' }
模块级(build.gradle):
//plugins下面
id 'com.huawei.agconnect'
...
//android{}后面
signingConfigs{
release{
storeFile file("myapp_xrtqh_xrt.jks")
keyAlias 'key0'
keyPassword '123456'
storePassword '123456'
v1SigningEnabled true
v2SigningEnabled true
}
}
...
//buildTypes {release {...}}
signingConfig signingConfigs.release
...
//buildTypes {...}
debug{
signingConfig signingConfigs.release
debuggable true
}
...
// dependencies {...}
//配置依赖
implementation 'com.huawei.agconnect:agconnect-core:1.9.0.300'
配置key:
Build ---- Generaten Signed Bundle or APK ---- 选择APK、下一步
---- Create new ---- Key store path 后面的文件夹图标 ---- 单击绿色安卓机器人 ---- 选择app目录 ---- 文件名写项目名
---- 填写四个Password、Confirm密码(建议设置相同)---- Alias 为默认不修改 ---- Certificate内的六个文本框随便填
---- 选择ok ---- Next(下一步) ---- 单击release (勾选v1、v2) ---- Finish(完成)。
配置指纹密钥
在Android视图下 ---- 在app文件上右击 ---- 选择Open in ---- 选择Explorer ---- 点开app文件夹
---- 在地址栏中输入 cmd 回车 ---- 在cmd命令界面中输入 keytool -v -list -keystore myapp_xrtqh_xrt.jks 回车
---- 输入密码(这里的密码是看不见的,输错了就多按几次回车就行) ---- 复制指纹证书中的SHA256:后面的密钥
---- 回到浏览器中的项目页面,将指纹密钥填写进指纹密钥中即可。
到这里需要同步,同步没毛病就可以正式开始四个服务的了,代码如下:
依赖添加
首先在模块级(build.gradle)中添加依赖
// 推送服务
implementation 'com.huawei.hms:push:6.9.0.300'
// implementation 'com.huawei.hms:hmscoreinstaller:6.6.0.300'
// 登陆依赖文件
implementation 'com.huawei.hms:hmscoreinstaller:6.6.0.300'
implementation 'com.huawei.hms:hwid:6.9.0.301'
// 机器人服务依赖
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.agconnect:agconnect-core:1.9.0.300'
...
<!-- 应该是推送服务·添加在“<application”内-->
tools:replace="android:allowBackup"
...
<!-- 推送服务·添加咋i“<application>”后面-->
<service android:name=".MyHmsMessageService" android:exported="false">
<intent-filter>
<action android:name="com.huawei.push.action.MESAGING_EVENT"/>
</intent-filter>
</service>
配置xml文件
在 app 目录下的 Manifests 中点开 AndroidManifest.xml 文件添加许可
<!--主要许可 定位-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--次要许可 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
到此需要同步一次
添加按钮
在app目录下的 res 目录下的layout包下的 activity_main.xml 文件添加按钮
将第二行的“<androidx.constraintlayout.widget.ConstraintLayout”改成“<LinearLayout”,最后一行也需要改成“</LinearLayout”
<Button
android:id="@+id/btn_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="btn_id"
tools:layout_editor_absoluteX="24dp"
tools:layout_editor_absoluteY="21dp"
tools:ignore="验证码登陆" />
<Button
android:id="@+id/btn_idtoken"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="idtoken登陆" />
<Button
android:id="@+id/btn_silent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="静默登陆" />
<Button
android:id="@+id/btn_cancel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="取消授权" />
<Button
android:id="@+id/btn_exstlanting"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="退出登陆" />
<Button
android:id="@+id/btn_getlocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启定位" />
<Button
android:id="@+id/btn_removelocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="关闭定位" />
<Button
android:id="@+id/btn_testsee"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="文本识别" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_launcher_background" />
#添加机器人服务·文本识别的图片
在机器人学习服务的时候需要在res包下的drawable包下添加一张用于文字识别的图片(以防失败,请选择文字清晰的图片)
推送服务类
在app目录下的 java 包中的“com.example.myapp_xrtqh_xrt”包下添加一个用于推送服务的类-MyHmsMessageService
---- 继承一个类 extends HmsMessageService
public static void getToken(Context context){
new Thread(){
@Override
public void run() {
try {
String app_id ="108267281";
String tokenScope="HCM";
String token = HmsInstanceId.getInstance(context).getToken(app_id,tokenScope);
System.out.println("======== token"+ token);
} catch (ApiException e) {
e.printStackTrace();
}
}
}.start();// 启动才会执行run方法
}
四个服务主代码
在app目录下的 java 包中的“com.example.myapp_xrtqh_xrt”包下的“MainActivity”类中添加如下代码
首先需要在public class…后面
---- 继承一个类 extends AppCompatActivity (这个在后面的代码中 会报错生成,不需要自己写)
---- 添加实现一个接口 implements View.OnClickListener
---- 代码中出现错误,多数只需把鼠标放上面Alt+Enter 回车即可-(import)。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// 推送服务
Context context = MainActivity.this;
MyHmsMessageService.getToken(context);
}
private Button btnId;
private Button btnIdtoken;
private Button btnSilent;
// 声明fusedLocationProviderClient对象·定位
private FusedLocationProviderClient fusedLocationProviderClient;
private Button btnGetlocation;
private Button btnRemovelocation;
private LocationCallback locationCallback;
private Button btnCancel;
private Button btnExstlanting;
// 机器人服务`图片
private Button btnTestsee;
private ImageView imageView;
//退出登陆需要用到
private AccountAuthService services;
// 退出登陆、授权时用到
private AccountAuthService getAuthCodeSignInServices() {
AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
AccountAuthService service = AccountAuthManager.getService(this, params);
return service;
}
private void initView() {
btnId = findViewById(R.id.btn_id);
btnIdtoken = findViewById(R.id.btn_idtoken);
btnSilent = findViewById(R.id.btn_silent);
btnGetlocation = findViewById(R.id.btn_getlocation); //定位location
btnRemovelocation = findViewById(R.id.btn_removelocation);
btnCancel = findViewById(R.id.btn_cancel);
btnExstlanting = findViewById(R.id.btn_exstlanting);
btnTestsee = findViewById(R.id.btn_testsee);
imageView = findViewById(R.id.imageView);
// 监听
btnId.setOnClickListener(this);
btnIdtoken.setOnClickListener(this);
btnSilent.setOnClickListener(this);
btnGetlocation.setOnClickListener(this);
btnRemovelocation.setOnClickListener(this);
btnCancel.setOnClickListener(this);
btnExstlanting.setOnClickListener(this);
btnTestsee.setOnClickListener(this);
services = getAuthCodeSignInServices();
// 实例化对象fusedLocationProviderClient 定位服务
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
System.out.println("===========location" + locationResult.getLocations().toString());
}
};
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_id:
btnidp();
break;
case R.id.btn_idtoken:
btnidtokenp();
break;
case R.id.btn_silent:
btnsilent();
break;
case R.id.btn_getlocation:
getlocation();
break;
case R.id.btn_removelocation:
removelocation();
break;
case R.id.btn_cancel:
cancel();
break;
case R.id.btn_exstlanting:
exstlanting();
break;
case R.id.btn_testsee:
testsee();
break;
}
}
// 短信验证登陆
private void btnidp() {
// 区别:
AccountAuthParams params = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setAuthorizationCode().createParams();
AccountAuthService service = AccountAuthManager.getService(this, params);
startActivityForResult(service.getSignInIntent(), 7777);
// 验证成功与否
Task<AuthAccount> task = service.silentSignIn();
task.addOnCompleteListener(new OnCompleteListener<AuthAccount>() {
@Override
public void onComplete(Task<AuthAccount> task) {
if (task.isSuccessful()) {
System.out.println("===========id登陆成功" + task.getResult().toString());
} else {
System.out.println("===========id登陆失败" + task.getException().toString());
}
}
});
}
// idtoken登陆
private void btnidtokenp() {
// 区别:
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).setIdToken().createParams();
AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
startActivityForResult(service.getSignInIntent(), 8888);
// 验证成功与否
Task<AuthAccount> task = service.silentSignIn();
task.addOnCompleteListener(new OnCompleteListener<AuthAccount>() {
@Override
public void onComplete(Task<AuthAccount> task) {
if (task.isSuccessful()) {
System.out.println("===========it登陆成功" + task.getResult().toString());
} else {
System.out.println("===========it登陆失败" + task.getException().toString());
}
}
});
}
// 静默登陆
private void btnsilent() {
AccountAuthParams authParams = new AccountAuthParamsHelper(AccountAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
AccountAuthService service = AccountAuthManager.getService(MainActivity.this, authParams);
// 验证成功与否
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 exstlanting() {
Task<Void> task = services.signOut();
task.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
System.out.println("=====================退出成功");
}
});
}
// 取消授权
private void cancel() {
Task<Void> task = services.cancelAuthorization();
task.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(Task<Void> task) {
System.out.println("=====================取消授权成功");
}
});
}
// 持续定位
private void getlocation() {
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 removelocation() {
Task<Void> task = fusedLocationProviderClient.removeLocationUpdates(locationCallback);
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 testsee() {
MLLocalTextSetting mlLocalTextSetting = new MLLocalTextSetting.Factory()
.setOCRMode(MLLocalTextSetting.OCR_DETECT_MODE)
.setLanguage("zh")
.create();
MLTextAnalyzer localTextAnalyzer = MLAnalyzerFactory
.getInstance()
.getLocalTextAnalyzer(mlLocalTextSetting);
//此处"text_faruxue"为添加的图片名,位于res.drawable目录下
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.text_faruxue);
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();让后Alt+Enter选择try/catch回车即可生成
localTextAnalyzer.stop();
} catch (IOException e) {
e.printStackTrace();
}
}