实名认证和防沉迷集成


实名认证和防沉迷集成

  1. build.gradle
1
2
3
4
compileSdkVersion 26

minSdkVersion 21
targetSdkVersion 26

右键项目 - Open Model Settings - 选择左侧项目 - 选择Dependencies - 选择 + 号 - 选择Library Dependence - 输入 com.android.support:appcompat 搜索并选中添加

例如:compile ‘com.android.support:appcompat-v7:26.1.0’

  1. res
  • drawable 目录下添加 bg_dialog_warning.xml
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffff" />
<corners android:radius="12dp" />
</shape>
  • layout 目录下

防沉迷提示 dialog_anti.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/dialog_anti_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:gravity="center"
android:padding="8dp"
android:textColor="#000000"
android:textSize="18sp"
android:text="防沉迷提示" />

<TextView
android:id="@+id/dialog_anti_message"
android:maxWidth="300dp"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_gravity="center"
android:padding="7dp"
android:textSize="14sp"
android:text="" />

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#dfdfdf" />

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/dialog_anti_button_negative"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_weight="1"
android:textColor="#000000"
android:text="我知道了" />

</LinearLayout>

</LinearLayout>

实名认证 dialog_auth.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/dialog_auth_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:gravity="center"
android:padding="8dp"
android:textColor="#000000"
android:textSize="18sp"
android:text="实名认证" />
<EditText
android:id="@+id/dialog_auth_username"
android:maxWidth="300dp"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center"
android:inputType="textPersonName"
android:hint="请输入您的真实姓名"
android:textSize="14sp"
android:text="" />
<EditText
android:id="@+id/dialog_auth_userid"
android:maxWidth="300dp"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:layout_gravity="center"
android:hint="请输入身份证号,如有字母请小写"
android:textSize="14sp"
android:inputType="textPersonName" />

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#dfdfdf" />

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/dialog_auth_button_negative"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_weight="1"
android:textColor="#000000"
android:text="取消" />

<Button
android:id="@+id/dialog_auth_button_positive"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_weight="1"
android:background="#33ccff"
android:textColor="#ffffff"
android:text="提交" />

</LinearLayout>

</LinearLayout>

实名认证提示 dialog_auth_tip.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/dialog_auth_tip_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:gravity="center"
android:padding="8dp"
android:textColor="#000000"
android:textSize="18sp"
android:text="实名认证" />

<TextView
android:id="@+id/dialog_auth_tip_message"
android:maxWidth="300dp"
android:layout_width="260dp"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_gravity="center"
android:padding="7dp"
android:textSize="14sp"
android:text="根据国家关于《防止未成年人沉迷网络游戏的通知》要求,玩家必须完成实名认证,否则将禁止进入游戏。" />

<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#dfdfdf" />

<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<Button
android:id="@+id/dialog_auth_tip_button_negative"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_weight="1"
android:textColor="#000000"
android:text="取消" />

<Button
android:id="@+id/dialog_auth_tip_button_positive"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_weight="1"
android:textColor="#000000"
android:text="去认证" />

</LinearLayout>

</LinearLayout>
  • values

styles.xml

1
2
3
4
5
<resources>
<style name="WarningDialogTheme" parent="Theme.AppCompat.Dialog">
<item name="android:windowBackground">@drawable/bg_dialog_warning</item>
</style>
</resources>
  1. AndroidManifest.xml
