当前位置:网站首页>Hongmeng starts 2
Hongmeng starts 2
2022-06-12 23:11:00 【And white】
Related articles
Use OKhttp Make a network request
step 1 All prerequisite configurations
1. Add permissions in src-main-config.json in module Add network permissions inside
"reqPermissions": [ { "name": "ohos.permission.INTERNET" }]
2. deviceConfig Add in to make http request
"deviceConfig": {
"default": {
"network": { "cleartextTraffic": true}
}
},
step 2 Use okhttp
Import Follow android studio equally Also in build.gradle Inside
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.google.code.gson:gson:2.8.5'// Easy to parse data
Write a tool class to facilitate the request , Of course, it can also be opened directly
public static void startNetWork(String method,String url, HashSet<DataParams> params,RequestBody body,Callback callback) {
if (method==null){
return;
}
// The maximum response time is 10 seconds
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
Request.Builder builder = new Request.Builder();
HttpUrl.Builder builderUrl = HttpUrl.parse(url).newBuilder();
builder.url(builderUrl.build());
if (method.equals("GET")){
if (params != null) {
Iterator<DataParams> iterator = params.iterator();
while (iterator.hasNext()){
builderUrl.addQueryParameter(iterator.next().getKey(), iterator.next().getValue());
}
}
builder.method(method,new FormBody.Builder().build());
}else if (method.equals("POST")){
builder.post(body);
}
Call call = client.newCall(builder.build());
call.enqueue(callback);
}
To request - Processing data
private void login() {
String postJson = new Gson().toJson(new UserBean(userName.getText().trim(), passWord.getText().trim()));
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postJson);
SomeUtils.startNetWork("POST", Comm.Login, null, requestBody, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e.getMessage());
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String getJSON = response.body().string();
System.out.println(getJSON);
// to want to Log Print can be turned down
mEventHandler mEventHandler = new mEventHandler(EventRunner.create(true));
try {
LoginBean loginBean = new Gson().fromJson(getJSON, LoginBean.class);
if (loginBean.isResult()) {
// Write local
SomeUtils.setLoginCache(getJSON, LoginAbility.this);
// Jump
mEventHandler.processEvent(InnerEvent.get(TO_NEXT));
} else {
//ToastDialog This thing cannot pop up in a child thread
getMainTaskDispatcher().asyncDispatch(new Runnable() {
@Override
public void run() {
new ToastDialog(LoginAbility.this)
.setText(loginBean.getMessage())
.show();
}
});
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
HiLog Printing of
// Want to print the log Need a helper class HiLogLabel The type of now provides only one HiLog.LOG_APP
private static final HiLogLabel LABEL_LOG = new HiLogLabel(HiLog.LOG_APP, 0x00, TAG);
// True print The second parameter here is fromat Equivalent to placeholder format string Brackets public Visible for logs ,private Because the log is not visible
HiLog.error(LABEL_LOG, "%{public}s", getJSON);
Interface jump
// It's similar to the one in Andrews handler
class mEventHandler extends EventHandler{
public mEventHandler(EventRunner runner) throws IllegalArgumentException {
super(runner);
}
@Override
protected void processEvent(InnerEvent event) {
super.processEvent(event);
switch (event.eventId){
case TO_NEXT:
Intent intentNext = new Intent();
// The design here is very uncomfortable
Operation operation2 = new Intent.OperationBuilder()
.withBundleName(MyApplication.PackageName)
.withAbilityName(MyApplication.PackageName + ".ability.MainAbility").build();
intentNext.setOperation(operation2);
startAbility(intentNext);
terminateAbility();// amount to finish()
break;
}
}
}
Hongmeng's local lightweight storage
private static final String ALL_LOCAT_VALUE = "ALL_LOCAT_VALUE";
private static final String LOGIN_CACHE = "LOGIN_CACHE";
public static Preferences getPref(Context context){
DatabaseHelper helper = new DatabaseHelper(context);
return helper.getPreferences(ALL_LOCAT_VALUE);
}
public static void setLoginCache(String json,Context context){
Preferences pref = getPref(context);
pref.putString(LOGIN_CACHE,json);
pref.flush();
}
public static LoginBean.DataDTO getLoginBean(Context context){
Preferences pref = getPref(context);
String string = pref.getString(LOGIN_CACHE, "");
if (string.equals(""))return null;
LoginBean loginBean = new Gson().fromJson(string, LoginBean.class);
return loginBean.getData();
}
边栏推荐
- [Yugong series] wechat applet in February 2022 - Reference
- 应用最广泛的动态路由协议:OSPF
- Alcohol detector based on 51 single chip microcomputer
- 【LeetCode】300. Longest ascending subsequence
- C language: how to give an alias to a global variable?
- [web technology] 1348- talk about several ways to implement watermarking
- Detr (detection with transformers) learning notes
- China barcode decoder market trend report, technical innovation and market forecast
- PostgreSQL 中文社区黑龙江分会和辽宁分会成立啦!
- MOOG servo valve d634-341c/r40ko2m0nss2
猜你喜欢

Deep learning neural network: implementation method of convolution [direct method (no loss of precision), GEMM (matrix multiplication, no loss of precision), FFT (Fourier transform, loss of precision)

80 lines of code to realize simple rxjs

The shutter library recommends sizer to help you easily create a responsive UI

Record 5 - the serial port of stm32f411ceu6 realizes the sending and receiving of fixed length data and variable length data

数字藏品的发展趋势!

Web3 principle and decentralization

Industry reshuffle, a large number of programmers are going to lose their jobs? How can we break the current workplace dilemma
![[Part 8] semaphore source code analysis and application details [key points]](/img/e2/05c08435d60564aaa1172d2d574675.jpg)
[Part 8] semaphore source code analysis and application details [key points]

Photoshop:PS如何实现放大图片不模糊

Design a MySQL table for message queue to store message data
随机推荐
Analysis report on the 14th five year development plan and operation mode of China's hazardous waste treatment industry from 2022 to 2028
Detr (detection with transformers) learning notes
Plusieurs camarades de classe de Tsinghua sont partis...
Design a MySQL table for message queue to store message data
Research Report on market supply and demand and strategy of tizanidine industry in China
Dix points de défense clés dans les exercices d'attaque et de défense détaillés
Sword finger offer series - 47 Maximum value of gifts
OpenCV源代码编译
Chapter 8 - shared model JUC
Photoshop:PS如何实现放大图片不模糊
MySQL row to column, column to row, multiple columns to one row, one row to multiple columns
80 lines of code to realize simple rxjs
Market trend report, technical innovation and market forecast of Chinese stump crusher
ImageView grayed, reflected, rounded, watermarked
[North Asia data recovery] data recovery cases in which the partitions disappear and the partitions are inaccessible after the server reinstalls the system
数字藏品的发展趋势!
The development trend of digital collections!
Database system composition
MOOG servo valve d634-341c/r40ko2m0nss2
China's elastic belt market trend report, technical dynamic innovation and market forecast