1
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
  1. java
  • AntiDialog.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AntiDialog extends Dialog {

static AntiDialog mDialog = null;

private AntiDialog(Context context, int themeResId) {
super(context, themeResId);
}

public static class Builder {
private View mLayout;

private TextView mTitle;
private TextView mMessage;
private Button mNegativeButton;

private View.OnClickListener mPositiveListener;
private View.OnClickListener mNegativeListener;

private int mAnti; // 是否强制退出游戏

public Builder(Context context) {
if(mDialog != null) mDialog.dismiss();
mDialog = new AntiDialog(context, R.style.WarningDialogTheme);
LayoutInflater inflater = LayoutInflater.from(context);
mLayout = inflater.inflate(R.layout.dialog_anti, null);

mTitle = mLayout.findViewById(R.id.dialog_anti_title);
mMessage = mLayout.findViewById(R.id.dialog_anti_message);
mNegativeButton = mLayout.findViewById(R.id.dialog_anti_button_negative);
}

public Builder setTitle(int resId) {
mTitle.setText(resId);
return this;
}

public Builder setTitle(String text) {
mTitle.setText(text);
return this;
}

public Builder setMessage(int resId) {
mMessage.setText(resId);
return this;
}

public Builder setMessage(String text) {
mMessage.setText(text);
return this;
}

public Builder setNegativeButton(int resId, View.OnClickListener listener) {
mNegativeButton.setText(resId);
mNegativeListener = listener;
return this;
}

public Builder setNegativeButton(String text, View.OnClickListener listener) {
mNegativeButton.setText(text);
mNegativeListener = listener;
return this;
}

public AntiDialog create(int anti) {
mAnti = anti;
String t;
if(anti == 1){
t = "【健康系统】根据健康系统规则,您只能在8:00 - 21:00时间段进行游戏。请合理安排游戏时间,劳逸结合。";
}else if(anti > 1){
t = "【健康系统】您今日累计游戏时间已经超过" +(anti/60)+ "个小时,根据健康系统规则,您今日将无法登录游戏。请合理安排游戏时间,劳逸结合。";
}else{
t = "【健康系统】您今日累计游戏时间已经有" +AuthService.during+ "分钟。";
}
mMessage.setText(t);
mDialog.setContentView(mLayout);
mNegativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
mDialog.dismiss();
mDialog = null;
if (mAnti > 0){
AuthService.exitApp();
}
}
});
mDialog.setCancelable(true);
mDialog.setCanceledOnTouchOutside(false);
return mDialog;
}
}
}
  • AuthDialog.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AuthDialog extends Dialog {

private AuthDialog(Context context, int themeResId) {
super(context, themeResId);
}

public static class Builder {
private View mLayout;

private EditText mUsername;
private EditText mUserid;
private Button mPositiveButton;
private Button mNegativeButton;

private View.OnClickListener mPositiveListener;
private View.OnClickListener mNegativeListener;

private AuthDialog mDialog;
private Context mContext;

private String id_card_number;
private String name;

private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
mPositiveButton.setEnabled(true);
Toast.makeText(mContext,"实名认证失败",Toast.LENGTH_SHORT).show();
}
};

public Builder(Context context) {
mContext = context;
mDialog = new AuthDialog(mContext, R.style.WarningDialogTheme);
LayoutInflater inflater = LayoutInflater.from(mContext);
mLayout = inflater.inflate(R.layout.dialog_auth, null);

mUsername = (EditText) mLayout.findViewById(R.id.dialog_auth_username);
mUserid = (EditText) mLayout.findViewById(R.id.dialog_auth_userid);
mNegativeButton = (Button) mLayout.findViewById(R.id.dialog_auth_button_negative);
mPositiveButton = (Button) mLayout.findViewById(R.id.dialog_auth_button_positive);
}

public Builder setPositiveButton(int resId, View.OnClickListener listener) {
mPositiveButton.setText(resId);
mPositiveListener = listener;
return this;
}

public Builder setPositiveButton(String text, View.OnClickListener listener) {
mPositiveButton.setText(text);
mPositiveListener = listener;
return this;
}

public Builder setNegativeButton(int resId, View.OnClickListener listener) {
mNegativeButton.setText(resId);
mNegativeListener = listener;
return this;
}

public Builder setNegativeButton(String text, View.OnClickListener listener) {
mNegativeButton.setText(text);
mNegativeListener = listener;
return this;
}

public AuthDialog create() {
mDialog.setContentView(mLayout);
mPositiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
id_card_number = mUserid.getText().toString();
name = mUsername.getText().toString();
if(name.length()==0){
Toast.makeText(mContext,"请输入姓名",Toast.LENGTH_SHORT).show();
return;
}
if(id_card_number.length()!=18){
Toast.makeText(mContext,"请输入正确格式的身份证号",Toast.LENGTH_SHORT).show();
return;
}
mPositiveButton.setEnabled(false);
new Thread(new Runnable(){
@Override
public void run() {
// 查询是否验证通过
if(AuthService.idmatch(id_card_number,name)){
mDialog.dismiss();
}else{
handler.sendMessage( new Message());
}
}
}).start();

}

});
mNegativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
mDialog.dismiss();
AuthService.exitApp();
}
});
mDialog.setCancelable(true);
mDialog.setCanceledOnTouchOutside(false);
return mDialog;
}
}
}
  • AuthTipDialog.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import android.app.Dialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AuthTipDialog extends Dialog {

private AuthTipDialog(Context context, int themeResId) {
super(context, themeResId);
}

public static class Builder {
private Context mContext;
private View mLayout;

private TextView mTitle;
private TextView mMessage;
private Button mPositiveButton;
private Button mNegativeButton;

private View.OnClickListener mPositiveListener;
private View.OnClickListener mNegativeListener;

private AuthTipDialog mDialog;

public Builder(Context context) {
mContext = context;
mDialog = new AuthTipDialog(context, R.style.WarningDialogTheme);
LayoutInflater inflater = LayoutInflater.from(context);
mLayout = inflater.inflate(R.layout.dialog_auth_tip, null);

mTitle = mLayout.findViewById(R.id.dialog_auth_tip_title);
mMessage = mLayout.findViewById(R.id.dialog_auth_tip_message);
mNegativeButton = mLayout.findViewById(R.id.dialog_auth_tip_button_negative);
mPositiveButton = mLayout.findViewById(R.id.dialog_auth_tip_button_positive);
}

public Builder setTitle(int resId) {
mTitle.setText(resId);
return this;
}

public Builder setTitle(String text) {
mTitle.setText(text);
return this;
}

public Builder setMessage(int resId) {
mMessage.setText(resId);
return this;
}

public Builder setMessage(String text) {
mMessage.setText(text);
return this;
}

public Builder setPositiveButton(int resId, View.OnClickListener listener) {
mPositiveButton.setText(resId);
mPositiveListener = listener;
return this;
}

public Builder setPositiveButton(String text, View.OnClickListener listener) {
mPositiveButton.setText(text);
mPositiveListener = listener;
return this;
}

public Builder setNegativeButton(int resId, View.OnClickListener listener) {
mNegativeButton.setText(resId);
mNegativeListener = listener;
return this;
}

public Builder setNegativeButton(String text, View.OnClickListener listener) {
mNegativeButton.setText(text);
mNegativeListener = listener;
return this;
}

public AuthTipDialog create() {
mDialog.setContentView(mLayout);
mPositiveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
mDialog.dismiss();
AuthDialog authDialog = new AuthDialog.Builder(mContext).create();
authDialog.show();
}
});
mNegativeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
mDialog.dismiss();
AuthService.exitApp();
}
});
mDialog.setCancelable(true);
mDialog.setCanceledOnTouchOutside(false);
return mDialog;
}
}
}
  • AuthService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304

import android.app.ActivityManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
* 获取token类
*/
public class AuthService {

static Context mContext;
static File mDir;
// dt 当前登录日期 during 已经在游戏中玩的分钟数
static String createSql = "create table user(id integer primary key autoincrement, name, id_card_number, dt, age integer, during integer)";
static String selectSql = "select id, name, id_card_number, dt, age, during from user";
static String insertSql = "insert into user(name, id_card_number, age, dt, during) values(?,?,?,?,?)";
static String updateSql = "update user set dt=?,during=? where id=?";
static String dt = null;
static int id = 1;
static int age = 0;
public static int during = 0;
static long times = 0;
static Handler mHandler;

public static void init(Context context, File dir){
mContext = context;
mDir = dir;
SQLiteDatabase DB = null;
Cursor cursor = null;
Date today = new Date();
times = today.getTime() / 1000 / 60;
try {
DB = SQLiteDatabase.openOrCreateDatabase(mDir + "/info.db", null);
try {
cursor = DB.rawQuery(selectSql, null);
}catch (Exception e){
DB.execSQL(createSql);
cursor = DB.rawQuery(selectSql, null);
}
if(cursor!=null && cursor.getCount() > 0){// 已实名认证成功
while (cursor.moveToNext()) {
String nameString = cursor.getString(cursor.getColumnIndex("name"));
String id_card_number = cursor.getString(cursor.getColumnIndex("id_card_number"));
dt = cursor.getString(cursor.getColumnIndex("dt"));
id = cursor.getInt(cursor.getColumnIndex("id"));
age = cursor.getInt(cursor.getColumnIndex("age"));
during = cursor.getInt(cursor.getColumnIndex("during"));
// System.out.println("ID--->"+id_card_number);
// System.out.println("NAME--->"+nameString);
// System.out.println("AGE--->"+age);
// 如果是当天,则累计;否则重置
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String dateTime = df.format(today);
if (dateTime.compareTo(dt) == 0){
checkAnti();
}else{
dt = dateTime;
during = 0;
updateUser();
}

break;
}
}else{
// 需要实名认证
AuthTipDialog authTipDialog = new AuthTipDialog.Builder(mContext).create();
authTipDialog.show();
}
} catch (Exception e){
// 需要实名认证
AuthTipDialog authTipDialog = new AuthTipDialog.Builder(mContext).create();
authTipDialog.show();
} finally {
if(cursor!=null) cursor.close();
if(DB!=null) DB.close();
}

scheduleAnti();
}

public static void scheduleAnti(){
mHandler = new Handler();
Runnable r = new Runnable() {
@Override
public void run() {
checkAnti();
//每隔1s循环执行run方法
mHandler.postDelayed(this, 300000);
}
};
mHandler.postDelayed(r, 300000);
}

public static void saveUser(String id_card_number, String name){
SQLiteDatabase DB = null;
try {
DB = SQLiteDatabase.openOrCreateDatabase(mDir + "/info.db", null);
Calendar cal = Calendar.getInstance();
age = cal.get(Calendar.YEAR) - new Integer(id_card_number.substring(6,10));
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
dt = df.format(new Date());
DB.execSQL(insertSql, new String[]{name, id_card_number, age + "", dt, "0"});
} catch (Exception e){
e.printStackTrace();
} finally {
if(DB!=null) DB.close();
}
}

public static void checkAnti(){// 检查是否防沉迷时间到了
if(dt == null) return;
// 未满13周岁未成年用户:游戏帐号累计登录游戏时长达1个小时后,在对局结束后,将被强制下线,且当日不能再登录游戏。同时,在每日21:00-次日8:00时间段,将无法登录游戏。
// 13周岁及以上未成年用户:游戏帐号累计登录游戏时长达2个小时后,在对局结束后,将被强制下线,且当日不能再登录游戏。
int duringMax = 60 * 24;
boolean showTip = false;
if (age < 13){
duringMax = 60;
showTip = true;
}else if (age < 18){
duringMax = 60 * 2;
showTip = true;
}
Date today = new Date();
int h = today.getHours();
long d = today.getTime() / 1000 / 60 - times;
during += d;
times = today.getTime() / 1000 / 60;
updateUser();
if (during >= duringMax){
AntiDialog antiDialog = new AntiDialog.Builder(mContext).create(duringMax);
antiDialog.show();
}else if(duringMax == 60 && ( h < 8 || h >= 21)){ // 每日21:00-次日8:00时间段,将无法登录游戏
AntiDialog antiDialog = new AntiDialog.Builder(mContext).create(1);
antiDialog.show();
}else if(showTip){
AntiDialog antiDialog = new AntiDialog.Builder(mContext).create(0);
antiDialog.show();
}
}

public static void updateUser(){
SQLiteDatabase DB = null;
try {
DB = SQLiteDatabase.openOrCreateDatabase(mDir + "/info.db", null);
DB.execSQL(updateSql, new String[]{dt, during+ "", id + ""});
} catch (Exception e){
e.printStackTrace();
} finally {
if(DB!=null) DB.close();
}
}

/**
* 获取权限token
* @return 返回示例:
* {
* "access_token": "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567",
* "expires_in": 2592000
* }
*/
public static String getAuth() {
// 官网获取的 API Key 更新为你注册的
String clientId = "xxxxx";
// 官网获取的 Secret Key 更新为你注册的
String clientSecret = "xxxxx";
return getAuth(clientId, clientSecret);
}

/**
* 获取API访问token
* 该token有一定的有效期,需要自行管理,当失效时需重新获取.
* @param ak - 百度云官网获取的 API Key
* @param sk - 百度云官网获取的 Securet Key
* @return assess_token 示例:
* "24.460da4889caad24cccdb1fea17221975.2592000.1491995545.282335-1234567"
*/
public static String getAuth(String ak, String sk) {
// 获取token地址
String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
String getAccessTokenUrl = authHost
// 1. grant_type为固定参数
+ "grant_type=client_credentials"
// 2. 官网获取的 API Key
+ "&client_id=" + ak
// 3. 官网获取的 Secret Key
+ "&client_secret=" + sk;
try {
URL realUrl = new URL(getAccessTokenUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
// 定义 BufferedReader输入流来读取URL的响应
InputStream inputStream = null;
int code = connection.getResponseCode();
if (code == 200) {
inputStream = connection.getInputStream(); // {"refresh_token":"25.7138471a4d4da254dde9f26d25c5f1b1.315360000.1892710463.282335-18116019","expires_in":2592000,"session_key":"9mzdDoDznz34Ch8zo2IjeiPgQzeJ8GpsY3MygqKYkWFqykeeCtRuw31V0NAXE5B1T9XFGQAsZHHVE8RWrE9pBXr3BWxXnQ==","access_token":"24.52b38e1c31e3cc4972774dffc795bbe6.2592000.1579942463.282335-18116019","scope":"public brain_all_scope vis-faceverify_faceverify_h5-face-liveness vis-faceverify_FACE_V3 vis-faceverify_FACE_Police vis-faceverify_idl_face_merge wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\u6743\u9650 vis-classify_flower lpq_\u5f00\u653e cop_helloScope ApsMis_fangdi_permission smartapp_snsapi_base iop_autocar oauth_tp_app smartapp_smart_game_openapi oauth_sessionkey smartapp_swanid_verify smartapp_opensource_openapi smartapp_opensource_recapi fake_face_detect_\u5f00\u653eScope vis-ocr_\u865a\u62df\u4eba\u7269\u52a9\u7406 idl-video_\u865a\u62df\u4eba\u7269\u52a9\u7406","session_secret":"b8b78a14e97d9faa92d06dd89928c686"}

} else {
inputStream = connection.getErrorStream(); // {"error_description":"unknown client id","error":"invalid_client"}
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String result = "";
String line;
while ((line = in.readLine()) != null) {
result += line;
}
/**
* 返回结果示例
*/
// System.err.println("result:" + result);
JSONObject jsonObject = new JSONObject(result);
String access_token = jsonObject.getString("access_token");
return access_token;
} catch (Exception e) {
System.err.printf("获取token失败!");
e.printStackTrace(System.err);
}
return null;
}

public static boolean idmatch(String id_card_number, String name){
String access_token = getAuth();
String postIdMatchUrl = "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token=" + access_token;
try {
JSONObject jsonParams = new JSONObject();
jsonParams.put("id_card_number",id_card_number);
jsonParams.put("name",name);
String json = jsonParams.toString();
//if(true) return true;
URL realUrl = new URL(postIdMatchUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
OutputStream os = connection.getOutputStream();
os.write(json.getBytes("UTF-8"));
os.flush();
// read the response
InputStream inputStream = null;
int code = connection.getResponseCode();
if (code == 200) {
inputStream = connection.getInputStream(); // {"error_code":0,"error_msg":"SUCCESS","log_id":9445001001252,"timestamp":1577352336,"cached":0,"result":null}
} else {
inputStream = connection.getErrorStream(); // {"error_code":222022,"error_msg":"param[id_card_number] format error","log_id":8925450525457,"timestamp":1577351254,"cached":0,"result":null} {"error_code":222351,"error_msg":"id number and name not match","log_id":9915001350510,"timestamp":1577354127,"cached":0,"result":null}
return false;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = URLDecoder.decode(lines, "UTF-8");
sb.append(lines);
}
JSONObject resultObject = new JSONObject(sb.toString());
connection.disconnect();
// System.err.println("result:" + resultObject.toString());
int error_code = resultObject.getInt("error_code");
if (error_code == 0){
saveUser(id_card_number, name);
return true;
}
else
return false;
} catch (Exception e) {
System.err.printf("获取idmatch失败!");
e.printStackTrace(System.err);
}
return false;
}

public static void exitApp(){
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.AppTask> appTaskList = activityManager.getAppTasks();
for (ActivityManager.AppTask appTask : appTaskList) {
appTask.finishAndRemoveTask();
}
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
  1. AppActivity.java

在 onCreate 方法中添加

1
AuthService.init(this, getFilesDir());