();
182 | for (String p : pi.requestedPermissions) {
183 | if (checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED) {
184 | list.add(p);
185 | }
186 | }
187 | if (list.size() > 0) {
188 | String[] permissions = list.toArray(new String[list.size()]);
189 | if (permissions != null) {
190 | requestPermissions(permissions, 1);
191 | }
192 | }
193 | } catch (Throwable t) {
194 | t.printStackTrace();
195 | }
196 | }
197 | }
198 |
199 | /**
200 | * 预登录
201 | *
202 | * 建议提前调用预登录接口,可以加快免密登录过程,提高用户体验
203 | */
204 | private void preVerify() {
205 |
206 | isPreVerifyDone = false;
207 | //设置在1000-10000之内
208 | SecVerify.setTimeOut(5000);
209 | //移动的debug tag 是CMCC-SDK,电信是CT_ 联通是PriorityAsyncTask
210 | SecVerify.setDebugMode(true);
211 | SecVerify.preVerify(new PreVerifyCallback() {
212 | @Override
213 | public void onComplete(Void data) {
214 | // Nothing to do
215 | if (devMode) {
216 | Toast.makeText(MainActivity.this, "预登录成功", Toast.LENGTH_SHORT).show();
217 | }
218 | isPreVerifyDone = true;
219 | }
220 |
221 | @Override
222 | public void onFailure(VerifyException e) {
223 | isPreVerifyDone = true;
224 | // Nothing to do
225 | Throwable t = e.getCause();
226 | String errDetail = null;
227 | if (t != null){
228 | errDetail = t.getMessage();
229 | }
230 |
231 | if (devMode) {
232 | // 登录失败
233 | Log.e(TAG, "preVerify failed", e);
234 | // 错误码
235 | int errCode = e.getCode();
236 | // 错误信息
237 | String errMsg = e.getMessage();
238 | // 更详细的网络错误信息可以通过t查看,请注意:t有可能为null
239 | String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
240 | if (!TextUtils.isEmpty(errDetail)) {
241 | msg += "\n详细信息: " + errDetail;
242 | }
243 | Log.e(TAG,msg);
244 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
245 | }
246 | }
247 | });
248 | }
249 |
250 | /**
251 | * 免密登录
252 | */
253 | private void verify() {
254 | CommonProgressDialog.showProgressDialog(this);
255 | //需要在verify之前设置
256 | SecVerify.OtherOAuthPageCallBack(new OAuthPageEventCallback() {
257 | @Override
258 | public void initCallback(OAuthPageEventResultCallback cb) {
259 | cb.pageOpenCallback(new PageOpenedCallback() {
260 | @Override
261 | public void handle() {
262 | Log.i(TAG, System.currentTimeMillis() + " pageOpened");
263 | Log.e(TAG,(System.currentTimeMillis() - starttime) + "ms is the time pageOpen take ");
264 | }
265 | });
266 | cb.loginBtnClickedCallback(new LoginBtnClickedCallback() {
267 | @Override
268 | public void handle() {
269 | Log.i(TAG, System.currentTimeMillis() + " loginBtnClicked");
270 | }
271 | });
272 | cb.agreementPageClosedCallback(new AgreementPageClosedCallback() {
273 | @Override
274 | public void handle() {
275 | Log.i(TAG, System.currentTimeMillis() + " agreementPageClosed");
276 | }
277 | });
278 | cb.agreementPageOpenedCallback(new AgreementClickedCallback() {
279 | @Override
280 | public void handle() {
281 | Log.i(TAG, System.currentTimeMillis() + " agreementPageOpened");
282 | }
283 | });
284 | cb.cusAgreement1ClickedCallback(new CusAgreement1ClickedCallback() {
285 | @Override
286 | public void handle() {
287 | Log.i(TAG, System.currentTimeMillis() + " cusAgreement1ClickedCallback");
288 | }
289 | });
290 | cb.cusAgreement2ClickedCallback(new CusAgreement2ClickedCallback() {
291 | @Override
292 | public void handle() {
293 | Log.i(TAG, System.currentTimeMillis() + " cusAgreement2ClickedCallback");
294 | }
295 | });
296 | cb.checkboxStatusChangedCallback(new CheckboxStatusChangedCallback() {
297 | @Override
298 | public void handle(boolean b) {
299 | Log.i(TAG,System.currentTimeMillis() + " current status is " + b);
300 | }
301 | });
302 | cb.pageCloseCallback(new PageClosedCallback() {
303 | @Override
304 | public void handle() {
305 | Log.i(TAG, System.currentTimeMillis() + " pageClosed");
306 | HashMap> map = UiLocationHelper.getInstance().getViewLocations();
307 | if (map == null) {
308 | return;
309 | }
310 | for (String key : map.keySet()) {
311 | List locats = map.get(key);
312 | if (locats != null && locats.size() > 0) {
313 | for (int i : locats) {
314 | Log.i(TAG, i + " xywh");
315 | }
316 | }
317 | }
318 | }
319 | });
320 | }
321 | });
322 | starttime = System.currentTimeMillis();
323 | SecVerify.verify(new PageCallback() {
324 | @Override
325 | public void pageCallback(int code, String desc) {
326 | Log.e(TAG, code + " " + desc);
327 | if (code != 6119140) {
328 | CommonProgressDialog.dismissProgressDialog();
329 | if (devMode) {
330 | Toast.makeText(MainActivity.this, code + " " + desc, Toast.LENGTH_SHORT).show();
331 | }
332 |
333 | }
334 | }
335 | }, new GetTokenCallback() {
336 | @Override
337 | public void onComplete(VerifyResult data) {
338 | tokenToPhone(data);
339 | }
340 |
341 | @Override
342 | public void onFailure(VerifyException e) {
343 | showExceptionMsg(e);
344 | }
345 | });
346 |
347 | }
348 |
349 | private void tokenToPhone(VerifyResult data) {
350 | CommonProgressDialog.dismissProgressDialog();
351 | if (data != null) {
352 | Log.d(TAG, data.toJSONString());
353 | // 获取授权码成功,将token信息传给应用服务端,再由应用服务端进行登录验证,此功能需由开发者自行实现
354 | CommonProgressDialog.showProgressDialog(MainActivity.this);
355 | LoginTask.getInstance().login(data, new ResultListener() {
356 | @Override
357 | public void onComplete(LoginResult data) {
358 | CommonProgressDialog.dismissProgressDialog();
359 | Log.d(TAG, "Login success. data: " + data.toJSONString());
360 | vibrate();
361 | // 服务端登录成功,跳转成功页
362 | goResultActivity(data);
363 | }
364 |
365 | @Override
366 | public void onFailure(DemoException e) {
367 | // 登录失败
368 | Log.e(TAG, "login failed", e);
369 | CommonProgressDialog.dismissProgressDialog();
370 | // 错误码
371 | int errCode = e.getCode();
372 | // 错误信息
373 | String errMsg = e.getMessage();
374 | // 更详细的网络错误信息可以通过t查看,请注意:t有可能为null
375 | Throwable t = e.getCause();
376 | String errDetail = null;
377 | if (t != null) {
378 | errDetail = t.getMessage();
379 | }
380 | String msg = "获取授权码成功,应用服务器登录失败" + "\n错误码: " + errCode + "\n错误信息: " + errMsg;
381 | if (!TextUtils.isEmpty(errDetail)) {
382 | msg += "\n详细信息: " + errDetail;
383 | }
384 | if (!devMode) {
385 | msg = "当前网络不稳定";
386 | }
387 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
388 | goResultActivity(null);
389 | // Demo为了演示效果,登录失败时也做一次预登录
390 | preVerify();
391 | }
392 | });
393 | }
394 | }
395 |
396 | public void showExceptionMsg(VerifyException e) {
397 | // 登录失败
398 | if (defaultUi == 1){
399 | //失败之后不会自动关闭授权页面,需要手动关闭
400 | SecVerify.finishOAuthPage();
401 | }
402 | CommonProgressDialog.dismissProgressDialog();
403 | Log.e(TAG, "verify failed", e);
404 | // 错误码
405 | int errCode = e.getCode();
406 | // 错误信息
407 | String errMsg = e.getMessage();
408 | // 更详细的网络错误信息可以通过t查看,请注意:t有可能为null
409 | Throwable t = e.getCause();
410 | String errDetail = null;
411 | if (t != null) {
412 | errDetail = t.getMessage();
413 | }
414 |
415 | String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
416 | if (!TextUtils.isEmpty(errDetail)) {
417 | msg += "\n详细信息: " + errDetail;
418 | }
419 | if (!devMode) {
420 | msg = "当前网络不稳定";
421 | if (errCode == VerifyErr.C_NO_SIM.getCode()
422 | || errCode == VerifyErr.C_UNSUPPORTED_OPERATOR.getCode()
423 | || errCode == VerifyErr.C_CELLULAR_DISABLED.getCode()) {
424 | msg = errMsg;
425 | }
426 | }
427 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
428 | goResultActivity(null);
429 | }
430 |
431 | private void customizeUi() {
432 | SecVerify.setUiSettings(CustomizeUtils.customizeUi());
433 | SecVerify.setLandUiSettings(CustomizeUtils.customizeLandUi());
434 | }
435 |
436 |
437 | private void customizeUi1() {
438 | SecVerify.setUiSettings(CustomizeUtils.customizeUi1());
439 | SecVerify.setLandUiSettings(CustomizeUtils.customizeUi5(this));
440 | // LandUiSettings uiSettings1 = new LandUiSettings.Builder()
441 | // .setTranslateAnim(true)
442 | // .setImmersiveTheme(true)
443 | // .setImmersiveStatusTextColorBlack(true)
444 | // .build();
445 | // SecVerify.setLandUiSettings(uiSettings1);
446 | }
447 |
448 |
449 | private void customizeUi2() {
450 | SecVerify.setUiSettings(CustomizeUtils.customizeUi2());
451 | SecVerify.setLandUiSettings(null);
452 | // LandUiSettings uiSettings1 = new LandUiSettings.Builder()
453 | // .setDialogMaskBackgroundClickClose(true)
454 | // .setStartActivityTransitionAnim(R.anim.sec_verify_translate_bottom_in,R.anim.sec_verify_translate_bottom_out)
455 | // .setFinishActivityTransitionAnim(R.anim.sec_verify_translate_bottom_in,R.anim.sec_verify_translate_bottom_out)
456 | // .setDialogTheme(true)
457 | // .setDialogAlignBottom(true)
458 | // .build();
459 | // SecVerify.setLandUiSettings(uiSettings1);
460 | }
461 |
462 | private void customizeUi3() {
463 | SecVerify.setUiSettings(CustomizeUtils.customizeUi3());
464 | SecVerify.setLandUiSettings(null);
465 | }
466 |
467 | private void customizeUi4() {
468 | SecVerify.setUiSettings(CustomizeUtils.customizeUi4());
469 | SecVerify.setLandUiSettings(CustomizeUtils.customizeLandUi4());
470 | }
471 |
472 | /**
473 | * 添加自定义view
474 | */
475 | private void addCustomView() {
476 | CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView(MobSDK.getContext()),
477 | new CustomViewClickCallback(0));
478 |
479 | List views = new ArrayList();
480 | TextView textView = new TextView(MobSDK.getContext());
481 | textView.setText("返回");
482 | textView.setId(R.id.customized_view_id_div);
483 | textView.setTextColor(0xff000000);
484 | textView.setTextSize(16);
485 | RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
486 | // params.addRule(RelativeLayout.RIGHT_OF, R.id.sec_verify_title_bar_left);
487 | params.addRule(RelativeLayout.CENTER_VERTICAL);
488 | params.leftMargin = ResHelper.dipToPx(MainActivity.this,35);
489 | textView.setLayoutParams(params);
490 | views.add(textView);
491 | CustomUIRegister.addTitleBarCustomizedUi(views,new CustomViewClickCallback(1));
492 | }
493 |
494 | private void addCustomView1() {
495 | CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView(this), new CustomViewClickListener() {
496 | @Override
497 | public void onClick(View view) {
498 | int id = view.getId();
499 | if (id == R.id.customized_btn_id_1) {
500 | customizeUi3();
501 | addCustomView3();
502 | SecVerify.refreshOAuthPage();
503 | }
504 | }
505 | });
506 | View view = LayoutInflater.from(this).inflate(R.layout.sec_verify_demo_loading,null);
507 | RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
508 | params.addRule(RelativeLayout.CENTER_IN_PARENT);
509 | view.setLayoutParams(params);
510 | CustomUIRegister.setCustomizeLoadingView(view);
511 |
512 | }
513 |
514 | private void addCustomView2() {
515 | CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView2(this), new CustomViewClickListener() {
516 | @Override
517 | public void onClick(View view) {
518 | int id = view.getId();
519 | String msg = "";
520 | if (id == R.id.customized_btn_id_1) {
521 | msg = "用户取消登录";
522 | // 自定义控件点击时,SecVerify默认不关闭授权页面,若需关闭,可调用该方法
523 | SecVerify.finishOAuthPage();
524 | CommonProgressDialog.dismissProgressDialog();
525 | } else if (id == R.id.customized_view_id) {
526 | return;
527 | }
528 | // 关闭加载框
529 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
530 | }
531 | });
532 | }
533 |
534 | private void addCustomView3() {
535 |
536 | CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView3(this), new CustomViewClickListener() {
537 | @Override
538 | public void onClick(View view) {
539 | int id = view.getId();
540 | String msg = "";
541 | if (id == R.id.customized_btn_id_1) {
542 | msg = "按钮1 clicked";
543 | // 自定义控件点击时,SecVerify默认不关闭授权页面,若需关闭,可调用该方法
544 | addCustomView1();
545 | customizeUi2();
546 | SecVerify.refreshOAuthPage();
547 | } else if (id == R.id.customized_btn_id_0){
548 | msg = "关闭返回 ";
549 | SecVerify.finishOAuthPage();
550 | } else if (id == R.id.customized_btn_id_3){
551 | msg = "登录返回";
552 | SecVerify.finishOAuthPage();
553 | }
554 | // 关闭加载框
555 | CommonProgressDialog.dismissProgressDialog();
556 | Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
557 | }
558 | });
559 | }
560 |
561 | private void addCustomView4() {
562 | CustomUIRegister.addCustomizedUi(CustomizeUtils.buildCustomView4(MobSDK.getContext()),
563 | null);
564 | CustomUIRegister.addTitleBarCustomizedUi(null,null);
565 | }
566 |
567 | private void goResultActivity(LoginResult data) {
568 | Intent i = new Intent(this, ResultActivity.class);
569 | if (data != null) {
570 | i.putExtra("sec_verify_demo_verify_success", true);
571 | i.putExtra(Const.EXTRAS_DEMO_LOGIN_RESULT, data);
572 | } else {
573 | i.putExtra("sec_verify_demo_verify_success", false);
574 | }
575 | startActivityForResult(i, REQUEST_CODE);
576 | SecVerify.finishOAuthPage();
577 | com.mob.secverify.ui.component.CommonProgressDialog.dismissProgressDialog();
578 | }
579 |
580 | private void vibrate() {
581 | Vibrator vibrator = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
582 | if (vibrator != null) {
583 | if (Build.VERSION.SDK_INT >= 26) {
584 | VibrationEffect vibrationEffect = VibrationEffect.createOneShot(500, 20);
585 | vibrator.vibrate(vibrationEffect);
586 | } else {
587 | vibrator.vibrate(500);
588 | }
589 | }
590 | }
591 |
592 | @Override
593 | protected void onResume() {
594 | super.onResume();
595 | if (defaultUi == 1 || defaultUi == 3) {
596 | //处理部分机型调起授权页面的Activity设置固定方向之后,授权页面无法横竖屏切换
597 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//根据需要设置为横屏或者竖屏
598 | }
599 | }
600 |
601 | @Override
602 | protected void onPause() {
603 | super.onPause();
604 | if (defaultUi == 1 || defaultUi == 3) {
605 | //处理部分机型调起授权页面的Activity设置固定方向之后,授权页面无法横竖屏切换
606 | setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
607 | }
608 | }
609 |
610 |
611 | private void switchDevMode() {
612 | if (devMode) {
613 | devMode = false;
614 | Toast.makeText(this, "开发者模式:Off", Toast.LENGTH_SHORT).show();
615 | } else {
616 | devMode = true;
617 | Toast.makeText(this, "开发者模式:On", Toast.LENGTH_SHORT).show();
618 | }
619 | }
620 |
621 | private static class CustomViewClickCallback implements CustomViewClickListener {
622 | private int customUI;
623 |
624 | public CustomViewClickCallback(int customUI) {
625 | this.customUI = customUI;
626 | }
627 |
628 | @Override
629 | public void onClick(View view) {
630 | if (customUI == 0) {
631 | int id = view.getId();
632 | String msg = "";
633 | if (id == R.id.customized_btn_id_1) {
634 | msg = "微信 clicked";
635 | // 自定义控件点击时,SecVerify默认不关闭授权页面,若需关闭,可调用该方法
636 | SecVerify.finishOAuthPage();
637 | Toast.makeText(MobSDK.getContext(), msg, Toast.LENGTH_SHORT).show();
638 | } else if (id == R.id.customized_btn_id_3) {
639 | // msg = "按钮2 clicked";
640 | Intent intent = new Intent(MobSDK.getContext(), DemoLoginActivity.class);
641 | intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
642 | MobSDK.getContext().startActivity(intent);
643 | }
644 | // 关闭加载框
645 | } else if (customUI == 1) {
646 | // 关闭加载框
647 | SecVerify.finishOAuthPage();
648 | } else if (customUI == 4){
649 | int id = view.getId();
650 | String msg = "";
651 | if (id == R.id.customized_btn_id_1) {
652 | // 自定义控件点击时,SecVerify默认不关闭授权页面,若需关闭,可调用该方法
653 | } else if (id == R.id.customized_view_id) {
654 | return;
655 | }
656 | // 关闭加载框
657 | }
658 | CommonProgressDialog.dismissProgressDialog();
659 | }
660 | }
661 |
662 | @Override
663 | public void onConfigurationChanged(Configuration newConfig) {
664 | super.onConfigurationChanged(newConfig);
665 | onCreate(null);
666 | }
667 | }
668 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ResultActivity.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo;
2 |
3 | import android.content.Intent;
4 | import android.content.res.Configuration;
5 | import android.graphics.Color;
6 | import android.os.Build;
7 | import android.view.View;
8 | import android.view.WindowManager;
9 | import android.widget.ImageView;
10 | import android.widget.TextView;
11 |
12 | import com.mob.secverify.demo.entity.LoginResult;
13 | import com.mob.secverify.demo.util.Const;
14 |
15 | public class ResultActivity extends BaseActivity {
16 | private TextView tryAgainTv;
17 | private TextView phoneTv;
18 | private TextView successTv;
19 | private ImageView backIv;
20 | private ImageView resultImgIv;
21 | private ImageView phoneIv;
22 |
23 | @Override
24 | protected int getContentViewId() {
25 | return R.layout.activity_result;
26 | }
27 |
28 | @Override
29 | protected void getTitleStyle(TitleStyle titleStyle) {
30 | titleStyle.showLeft = true;
31 | }
32 |
33 | @Override
34 | protected void onViewCreated() {
35 | if (Build.VERSION.SDK_INT >= 21){
36 | // 设置沉浸式状态栏
37 | View decorView = getWindow().getDecorView();
38 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
39 | | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
40 | decorView.setSystemUiVisibility(option);
41 | // 设置状态栏透明
42 | getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
43 | getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
44 | getWindow().setStatusBarColor(Color.TRANSPARENT);
45 | // if (Build.VERSION.SDK_INT >= 23){
46 | // getWindow().getDecorView().setSystemUiVisibility(
47 | // View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
48 | // }
49 | }
50 | overridePendingTransition(R.anim.translate_in, R.anim.translate_out);
51 | initView();
52 | initContent();
53 | }
54 |
55 | private void initContent() {
56 | Intent intent = getIntent();
57 | if (intent.getBooleanExtra("sec_verify_demo_verify_success", true)) {
58 | resultImgIv.setImageDrawable(getResources().getDrawable(R.drawable.sec_verify_demo_verify_success));
59 | if (intent.hasExtra(Const.EXTRAS_DEMO_LOGIN_RESULT)) {
60 | LoginResult result = (LoginResult) intent.getSerializableExtra(Const.EXTRAS_DEMO_LOGIN_RESULT);
61 | if (result != null) {
62 | phoneTv.setText(result.getPhone());
63 | }
64 | } else {
65 | phoneTv.setVisibility(View.GONE);
66 | phoneIv.setVisibility(View.GONE);
67 | }
68 | } else {
69 | resultImgIv.setImageDrawable(getResources().getDrawable(R.drawable.sec_verify_demo_verify_failed));
70 | // Exception exception = (Exception) intent.getSerializableExtra(Const.EXTRAS_DEMO_LOGIN_RESULT);
71 | successTv.setText("登录失败");
72 | phoneTv.setVisibility(View.GONE);
73 | phoneIv.setVisibility(View.GONE);
74 | }
75 |
76 | }
77 |
78 | private void initView() {
79 | tryAgainTv = findViewById(R.id.sec_verify_demo_verify_result_one_more_try);
80 | phoneTv = findViewById(R.id.sec_verify_demo_success_phone_tv);
81 | successTv = findViewById(R.id.sec_verify_demo_verify_result_success);
82 | resultImgIv = findViewById(R.id.sec_verify_demo_verify_result_image);
83 | backIv = findViewById(R.id.sec_verify_demo_title_bar_left_iv);
84 | phoneIv = findViewById(R.id.sec_verify_demo_success_phone_iv);
85 |
86 | backIv.setOnClickListener(this);
87 | tryAgainTv.setOnClickListener(this);
88 | }
89 |
90 | @Override
91 | protected void onViewClicked(View v) {
92 | int id = v.getId();
93 | if (id == tryAgainTv.getId()) {
94 | // startActivity(new Intent(ResultActivity.this,MainActivity.class));
95 | this.finish();
96 | } else if (id == backIv.getId()) {
97 | this.finish();
98 | }
99 | }
100 |
101 | @Override
102 | public void onConfigurationChanged(Configuration newConfig) {
103 | super.onConfigurationChanged(newConfig);
104 | onCreate(null);
105 | }
106 | }
107 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ResultListener.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo;
2 |
3 | import com.mob.secverify.demo.exception.DemoException;
4 |
5 | public abstract class ResultListener {
6 | public abstract void onComplete(T data);
7 | public abstract void onFailure(DemoException e);
8 | }
9 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/SuccessActivity.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo;
2 |
3 | import android.content.Intent;
4 | import android.view.View;
5 | import android.widget.Button;
6 | import android.widget.TextView;
7 |
8 | import com.mob.secverify.demo.entity.LoginResult;
9 | import com.mob.secverify.demo.util.Const;
10 |
11 | public class SuccessActivity extends BaseActivity {
12 | private static final String TAG = "SuccessActivity";
13 | private Button toHomepageBtn;
14 | private TextView phoneTv;
15 | private String phone;
16 |
17 | @Override
18 | protected int getContentViewId() {
19 | return R.layout.activity_success;
20 | }
21 |
22 | @Override
23 | protected void getTitleStyle(TitleStyle titleStyle) {
24 | titleStyle.showLeft = false;
25 | }
26 |
27 | @Override
28 | protected void onViewCreated() {
29 | Intent i = getIntent();
30 | if (i != null) {
31 | LoginResult result = (LoginResult) i.getSerializableExtra(Const.EXTRAS_DEMO_LOGIN_RESULT);
32 | if (result != null) {
33 | phone = result.getPhone();
34 | }
35 | }
36 | initView();
37 | }
38 |
39 | @Override
40 | protected void onViewClicked(View v) {
41 | int id = v.getId();
42 | if (id == toHomepageBtn.getId()) {
43 | finish();
44 | }
45 | }
46 |
47 | private void initView() {
48 | toHomepageBtn = findViewById(R.id.sec_verify_demo_success_one_more_try_btn);
49 | toHomepageBtn.setOnClickListener(this);
50 | phoneTv = findViewById(R.id.sec_verify_demo_success_phone_tv);
51 | phoneTv.setText(phone);
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/core/ENV.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.core;
2 |
3 | public class ENV {
4 | public static final boolean DEBUG = false;
5 | }
6 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/core/ServerConfig.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.core;
2 |
3 | import android.text.TextUtils;
4 |
5 | public class ServerConfig {
6 | private static final String PROTOCOL = "http://";
7 | private static final String SERVER_URL_RELEASE = "demo.verify.mob.com";
8 |
9 | public static String getServerUrl() {
10 | return checkSuffix(PROTOCOL + SERVER_URL_RELEASE);
11 | }
12 |
13 | private static String checkSuffix(String url) {
14 | if (!TextUtils.isEmpty(url) && !url.endsWith("/")) {
15 | url += "/";
16 | }
17 | return url;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/entity/BaseEntity.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.entity;
2 |
3 | import com.google.gson.Gson;
4 | import com.mob.tools.utils.Hashon;
5 |
6 | import java.io.Serializable;
7 |
8 | public class BaseEntity implements Serializable {
9 | public String toJSONString() {
10 | Gson gson = new Gson();
11 | return gson.toJson(this);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/entity/LoginResult.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.entity;
2 |
3 | public class LoginResult extends BaseEntity {
4 | private String phone;
5 |
6 | public String getPhone() {
7 | return phone;
8 | }
9 |
10 | public void setPhone(String phone) {
11 | this.phone = phone;
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/exception/DemoErr.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.exception;
2 |
3 | public enum DemoErr {
4 | /** 服务端响应错误 */
5 | SERVER_RESPONSE_ERROR(1098, "Server response error"),
6 | /** 未知错误 */
7 | UNKNOWN_ERROR(1099, "Server response error");
8 |
9 | private int code;
10 | private String message;
11 |
12 | DemoErr(int code, String message) {
13 | this.code = code;
14 | this.message = message;
15 | }
16 |
17 | public int getCode() {
18 | return this.code;
19 | }
20 |
21 | public String getMessage() {
22 | return this.message;
23 | }
24 |
25 | public static DemoErr valueOf(int value) {
26 | switch (value) {
27 | case 1098: return SERVER_RESPONSE_ERROR;
28 | case 1099: return UNKNOWN_ERROR;
29 | }
30 | return null;
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/exception/DemoException.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.exception;
2 |
3 | public class DemoException extends Exception {
4 | protected int code;
5 |
6 | public DemoException(Throwable e){
7 | super(e);
8 | }
9 |
10 | public DemoException(DemoErr demoErr) {
11 | super(demoErr.getMessage());
12 | this.code = demoErr.getCode();
13 | }
14 |
15 | public DemoException(DemoErr demoErr, Throwable throwable){
16 | super(demoErr.getMessage(),throwable);
17 | this.code = demoErr.getCode();
18 | }
19 |
20 | public DemoException(int code, String message) {
21 | super(message);
22 | this.code = code;
23 | }
24 |
25 | public DemoException(int code, String message, Throwable t) {
26 | super(message, t);
27 | this.code = code;
28 | }
29 |
30 | public int getCode() {
31 | return this.code;
32 | }
33 |
34 | @Override
35 | public String toString() {
36 | return "{\"code\": " + code + ", \"message\": \"" + getMessage() + "\"}";
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/login/LoginTask.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.login;
2 |
3 | import com.mob.MobSDK;
4 | import com.mob.secverify.datatype.LoginToken;
5 | import com.mob.secverify.datatype.VerifyResult;
6 | import com.mob.secverify.demo.ResultListener;
7 | import com.mob.secverify.demo.core.ServerConfig;
8 | import com.mob.secverify.demo.entity.LoginResult;
9 | import com.mob.secverify.demo.net.HttpManager;
10 | import com.mob.tools.utils.DeviceHelper;
11 |
12 | import java.util.HashMap;
13 | import java.util.Map;
14 |
15 | public class LoginTask {
16 | private static final String TAG = LoginToken.class.getSimpleName();
17 | private static final String URL_LOGIN = "demo/sdkLogin";
18 | private static LoginTask instance;
19 |
20 | private LoginTask() {}
21 |
22 | public static LoginTask getInstance() {
23 | if (instance == null) {
24 | synchronized (LoginTask.class) {
25 | if (instance == null) {
26 | instance = new LoginTask();
27 | }
28 | }
29 | }
30 | return instance;
31 | }
32 |
33 | public void login(VerifyResult verifyResult, ResultListener resultListener) {
34 | Map values = new HashMap();
35 | if (verifyResult != null) {
36 | values.put("opToken", verifyResult.getOpToken());
37 | values.put("operator", verifyResult.getOperator());
38 | values.put("phoneOperator", verifyResult.getOperator());
39 | values.put("token", verifyResult.getToken());
40 | values.put("md5", DeviceHelper.getInstance(MobSDK.getContext()).getSignMD5());
41 | }
42 | HttpManager.getInstance().asyncPost(ServerConfig.getServerUrl() + URL_LOGIN, values, resultListener);
43 | }
44 |
45 | // public void loginForNoUI(com.mob.secverify.pure.entity.VerifyResult verifyResult, ResultListener resultListener) {
46 | // Map values = new HashMap();
47 | // if (verifyResult != null) {
48 | // values.put("opToken", verifyResult.getOpToken());
49 | // values.put("operator", verifyResult.getOperator());
50 | // values.put("phoneOperator", verifyResult.getOperator());
51 | // values.put("token", verifyResult.getToken());
52 | // values.put("md5", DeviceHelper.getInstance(MobSDK.getContext()).getSignMD5());
53 | // values.put("appkey", MobSDK.getAppkey());
54 | // }
55 | // HttpManager.getInstance().asyncPost(ServerConfig.getServerUrl() + URL_LOGIN, values, resultListener);
56 | // }
57 | }
58 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/AbstractHttp.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | import java.io.File;
4 | import java.util.Map;
5 |
6 | /**
7 | * Created by weishj on 2017/12/20.
8 | */
9 |
10 | public abstract class AbstractHttp {
11 | /** 默认编码 (UTF-8) */
12 | public static final String DEFAULT_ENCODING = "UTF-8";
13 | /** GET请求时 url和 参数的分隔符 */
14 | public static final String URL_AND_PARA_SEPARATOR = "?";
15 | /** 是否取消请求 */
16 | protected boolean isCancel = false;
17 | public static final int DEFAULT_BYTE_LENGTH = 8192;
18 | protected static final int LONG_TIME = 10000;
19 | protected int connectionTimeOut = LONG_TIME;
20 | protected int soTimeOut = LONG_TIME;
21 | public enum HttpMethod{
22 | /** GET请求 */
23 | GET,
24 | /** POST请求 */
25 | POST
26 | }
27 |
28 | /**
29 | * 构造
30 | */
31 | public AbstractHttp(){
32 | super();
33 | }
34 |
35 | public AbstractHttp(int connectionTimeOut,int soTimeOut){
36 | super();
37 | if(connectionTimeOut<0 || soTimeOut <0){
38 | throw new RuntimeException("connectionTimeOut<0 || soTimeOut<0");
39 | }
40 |
41 | if(connectionTimeOut>0)
42 | this.connectionTimeOut = connectionTimeOut;
43 | if(soTimeOut>0)
44 | this.soTimeOut = soTimeOut;
45 | }
46 |
47 | //-----------------------------------------
48 |
49 | /**
50 | * 取消请求
51 | */
52 | protected void cancel(){
53 | isCancel = true;
54 | }
55 |
56 | /**
57 | * 异步线程
58 | * @param runnable
59 | */
60 | protected void asyncThread(Runnable runnable){
61 | new Thread(runnable).start();
62 | }
63 |
64 |
65 | /**
66 | * 异步连接 默认GET请求
67 | * @param url
68 | * @param httpCallBack
69 | */
70 | public abstract void asyncConnect(String url, HttpCallBack httpCallBack);
71 |
72 | /**
73 | * 异步连接 默认GET请求
74 | * @param url
75 | * @param params
76 | * @param httpCallBack
77 | */
78 | public abstract void asyncConnect(String url, Map params, HttpCallBack httpCallBack);
79 | /**
80 | * 异步连接
81 | * @param url
82 | * @param params
83 | * @param httpMethod
84 | * @param httpCallBack
85 | */
86 | public abstract void asyncConnect(String url, Map params, HttpMethod httpMethod, HttpCallBack httpCallBack);
87 |
88 | /**
89 | * 同步连接 默认GET请求
90 | * @param url
91 | */
92 | public abstract String syncConnect(String url);
93 |
94 | /**
95 | * 同步连接 默认GET请求
96 | * @param url
97 | * @param params
98 | */
99 | public abstract String syncConnect(String url, Map params);
100 |
101 | /**
102 | * 同步连接 默认GET请求
103 | * @param url
104 | * @param params
105 | * @param httpMethod
106 | */
107 | public abstract String syncConnect(String url, Map params, HttpMethod httpMethod);
108 |
109 | /**
110 | * 同步连接 默认GET请求
111 | * @param url
112 | * @param params
113 | * @param httpCallBack
114 | */
115 | public abstract String syncConnect(String url, Map params, HttpCallBack httpCallBack);
116 |
117 | /**
118 | * 同步连接
119 | * @param url
120 | * @param params
121 | * @param httpMethod
122 | * @param httpCallBack
123 | */
124 | public abstract String syncConnect(String url, Map params, HttpMethod httpMethod, HttpCallBack httpCallBack);
125 |
126 |
127 | /**
128 | * 异步下载文件
129 | * @param url
130 | * @param fileName
131 | * @param httpDownloadCallBack
132 | * @return
133 | */
134 | public abstract void asyncDownloadFile(String url, String fileName, HttpCallBack httpDownloadCallBack);
135 |
136 | /**
137 | * 同步下载文件
138 | * @param url
139 | * @param fileName
140 | * @return
141 | */
142 | public abstract File syncDownloadFile(String url, String fileName);
143 |
144 | /**
145 | * 同步下载文件
146 | * @param url
147 | * @param fileName
148 | * @param httpDownloadCallBack
149 | * @return
150 | */
151 | public abstract File syncDownloadFile(String url, String fileName, HttpCallBack httpDownloadCallBack);
152 |
153 |
154 |
155 | }
156 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/HttpCallBack.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | /**
4 | * Created by weishj on 2017/12/20.
5 | */
6 |
7 | public interface HttpCallBack {
8 |
9 | /**
10 | * 开始
11 | * @param url
12 | */
13 | void onStart(String url);
14 |
15 | /**
16 | * 加载…
17 | * @param progress
18 | * @param count
19 | */
20 | void onLoading(long progress, long count);
21 |
22 | /**
23 | * 成功
24 | * @param t 返回的对象
25 | */
26 | void onSuccess(T t);
27 |
28 | /**
29 | * 失败
30 | * @param responseCode
31 | * @param e
32 | */
33 | void onFailure(int responseCode, Throwable e);
34 |
35 | /**
36 | * 取消
37 | */
38 | void onCancel();
39 | }
40 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/HttpConnectCallBack.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | /**
4 | * Created by weishj on 2017/12/20.
5 | */
6 |
7 | public abstract class HttpConnectCallBack implements HttpCallBack {
8 | @Override
9 | public abstract void onSuccess(String content);
10 | }
11 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/HttpDownloadCallBack.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | import java.io.File;
4 |
5 | /**
6 | * Created by weishj on 2017/12/20.
7 | */
8 |
9 | public abstract class HttpDownloadCallBack implements HttpCallBack {
10 | @Override
11 | public abstract void onSuccess(File file);
12 | }
13 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/HttpManager.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | import android.os.Handler;
4 | import android.os.Looper;
5 | import android.os.Message;
6 | import android.util.Log;
7 |
8 | import com.google.gson.Gson;
9 | import com.mob.secverify.demo.ResultListener;
10 | import com.mob.secverify.demo.exception.DemoErr;
11 | import com.mob.secverify.demo.exception.DemoException;
12 |
13 | import java.lang.reflect.ParameterizedType;
14 | import java.util.HashMap;
15 | import java.util.Map;
16 |
17 | public class HttpManager {
18 | private static final String TAG = HttpManager.class.getSimpleName();
19 | private static HttpManager instance;
20 | private NetworkHelper netHelper;
21 | private Gson gson;
22 |
23 | private HttpManager() {
24 | netHelper = new NetworkHelper(3000, 10000);
25 | gson = new Gson();
26 | }
27 |
28 | public static HttpManager getInstance() {
29 | if (instance == null) {
30 | synchronized (HttpManager.class) {
31 | if (instance == null) {
32 | instance = new HttpManager();
33 | }
34 | }
35 | }
36 | return instance;
37 | }
38 |
39 | public void asyncPost(String url, Map params, final ResultListener resultListener) {
40 | netHelper.asyncConnect(url, params, AbstractHttp.HttpMethod.POST, new HttpConnectCallBack() {
41 | @Override
42 | public void onStart(String url) {
43 |
44 | }
45 |
46 | @Override
47 | public void onLoading(long progress, long count) {
48 |
49 | }
50 |
51 | @Override
52 | public void onSuccess(String resp) {
53 | Class clazz = null;
54 | try {
55 | clazz = (Class) ((ParameterizedType) resultListener.getClass()
56 | .getGenericSuperclass()).getActualTypeArguments()[0];
57 | } catch (Throwable t) {
58 | Log.e(TAG, "post" + t.getMessage(), t);
59 | }
60 |
61 | final T data;
62 | if (clazz == HashMap.class) {
63 | data = gson.fromJson(resp, clazz);
64 | } else if (clazz == String.class) {
65 | data = (T) resp;
66 | } else {
67 | data = gson.fromJson(resp, clazz);
68 | }
69 | new Handler(Looper.getMainLooper(), new Handler.Callback() {
70 | @Override
71 | public boolean handleMessage(Message message) {
72 | resultListener.onComplete(data);
73 | return false;
74 | }
75 | }).sendEmptyMessage(0);
76 | }
77 |
78 | @Override
79 | public void onFailure(final int responseCode, final Throwable e) {
80 | new Handler(Looper.getMainLooper(), new Handler.Callback() {
81 | @Override
82 | public boolean handleMessage(Message message) {
83 | handleError(responseCode, e, resultListener);
84 | return false;
85 | }
86 | }).sendEmptyMessage(0);
87 | }
88 |
89 | @Override
90 | public void onCancel() {
91 |
92 | }
93 | });
94 | }
95 |
96 | private void handleError(int responseCode, Throwable t, ResultListener resultListener) {
97 | try {
98 | if (t != null) {
99 | HashMap map = gson.fromJson(t.getMessage(), HashMap.class);
100 | if (map != null) {
101 | // 错误响应示例:{"status":5119508,"res":null,"error":"免密登录失败"}
102 | double status = (Double) map.get("status");
103 | int code = (int) status;
104 | String msg = (String) map.get("error");
105 | if (resultListener != null) {
106 | resultListener.onFailure(new DemoException(code, msg, t));
107 | }
108 | } else {
109 | if (resultListener != null) {
110 | resultListener.onFailure(new DemoException(t));
111 | }
112 | }
113 | } else {
114 | if (resultListener != null) {
115 | resultListener.onFailure(new DemoException(DemoErr.UNKNOWN_ERROR));
116 | }
117 | }
118 | } catch (Throwable t1) {
119 | Log.e(TAG, "Server response error", t1);
120 | if (resultListener != null) {
121 | resultListener.onFailure(new DemoException(DemoErr.SERVER_RESPONSE_ERROR, t));
122 | }
123 | }
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/KVPair.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | public class KVPair {
4 | final public String name;
5 | final public T value;
6 |
7 | public KVPair(String name, T value) {
8 | this.name = name;
9 | this.value = value;
10 | }
11 |
12 | public String toString() {
13 | return name + " = " + value;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/net/NetworkHelper.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.net;
2 |
3 | import android.text.TextUtils;
4 | import android.util.Log;
5 |
6 | import com.google.gson.Gson;
7 | import com.google.gson.JsonObject;
8 | import com.google.gson.JsonParser;
9 | import com.mob.tools.utils.Data;
10 |
11 | import org.json.JSONObject;
12 |
13 | import java.io.BufferedInputStream;
14 | import java.io.BufferedReader;
15 | import java.io.File;
16 | import java.io.FileOutputStream;
17 | import java.io.InputStreamReader;
18 | import java.net.HttpURLConnection;
19 | import java.net.URL;
20 | import java.net.URLEncoder;
21 | import java.util.ArrayList;
22 | import java.util.HashMap;
23 | import java.util.Iterator;
24 | import java.util.Map;
25 |
26 | /**
27 | * Created by weishj on 2017/12/20.
28 | */
29 |
30 | public class NetworkHelper extends AbstractHttp{
31 | private static final String TAG = "SecVerifyDemo" + NetworkHelper.class.getSimpleName();
32 | private Gson gson;
33 |
34 | public NetworkHelper() {
35 | super();
36 | gson = new Gson();
37 | }
38 |
39 | public NetworkHelper(int connectionTimeOut, int soTimeOut) {
40 | super(connectionTimeOut, soTimeOut);
41 | gson = new Gson();
42 | }
43 |
44 | private HttpURLConnection getHttpURLConnection(String url, HttpMethod httpMethod, Map params) throws Throwable {
45 | if(HttpMethod.GET ==httpMethod){
46 | if(params!=null){
47 | ArrayList> list = new ArrayList>();
48 | for(String key : params.keySet()){
49 | list.add(new KVPair(key, String.valueOf(params.get(key))));
50 | }
51 | String paras = kvPairsToUrl(list);
52 | if (paras.length() > 0) {
53 | url += URL_AND_PARA_SEPARATOR + paras;
54 | }
55 | }
56 | }
57 | HttpURLConnection httpURLConnection = (HttpURLConnection)new URL(url).openConnection();
58 | // Header
59 | httpURLConnection.setRequestProperty("Content-Type", "application/json");
60 |
61 | httpURLConnection.setConnectTimeout(connectionTimeOut);
62 | httpURLConnection.setReadTimeout(soTimeOut);
63 | httpURLConnection.setUseCaches(false);
64 |
65 | String json = null;
66 | if(HttpMethod.POST ==httpMethod){
67 | httpURLConnection.setDoOutput(true);
68 | httpURLConnection.setRequestMethod("POST");
69 | Gson gson = new Gson();
70 | json = gson.toJson(params);
71 | if(!TextUtils.isEmpty(json))
72 | httpURLConnection.getOutputStream().write(json.getBytes());
73 | }else{
74 | httpURLConnection.setRequestMethod("GET");
75 | }
76 | Log.i(TAG, "=========== Http ==========");
77 | Log.i(TAG, "HEADER: "+ convertMaptoString(httpURLConnection.getHeaderFields()));
78 | Log.i(TAG, "PARAMS: " + json);
79 | Log.i(TAG, "HTTP METHOD: "+ httpURLConnection.getRequestMethod());
80 | Log.i(TAG, "URL:"+ url);
81 | Log.i(TAG, "=========== Http ==========");
82 | return httpURLConnection;
83 | }
84 |
85 | @Override
86 | public void asyncConnect(String url, HttpCallBack httpCallBack) {
87 | asyncConnect(url, null, httpCallBack);
88 | }
89 |
90 | @Override
91 | public void asyncConnect(String url, Map params,
92 | HttpCallBack httpCallBack) {
93 | asyncConnect(url, params, HttpMethod.GET, httpCallBack);
94 |
95 | }
96 |
97 | @Override
98 | public void asyncConnect(final String url, final Map params,
99 | final HttpMethod httpMethod, final HttpCallBack httpCallBack) {
100 | asyncThread(new Runnable() {
101 | @Override
102 | public void run() {
103 | syncConnect(url, params, httpMethod, httpCallBack);
104 | }
105 | });
106 |
107 | }
108 |
109 | @Override
110 | public String syncConnect(String url) {
111 | return syncConnect(url, null);
112 | }
113 |
114 | @Override
115 | public String syncConnect(String url, Map params) {
116 | return syncConnect(url, params, HttpMethod.GET);
117 | }
118 |
119 | @Override
120 | public String syncConnect(String url, Map params,
121 | HttpMethod httpMethod) {
122 | return syncConnect(url, params, httpMethod, null);
123 | }
124 |
125 | @Override
126 | public String syncConnect(String url, Map params,
127 | HttpCallBack httpCallBack) {
128 | return syncConnect(url, params, HttpMethod.GET, httpCallBack);
129 | }
130 |
131 | @Override
132 | public String syncConnect(String url, Map params,
133 | HttpMethod httpMethod, HttpCallBack httpCallBack) {
134 |
135 | if(TextUtils.isEmpty(url)){
136 | return null;
137 | }
138 |
139 | BufferedReader reader = null;
140 |
141 | HttpURLConnection httpURLConnection = null;
142 |
143 | int statusCode = -1;
144 | try {
145 | Log.v(TAG, url);
146 |
147 | if(httpCallBack!=null){
148 | httpCallBack.onStart(url);
149 | }
150 | httpURLConnection = getHttpURLConnection(url,httpMethod,params);
151 | httpURLConnection.connect();
152 | statusCode = httpURLConnection.getResponseCode();
153 | if(statusCode== HttpURLConnection.HTTP_OK){
154 |
155 | reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
156 |
157 | StringBuffer buffer = new StringBuffer();
158 | String line = null;
159 |
160 | long progress = 0;
161 |
162 | long count = httpURLConnection.getContentLength();
163 | isCancel = false;
164 | if(httpCallBack != null && count!=-1)
165 | httpCallBack.onLoading(progress, count);
166 | while ((!isCancel) && (line = reader.readLine())!=null) {
167 | buffer.append(line);
168 |
169 | if(httpCallBack != null && count!=-1){
170 | progress+= line.getBytes().length;
171 | httpCallBack.onLoading(progress, count);
172 | }
173 | }
174 |
175 |
176 | if(httpCallBack != null){
177 | if(!isCancel){
178 | progress = count;
179 | httpCallBack.onLoading(progress, count);
180 | }else{
181 | reader.close();
182 | httpCallBack.onCancel();
183 | return null;
184 | }
185 | }
186 | reader.close();
187 |
188 | // 正常响应示例:{"status":200,"res":{"phone":"13205558485"},"error":null}
189 | String str = buffer.toString();
190 | Log.i(TAG, "Response: "+ str);
191 | String res = "";
192 | try {
193 | JsonObject json = new JsonParser().parse(str).getAsJsonObject();
194 | JsonObject resJson = json.getAsJsonObject("res");
195 | res = resJson.toString();
196 | } catch (Throwable t) {
197 | Log.e(TAG, t.getMessage(), t);
198 | }
199 |
200 | if(httpCallBack != null && !isCancel) {
201 | httpCallBack.onSuccess(res);
202 | }
203 |
204 | if(httpURLConnection!=null) {
205 | httpURLConnection.disconnect();
206 | }
207 | return res;
208 | }else{
209 | reader = new BufferedReader(new InputStreamReader(httpURLConnection.getErrorStream()));
210 | StringBuffer buffer = new StringBuffer();
211 | String line;
212 | while ((line = reader.readLine())!=null) {
213 | buffer.append(line);
214 | }
215 | String errResponse = buffer.toString();
216 | if(httpCallBack != null) {
217 | httpCallBack.onFailure(statusCode, new Throwable(errResponse));
218 | }
219 |
220 | Log.i(TAG, "Response: "+ errResponse);
221 | return errResponse;
222 | }
223 | } catch (Throwable t) {
224 | Log.e(TAG, t.getMessage(), t);
225 | Map map = new HashMap();
226 | map.put("status", statusCode);
227 | map.put("error", t.getMessage());
228 | String msg = new Gson().toJson(map);
229 | Throwable resp = new Throwable(msg, t);
230 | if(httpCallBack != null)
231 | httpCallBack.onFailure(statusCode, resp);
232 | } finally {
233 |
234 | if(httpURLConnection!=null){
235 | httpURLConnection.disconnect();
236 | }
237 | }
238 |
239 | return null;
240 | }
241 |
242 | @Override
243 | public void asyncDownloadFile(final String url, final String fileName,
244 | final HttpCallBack httpDownloadCallBack) {
245 | asyncThread(new Runnable() {
246 | @Override
247 | public void run() {
248 | syncDownloadFile(url,fileName,httpDownloadCallBack);
249 | }
250 | });
251 | }
252 |
253 | @Override
254 | public File syncDownloadFile(String url, String fileName) {
255 | return syncDownloadFile(url, fileName, null);
256 | }
257 |
258 | @Override
259 | public File syncDownloadFile(String url, String fileName,
260 | HttpCallBack httpDownloadCallBack) {
261 |
262 | if(TextUtils.isEmpty(url)){
263 | return null;
264 | }
265 |
266 | File file = null;
267 |
268 | BufferedInputStream bis = null;
269 |
270 | FileOutputStream fos = null;
271 |
272 | HttpURLConnection httpURLConnection = null;
273 |
274 | int statusCode = -1;
275 | try {
276 | Log.v(TAG, url);
277 |
278 | if(TextUtils.isEmpty(fileName)){
279 | return null;
280 | }
281 |
282 | if(httpDownloadCallBack!=null)
283 | httpDownloadCallBack.onStart(url);
284 |
285 | httpURLConnection = getHttpURLConnection(url,HttpMethod.GET,null);
286 | httpURLConnection.connect();
287 | statusCode = httpURLConnection.getResponseCode();
288 | if(statusCode == HttpURLConnection.HTTP_OK){
289 |
290 | file = new File(fileName);
291 | fos = new FileOutputStream(file);
292 |
293 | long progress = 0;
294 |
295 | long count = httpURLConnection.getContentLength();
296 |
297 | bis = new BufferedInputStream(httpURLConnection.getInputStream());
298 |
299 | isCancel = false;
300 | byte[] buffer = new byte[DEFAULT_BYTE_LENGTH];
301 | int len = 0;
302 | if(httpDownloadCallBack!=null && count!=-1)
303 | httpDownloadCallBack.onLoading(progress, count);
304 | long time = System.currentTimeMillis();
305 | while((!isCancel) && (len = bis.read(buffer))!=-1){
306 | fos.write(buffer, 0, len);
307 | long temp = System.currentTimeMillis();
308 | if(temp-time>=1000){
309 | time = temp;
310 | if(httpDownloadCallBack!=null && count!=-1){
311 | progress += len;
312 | httpDownloadCallBack.onLoading(progress, count);
313 | }
314 | }
315 | }
316 |
317 | if(httpDownloadCallBack!=null ){
318 | if(!isCancel){
319 | progress = count;
320 | httpDownloadCallBack.onLoading(progress, count);
321 | }else{
322 | bis.close();
323 | fos.close();
324 | httpDownloadCallBack.onCancel();
325 |
326 | if(httpURLConnection!=null)
327 | httpURLConnection.disconnect();
328 |
329 | return file;
330 | }
331 | }
332 |
333 | bis.close();
334 | fos.close();
335 |
336 | if(httpDownloadCallBack!=null && !isCancel)
337 | httpDownloadCallBack.onSuccess(file);
338 |
339 | }else{
340 | if(httpDownloadCallBack!=null)
341 | httpDownloadCallBack.onFailure(statusCode, null);
342 | }
343 |
344 | } catch (Throwable e) {
345 | Log.e(TAG, e.getMessage(), e);
346 | if(httpDownloadCallBack!=null)
347 | httpDownloadCallBack.onFailure(statusCode, e);
348 | }finally{
349 | if(httpURLConnection!=null)
350 | httpURLConnection.disconnect();
351 | }
352 |
353 | return file;
354 | }
355 |
356 | /**
357 | * Convert map to string.
358 | *
359 | * This method will call the toString() method of K and V.
360 | *
361 | * @param map the map to be output.
362 | * @return the string result.
363 | */
364 | private String convertMaptoString(Map map) {
365 | if (map == null) {
366 | return "";
367 | }
368 | String str = "[";
369 | Iterator it = map.entrySet().iterator();
370 | while (it.hasNext()) {
371 | Map.Entry pair = (Map.Entry) it.next();
372 | str += " " + pair.getKey() + ":" + (pair.getValue() == null ? "" : pair.getValue());
373 | }
374 | return str + " ]";
375 | }
376 |
377 | private String kvPairsToUrl(ArrayList> values) throws Throwable {
378 | StringBuilder sb = new StringBuilder();
379 | for (KVPair value : values) {
380 | String encodedName = urlEncode(value.name, DEFAULT_ENCODING);
381 | String encodedValue = value.value != null
382 | ? Data.urlEncode(value.value, DEFAULT_ENCODING) : "";
383 | if (sb.length() > 0) {
384 | sb.append('&');
385 | }
386 | sb.append(encodedName).append('=').append(encodedValue);
387 | }
388 | return sb.toString();
389 | }
390 |
391 | public static String urlEncode(String s, String enc) throws Throwable {
392 | String text = URLEncoder.encode(s, enc);
393 | return TextUtils.isEmpty(text) ? text : text.replace("+", "%20");
394 | }
395 | }
396 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ui/component/CommonAlertDialog.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.ui.component;
2 |
3 | import android.app.Dialog;
4 | import android.content.Context;
5 | import android.os.Bundle;
6 | import android.text.SpannableString;
7 | import android.text.TextUtils;
8 | import android.util.DisplayMetrics;
9 | import android.view.KeyEvent;
10 | import android.view.View;
11 | import android.view.WindowManager;
12 | import android.widget.LinearLayout;
13 | import android.widget.TextView;
14 |
15 | import com.mob.secverify.demo.ResultListener;
16 | import com.mob.tools.utils.ResHelper;
17 |
18 | public class CommonAlertDialog extends Dialog implements View.OnClickListener {
19 |
20 | private Context context;
21 | private static CommonAlertDialog dialog;
22 | private WindowManager windowManager;
23 | private String dialogText;
24 | private SpannableString spannableDialogText;
25 | private ResultListener callback;
26 |
27 | public CommonAlertDialog(Context context) {
28 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
29 | this.context = context;
30 | }
31 |
32 | public CommonAlertDialog(Context context, String dialogText,ResultListener callback) {
33 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
34 | this.context = context;
35 | this.dialogText = dialogText;
36 | this.callback = callback;
37 | }
38 |
39 | public CommonAlertDialog(Context context, SpannableString dialogText,ResultListener callback) {
40 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
41 | this.context = context;
42 | this.spannableDialogText = dialogText;
43 | this.callback = callback;
44 | }
45 |
46 | public CommonAlertDialog(Context context,int themeResId) {
47 | super(context, themeResId);
48 | this.context = context;
49 | }
50 |
51 | @Override
52 | protected void onCreate(Bundle savedInstanceState) {
53 | super.onCreate(savedInstanceState);
54 | setCancelable(false);
55 | setCanceledOnTouchOutside(false);
56 | int width = (int) (getDeviceWidth(context) * 0.6);
57 | int height = (int) (getDeviceWidth(context) * 0.5);
58 | View view = getLayoutInflater().inflate(ResHelper.getLayoutRes(context, "sec_verify_demo_common_alert_dialog"), null);
59 | setContentView(view, new LinearLayout.LayoutParams(width, height));
60 |
61 | initView();
62 | }
63 |
64 | private void initView() {
65 | TextView dialogCancel = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_cancel"));
66 | TextView dialogAllow = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_allow"));
67 | TextView dialogTitle = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_title"));
68 | TextView dialogTextTv = findViewById(ResHelper.getIdRes(context,"sec_verify_demo_alert_dialog_text"));
69 | dialogTitle.setText("无法使用移动网络");
70 | dialogAllow.setText("前往");
71 | dialogCancel.setText("取消");
72 | if (!TextUtils.isEmpty(dialogText)){
73 | dialogTextTv.setText(dialogText);
74 | } else if (!TextUtils.isEmpty(spannableDialogText)){
75 | dialogTextTv.setText(spannableDialogText);
76 | }
77 | }
78 |
79 | public static void showProgressDialog(Context context) {
80 | showProgressDialog(context,"",null);
81 | }
82 |
83 | public static void showProgressDialog(Context context, String dialogText, ResultListener callback) {
84 | dismissProgressDialog();
85 | dialog = new CommonAlertDialog(context,dialogText,callback);
86 | dialog.show();
87 | }
88 |
89 | public static void showProgressDialog(Context context, SpannableString dialogText, ResultListener callback) {
90 | dismissProgressDialog();
91 | dialog = new CommonAlertDialog(context,dialogText,callback);
92 | dialog.show();
93 | }
94 |
95 | public static void dismissProgressDialog() {
96 | try {
97 | if ((dialog != null) && dialog.isShowing()) {
98 | dialog.dismiss();
99 | }
100 | } catch (final IllegalArgumentException e) {
101 | // Handle or log or ignore
102 | } catch (final Exception e) {
103 | // Handle or log or ignore
104 | } finally {
105 | dialog = null;
106 | }
107 |
108 | // if (dialog != null && dialog.isShowing()) {
109 | // dialog.dismiss();
110 | // dialog = null;
111 | // }
112 | }
113 |
114 |
115 | private int getDeviceWidth(Context context) {
116 | if (windowManager == null) {
117 | windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
118 | }
119 | DisplayMetrics dm = new DisplayMetrics();
120 | windowManager.getDefaultDisplay().getMetrics(dm);
121 | return dm.widthPixels;
122 | }
123 |
124 | @Override
125 | public boolean onKeyDown(int keyCode, KeyEvent event){//按键回调方法
126 | if(keyCode == KeyEvent.KEYCODE_BACK){//判断按键键值做出相应操作
127 | dismissProgressDialog();
128 | }
129 | return super.onKeyDown(keyCode,event);//其他按键继承系统属性
130 | }
131 |
132 | @Override
133 | public void onClick(View v) {
134 | int id = v.getId();
135 | if (id == ResHelper.getIdRes(context,"sec_verify_demo_alert_dialog_cancel")){
136 | dismissProgressDialog();
137 | } else if (id == ResHelper.getIdRes(context,"sec_verify_demo_alert_dialog_allow")){
138 | dismissProgressDialog();
139 | callback.onComplete(null);
140 | }
141 | }
142 | }
143 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ui/component/CommonProgressDialog.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.ui.component;
2 |
3 | import android.app.Dialog;
4 | import android.content.Context;
5 | import android.os.Bundle;
6 | import android.util.DisplayMetrics;
7 | import android.view.View;
8 | import android.view.WindowManager;
9 | import android.widget.RelativeLayout;
10 |
11 | import com.mob.tools.utils.ResHelper;
12 |
13 | public class CommonProgressDialog extends Dialog {
14 |
15 | private Context context;
16 | private static CommonProgressDialog dialog;
17 | private WindowManager windowManager;
18 |
19 | public CommonProgressDialog(Context context) {
20 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
21 | this.context = context;
22 | }
23 |
24 | public CommonProgressDialog(Context context, int themeResId) {
25 | super(context, themeResId);
26 | this.context = context;
27 | }
28 |
29 | @Override
30 | protected void onCreate(Bundle savedInstanceState) {
31 | super.onCreate(savedInstanceState);
32 | setCancelable(false);
33 | setCanceledOnTouchOutside(false);
34 | int width = (int) (getDeviceWidth(context) * 0.2);
35 | View view = getLayoutInflater().inflate(ResHelper.getLayoutRes(context, "sec_verify_demo_common_progress_dialog"), null);
36 | setContentView(view, new RelativeLayout.LayoutParams(width, width));
37 | }
38 |
39 | public static void showProgressDialog(Context context) {
40 | dismissProgressDialog();
41 | dialog = new CommonProgressDialog(context);
42 | dialog.show();
43 | }
44 |
45 | public static void dismissProgressDialog() {
46 | try {
47 | if ((dialog != null) && dialog.isShowing()) {
48 | dialog.dismiss();
49 | }
50 | } catch (final IllegalArgumentException e) {
51 | // Handle or log or ignore
52 | } catch (final Exception e) {
53 | // Handle or log or ignore
54 | } finally {
55 | dialog = null;
56 | }
57 | }
58 |
59 | private int getDeviceWidth(Context context) {
60 | if (windowManager == null) {
61 | windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
62 | }
63 | DisplayMetrics dm = new DisplayMetrics();
64 | windowManager.getDefaultDisplay().getMetrics(dm);
65 | return dm.widthPixels;
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ui/component/DemoAdapter.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.ui.component;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.content.pm.ActivityInfo;
6 | import android.graphics.Color;
7 | import android.graphics.Typeface;
8 | import android.os.Build;
9 | import android.text.SpannableString;
10 | import android.text.Spanned;
11 | import android.text.TextPaint;
12 | import android.text.TextUtils;
13 | import android.text.method.LinkMovementMethod;
14 | import android.text.style.ClickableSpan;
15 | import android.text.style.ForegroundColorSpan;
16 | import android.view.Gravity;
17 | import android.view.View;
18 | import android.view.ViewGroup;
19 | import android.view.WindowManager;
20 | import android.widget.Button;
21 | import android.widget.CheckBox;
22 | import android.widget.CompoundButton;
23 | import android.widget.ImageView;
24 | import android.widget.LinearLayout;
25 | import android.widget.RelativeLayout;
26 | import android.widget.TextView;
27 | import android.widget.Toast;
28 |
29 | import com.mob.MobSDK;
30 | import com.mob.secverify.demo.R;
31 | import com.mob.secverify.demo.util.OperatorUtils;
32 | import com.mob.secverify.ui.AgreementPage;
33 | import com.mob.secverify.ui.component.LoginAdapter;
34 | import com.mob.tools.utils.ResHelper;
35 |
36 | /**
37 | * 使用Adapter的方式修改授权页面ui,通过修改授权页面的控件属性,达到修改目的
38 | *
39 | * * todo 需要注意以下内容
40 | * * 1、在结束当前授权页面时需要调用SecVerify.finishOAuthPage();来结束,否则会影响下次进入
41 | * * 2、在点击登录之后,不论登录成功或者失败,需要SecVerify.finishOAuthPage();结束当前页面, 否则会影响电信授权页面的回调导致页面无法结束
42 | * * 3、设置脱敏手机号需要在onResume中设置,onCreate中可能还未拿到这个脱敏手机号
43 | */
44 | public class DemoAdapter extends LoginAdapter implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
45 | private Activity activity;
46 | private ViewGroup vgBody;
47 | private ViewGroup vgContainer;
48 | private RelativeLayout rlTitle;
49 | private ImageView ivLogo;
50 | private Button btnLogin;
51 | private TextView tvSecurityPhone;
52 | private CheckBox cbAgreement;
53 | private RelativeLayout rlPhone;
54 | private TextView tvSwitchAcc;
55 | private RelativeLayout rlAgreement;
56 | private TextView tvSlogan;
57 | private ImageView ivLeftClose;
58 | private TextView tvCenterText;
59 | private TextView tvAgreement;
60 | private String operator;
61 | private String url;
62 |
63 | @Override
64 | public void onCreate() {
65 | super.onCreate();
66 | init();
67 | setImmTheme();
68 | requestOrientation();
69 | if (activity.getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
70 | //当前为竖屏
71 | rebuildBodyContent();
72 | } else {
73 | //当前为横屏设置,参考rebuildBodyContent();设置
74 | }
75 | }
76 |
77 | //Android 8.0不可设置为固定方向
78 | private void requestOrientation() {
79 | // activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
80 | // activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
81 | activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
82 | }
83 |
84 |
85 | private void setImmTheme() {
86 | if (Build.VERSION.SDK_INT >= 21) {
87 | // 设置沉浸式状态栏
88 | View decorView = activity.getWindow().getDecorView();
89 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
90 | | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
91 | decorView.setSystemUiVisibility(option);
92 | // 设置状态栏透明
93 | activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
94 | activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
95 | activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
96 | if (Build.VERSION.SDK_INT >= 23) {
97 | activity.getWindow().getDecorView().setSystemUiVisibility(
98 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
99 | }
100 | }
101 | //是否占用状态栏的位置,false为占用,true为不占用
102 | vgContainer.setFitsSystemWindows(false);
103 | //是否全屏
104 | // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
105 | //如果不想适配P以上的水滴屏和刘海屏,可以在这里设置layoutInDisplayCutoutMode为其他的值
106 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
107 | WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
108 | lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
109 | activity.getWindow().setAttributes(lp);
110 | }
111 | }
112 |
113 | private void rebuildBodyContent() {
114 | //导航栏以下背景图片设置
115 | vgBody.setBackground(activity.getResources().getDrawable(R.color.sec_verify_text_color_common_white));
116 | //整个授权页面背景图片设置
117 | vgContainer.setBackground(activity.getResources().getDrawable(R.color.sec_verify_text_color_common_white));
118 |
119 | //头部导航栏设置
120 | rlTitle.setVisibility(View.VISIBLE);
121 | rlTitle.setBackgroundColor(activity.getResources().getColor(R.color.sec_verify_demo_main_color));
122 | rlTitle.getBackground().setAlpha(0);//透明度
123 | LinearLayout.LayoutParams rlTitleParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
124 | rlTitleParams.height = ResHelper.dipToPx(activity,50);
125 | rlTitle.setLayoutParams(rlTitleParams);
126 |
127 | //关闭图标相关设置
128 | ivLeftClose.setVisibility(View.VISIBLE);
129 | ivLeftClose.setImageDrawable(activity.getResources().getDrawable(R.drawable.sec_verify_page_one_key_login_close));
130 | ivLeftClose.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
131 | RelativeLayout.LayoutParams ivLeftCloseParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
132 | ivLeftCloseParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
133 | ivLeftCloseParams.addRule(RelativeLayout.CENTER_VERTICAL);
134 | ivLeftCloseParams.leftMargin = ResHelper.dipToPx(activity,20);
135 | ivLeftClose.setLayoutParams(ivLeftCloseParams);
136 | //导航栏标题
137 | tvCenterText.setText("一键登录");
138 | tvCenterText.setVisibility(View.VISIBLE);
139 | tvCenterText.setTypeface(Typeface.DEFAULT_BOLD);
140 | tvCenterText.setTextSize(16);
141 | tvCenterText.setTextColor(activity.getResources().getColor(R.color.sec_verify_demo_text_color_common_black));
142 | RelativeLayout.LayoutParams tvCenterTextParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
143 | tvCenterTextParams.addRule(RelativeLayout.CENTER_IN_PARENT);
144 | tvCenterText.setLayoutParams(tvCenterTextParams);
145 | //logo
146 | ivLogo.setVisibility(View.VISIBLE);
147 | ivLogo.setImageDrawable(activity.getResources().getDrawable(R.drawable.sec_verify_page_one_key_login_logo));
148 | ivLogo.setScaleType(ImageView.ScaleType.FIT_CENTER);
149 | RelativeLayout.LayoutParams ivLogoParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
150 | ivLogoParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
151 | ivLogoParams.width = ResHelper.dipToPx(activity,80);
152 | ivLogoParams.height = ResHelper.dipToPx(activity,80);
153 | ivLogoParams.topMargin = ResHelper.dipToPx(activity,30);
154 | ivLogo.setLayoutParams(ivLogoParams);
155 | //脱敏手机号
156 | tvSecurityPhone.setTextColor(activity.getResources().getColor(R.color.sec_verify_demo_text_color_common_black));
157 | tvSecurityPhone.setTextSize(20);
158 | tvSecurityPhone.setTypeface(Typeface.DEFAULT_BOLD);
159 | tvSecurityPhone.setVisibility(View.VISIBLE);
160 | RelativeLayout.LayoutParams tvSecurityPhoneParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
161 | tvSecurityPhoneParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
162 | tvSecurityPhoneParams.topMargin = ResHelper.dipToPx(activity,135);
163 | rlPhone.setLayoutParams(tvSecurityPhoneParams); //注意是rlPhone 不是tvSecurityPhone
164 | //切换其他方式登录
165 | tvSwitchAcc.setVisibility(View.VISIBLE);
166 | tvSwitchAcc.setTypeface(Typeface.DEFAULT_BOLD);
167 | tvSwitchAcc.setTextSize(16);
168 | tvSwitchAcc.setTextColor(activity.getResources().getColor(R.color.sec_verify_demo_text_color_blue));
169 | tvSwitchAcc.setText("切换其他方式登录");
170 | RelativeLayout.LayoutParams tvSwitchAccParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
171 | tvSwitchAccParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
172 | tvSwitchAccParams.topMargin = ResHelper.dipToPx(activity,180);
173 | tvSwitchAcc.setLayoutParams(tvSwitchAccParams);
174 | //登录按钮
175 | btnLogin.setText("登录");
176 | btnLogin.setBackground(activity.getResources().getDrawable(R.drawable.sec_verify_demo_shape_rectangle));
177 | btnLogin.setTextColor(activity.getResources().getColor(R.color.sec_verify_demo_text_color_common_white));
178 | btnLogin.setTextSize(16);
179 | btnLogin.setTypeface(Typeface.DEFAULT_BOLD);
180 | btnLogin.setVisibility(View.VISIBLE);
181 | RelativeLayout.LayoutParams btnLoginParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
182 | btnLoginParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
183 | btnLoginParams.height = ResHelper.dipToPx(activity,45);
184 | btnLoginParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
185 | btnLoginParams.topMargin = ResHelper.dipToPx(activity,220);
186 | btnLoginParams.leftMargin = ResHelper.dipToPx(activity,30);
187 | btnLoginParams.rightMargin = ResHelper.dipToPx(activity,30);
188 | btnLogin.setLayoutParams(btnLoginParams);
189 | //隐私协议
190 | cbAgreement.setVisibility(View.VISIBLE);
191 | cbAgreement.setButtonDrawable(activity.getResources().getDrawable(R.drawable.customized_checkbox_selector));
192 | cbAgreement.setChecked(false);
193 | tvAgreement.setText(buildSpanString());
194 | tvAgreement.setHighlightColor(activity.getResources().getColor(android.R.color.transparent));
195 | tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
196 | rlAgreement.setVisibility(View.VISIBLE);
197 | RelativeLayout.LayoutParams rlAgreementParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
198 | rlAgreementParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
199 | rlAgreementParams.topMargin = ResHelper.dipToPx(activity,280);
200 | rlAgreementParams.leftMargin = ResHelper.dipToPx(activity,30);
201 | rlAgreementParams.rightMargin = ResHelper.dipToPx(activity,30);
202 | rlAgreementParams.addRule(Gravity.LEFT);
203 | rlAgreement.setLayoutParams(rlAgreementParams);
204 |
205 | //slogan
206 | String operatorSlogan = "";
207 | if (OperatorUtils.getCellularOperatorType() == 1) {
208 | operatorSlogan = "中国移动提供认证服务";
209 | } else if (OperatorUtils.getCellularOperatorType() == 2) {
210 | operatorSlogan = "中国联通提供认证服务";
211 | } else if (OperatorUtils.getCellularOperatorType() == 3) {
212 | operatorSlogan = "中国电信提供认证服务";
213 | }
214 | tvSlogan.setText(operatorSlogan);
215 | tvSlogan.setTextSize(12);
216 | tvSlogan.setTextColor(activity.getResources().getColor(R.color.sec_verify_demo_text_color_common_black));
217 | tvSlogan.setTypeface(Typeface.DEFAULT_BOLD);
218 | tvSlogan.setVisibility(View.VISIBLE);
219 | RelativeLayout.LayoutParams tvSloganParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
220 | tvSloganParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
221 | tvSloganParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
222 | tvSloganParams.bottomMargin = ResHelper.dipToPx(activity,30);
223 | tvSlogan.setLayoutParams(tvSloganParams);
224 | }
225 |
226 | private SpannableString buildSpanString() {
227 | String operatorText = "";
228 | if (OperatorUtils.getCellularOperatorType() == 1) {
229 | operatorText = "《中国移动认证服务条款》";
230 | url = "https://wap.cmpassport.com/resources/html/contract.html";
231 | } else if (OperatorUtils.getCellularOperatorType() == 2) {
232 | operatorText = "《中国联通认证服务条款》";
233 | url = "https://ms.zzx9.cn/html/oauth/protocol2.html";
234 | } else if (OperatorUtils.getCellularOperatorType() == 3) {
235 | operatorText = "《中国电信认证服务条款》";
236 | url = "https://e.189.cn/sdk/agreement/content.do?type=main&appKey=&hidetop=true&returnUrl=";
237 | }
238 | String ageementText = "同意" + operatorText + "及《自有隐私协议》和" +
239 | "《自有服务策略》、《其他隐私协议》并授权秒验使用本机号码登录";
240 | String cusPrivacy1 = "《自有隐私协议》";
241 | String cusPrivacy2 = "《自有服务策略》";
242 | String cusPrivacy3 = "《其他隐私协议》";
243 | int baseColor = MobSDK.getContext().getResources().getColor(R.color.sec_verify_demo_text_color_common_black);
244 | int privacyColor = Color.parseColor("#FFFE7A4E");
245 | int cusPrivacyColor1 = Color.parseColor("#FF4E96FF");
246 | int cusPrivacyColor2 = Color.parseColor("#FF4E96FF");
247 | int cusPrivacyColor3 = Color.parseColor("#FFFE7A4E");
248 | SpannableString spanStr = new SpannableString(ageementText);
249 | int privacyIndex = ageementText.indexOf(operatorText);
250 | spanStr.setSpan(new ForegroundColorSpan(baseColor)
251 | , 0, ageementText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
252 | //设置文字的单击事件
253 | spanStr.setSpan(new ClickableSpan() {
254 | @Override
255 | public void updateDrawState(TextPaint ds) {
256 | ds.setUnderlineText(false);
257 | }
258 |
259 | @Override
260 | public void onClick(View widget) {
261 | gotoAgreementPage(url, "");
262 | }
263 | }, privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
264 | //设置文字的前景色
265 | spanStr.setSpan(new ForegroundColorSpan(privacyColor), privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
266 | if (!TextUtils.isEmpty(cusPrivacy1)) {
267 | int privacy1Index = ageementText.indexOf(cusPrivacy1);
268 | //设置文字的单击事件
269 | spanStr.setSpan(new ClickableSpan() {
270 | @Override
271 | public void updateDrawState(TextPaint ds) {
272 | ds.setUnderlineText(false);
273 | }
274 |
275 | @Override
276 | public void onClick(View widget) {
277 | gotoAgreementPage("https://www.mob.com", null);
278 | // if (wrapper != null && wrapper.cusAgreement1Clicked != null){
279 | // wrapper.cusAgreement1Clicked.handle();
280 | // }
281 | }
282 | }, privacy1Index, privacy1Index + "《自有隐私协议》".length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
283 | //设置文字的前景色
284 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor1), privacy1Index, privacy1Index + cusPrivacy1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
285 | }
286 | if (!TextUtils.isEmpty(cusPrivacy2)) {
287 | int privacy2Index = ageementText.lastIndexOf(cusPrivacy2);
288 | //设置文字的单击事件
289 | spanStr.setSpan(new ClickableSpan() {
290 | @Override
291 | public void updateDrawState(TextPaint ds) {
292 | ds.setUnderlineText(false);
293 | }
294 |
295 | @Override
296 | public void onClick(View widget) {
297 | gotoAgreementPage("https://www.baidu.com", null);
298 | }
299 | }, privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
300 | //设置文字的前景色
301 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor2), privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
302 | }
303 | if (!TextUtils.isEmpty(cusPrivacy3)) {
304 | int privacy3Index = ageementText.lastIndexOf(cusPrivacy3);
305 | //设置文字的单击事件
306 | spanStr.setSpan(new ClickableSpan() {
307 | @Override
308 | public void updateDrawState(TextPaint ds) {
309 | ds.setUnderlineText(false);
310 | ds.linkColor = Color.parseColor("#FFFFFF");
311 | }
312 |
313 | @Override
314 | public void onClick(View widget) {
315 | gotoAgreementPage("https://www.baidu.com", null);
316 | }
317 | }, privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
318 | //设置文字的前景色
319 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor3), privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
320 | }
321 | return spanStr;
322 | }
323 |
324 | //可替换为跳转自己的webview
325 | private static void gotoAgreementPage(String agreementUrl, String title) {
326 | if (TextUtils.isEmpty(agreementUrl)) {
327 | return;
328 | }
329 | AgreementPage page = new AgreementPage();
330 | Intent i = new Intent();
331 | i.putExtra("extra_agreement_url", agreementUrl);
332 | if (!TextUtils.isEmpty(title)) {
333 | i.putExtra("privacy", title);
334 | }
335 | page.show(MobSDK.getContext(), i);
336 | }
337 |
338 | private void init() {
339 | vgBody = getBodyView();
340 | vgContainer = getContainerView();
341 | activity = getActivity();
342 | rlTitle = getTitlelayout();
343 | ivLeftClose = getLeftCloseImage();
344 | tvCenterText = getCenterText();
345 | ivLogo = getLogoImage();
346 | btnLogin = getLoginBtn();
347 | tvSecurityPhone = getSecurityPhoneText();
348 | cbAgreement = getAgreementCheckbox();
349 | rlPhone = getPhoneLayout();
350 | tvSwitchAcc = getSwitchAccText();
351 | rlAgreement = getAgreementLayout();
352 | tvSlogan = getSloganText();
353 | tvAgreement = getAgreementText();
354 | operator = getOperatorName();
355 |
356 | //不支持匿名内部的方法来执行点击事件,会出现无法正常登录的情况
357 | btnLogin.setOnClickListener(this);
358 | ivLeftClose.setOnClickListener(this);
359 | tvSwitchAcc.setOnClickListener(this);
360 | cbAgreement.setOnClickListener(this);
361 | cbAgreement.setOnCheckedChangeListener(this);
362 | }
363 |
364 |
365 | @Override
366 | public void onClick(View v) {
367 | if (v.getId() == btnLogin.getId()) {
368 | Toast.makeText(activity.getApplicationContext(), "自定义Adapter 登录按钮点击事件", Toast.LENGTH_SHORT).show();
369 | } else if (v.getId() == ivLeftClose.getId()) {
370 | Toast.makeText(activity.getApplicationContext(), "自定义Adapter 关闭按钮点击事件", Toast.LENGTH_SHORT).show();
371 | } else if (v.getId() == tvSwitchAcc.getId()) {
372 | Toast.makeText(activity.getApplicationContext(), "自定义Adapter 切换登录按钮点击事件", Toast.LENGTH_SHORT).show();
373 | } else if (v.getId() == cbAgreement.getId()) {
374 | Toast.makeText(activity.getApplicationContext(), "自定义Adapter 复选框点击事件", Toast.LENGTH_SHORT).show();
375 | }
376 | //一定要记得加上这句
377 | super.onClick(v);
378 | }
379 |
380 | @Override
381 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
382 | //如果不加这句,那么OtherOAuthPageCallBack 不会有复选框改变的回调
383 | super.onCheckedChanged(buttonView, isChecked);
384 | }
385 | }
386 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ui/component/DialogAdapter.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.ui.component;
2 |
3 | import android.app.Activity;
4 | import android.content.Intent;
5 | import android.content.pm.ActivityInfo;
6 | import android.graphics.Color;
7 | import android.os.Build;
8 | import android.text.SpannableString;
9 | import android.text.Spanned;
10 | import android.text.TextPaint;
11 | import android.text.TextUtils;
12 | import android.text.method.LinkMovementMethod;
13 | import android.text.style.ClickableSpan;
14 | import android.text.style.ForegroundColorSpan;
15 | import android.view.Gravity;
16 | import android.view.View;
17 | import android.view.ViewGroup;
18 | import android.view.WindowManager;
19 | import android.widget.Button;
20 | import android.widget.CheckBox;
21 | import android.widget.LinearLayout;
22 | import android.widget.RelativeLayout;
23 | import android.widget.TextView;
24 |
25 | import com.mob.MobSDK;
26 | import com.mob.secverify.demo.R;
27 | import com.mob.secverify.demo.util.OperatorUtils;
28 | import com.mob.secverify.ui.AgreementPage;
29 | import com.mob.secverify.ui.component.LoginAdapter;
30 | import com.mob.tools.utils.ResHelper;
31 |
32 | /**
33 | * 使用Adapter的方式修改授权页面ui,支持使用自己的inflate的xml布局
34 | */
35 | public class DialogAdapter extends LoginAdapter {
36 | private Activity activity;
37 | private ViewGroup vgBody;
38 | private LinearLayout vgContainer;
39 | private RelativeLayout rlTitle;
40 | private Button btnLogin;
41 | private TextView tvSecurityPhone;
42 | private TextView tvOwnPhone;
43 | private TextView tvAgreement;
44 | private CheckBox cbAgreement;
45 | private View contentView;
46 | //可用于判断展示运营商隐私协议
47 | private String operator;
48 | private String url;
49 |
50 | @Override
51 | public void onCreate() {
52 | super.onCreate();
53 | //获取授权页面原有控件
54 | init();
55 | //设置授权页面主题
56 | setImmTheme();
57 | //设置授权页面方向
58 | requestOrientation();
59 | //隐藏 授权页面原有内容
60 | vgBody.setVisibility(View.GONE);
61 | rlTitle.setVisibility(View.GONE);
62 | //获取自己的View
63 | contentView = View.inflate(activity, R.layout.sec_verify_demo_dialog_one_key_login, null);
64 | LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
65 | params.width = ResHelper.dipToPx(activity, 300);
66 | params.height = ResHelper.dipToPx(activity, 300);
67 | vgContainer.setGravity(Gravity.CENTER);
68 | vgContainer.setBackgroundColor(activity.getResources().getColor(R.color.sec_verify_demo_background_transparent));
69 | //添加自己的View到授权页面上,注意不要使用Activity来设置
70 | vgContainer.addView(contentView, params);
71 |
72 | initOwnView();
73 | }
74 |
75 | private void initOwnView() {
76 | tvOwnPhone = contentView.findViewById(R.id.sec_verify_page_one_key_login_phone);
77 | tvOwnPhone.setText(tvSecurityPhone.getText());
78 |
79 | tvAgreement = contentView.findViewById(R.id.sec_verify_page_login_use_this_number);
80 | tvAgreement.setText(buildSpanString());
81 | tvAgreement.setHighlightColor(activity.getResources().getColor(android.R.color.transparent));
82 | tvAgreement.setMovementMethod(LinkMovementMethod.getInstance());
83 |
84 | contentView.findViewById(R.id.sec_verify_page_login_login_btn).setOnClickListener(new View.OnClickListener() {
85 | @Override
86 | public void onClick(View v) {
87 | //点击自己登录按钮时需要将默认的复选框设置为选中,并且点击原有的授权页面登录按钮
88 | cbAgreement.setChecked(true);
89 | btnLogin.performClick();
90 | }
91 | });
92 | }
93 |
94 | @Override
95 | public void onResume() {
96 | super.onResume();
97 | //将授权页面本身控件的文本设置到自己的View上面
98 | tvOwnPhone.setText(tvSecurityPhone.getText());
99 | }
100 |
101 | private void init() {
102 | vgBody = getBodyView();
103 | vgContainer = (LinearLayout) getContainerView();
104 | activity = getActivity();
105 | rlTitle = getTitlelayout();
106 | btnLogin = getLoginBtn();
107 | tvSecurityPhone = getSecurityPhoneText();
108 | cbAgreement = getAgreementCheckbox();
109 | operator = getOperatorName();
110 |
111 |
112 | // //不支持匿名内部的方法来执行点击事件,会出现无法正常登录的情况
113 | // btnLogin.setOnClickListener(this);
114 | // ivLeftClose.setOnClickListener(this);
115 | // tvSwitchAcc.setOnClickListener(this);
116 | // cbAgreement.setOnClickListener(this);
117 | // cbAgreement.setOnCheckedChangeListener(this);
118 | }
119 |
120 | //UI主题为透明,所以Android 8.0不可设置为固定方向为横屏或者竖屏
121 | private void requestOrientation() {
122 | // activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
123 | // activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
124 | activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
125 | }
126 |
127 |
128 | private void setImmTheme() {
129 | if (Build.VERSION.SDK_INT >= 21) {
130 | // 设置沉浸式状态栏
131 | View decorView = activity.getWindow().getDecorView();
132 | int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
133 | | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
134 | decorView.setSystemUiVisibility(option);
135 | // 设置状态栏透明
136 | activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
137 | activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
138 | activity.getWindow().setStatusBarColor(Color.TRANSPARENT);
139 | if (Build.VERSION.SDK_INT >= 23) {
140 | activity.getWindow().getDecorView().setSystemUiVisibility(
141 | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
142 | }
143 | }
144 | //是否占用状态栏的位置,false为占用,true为不占用
145 | vgContainer.setFitsSystemWindows(false);
146 | //是否全屏
147 | // activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
148 | //如果不想适配P以上的水滴屏和刘海屏,可以在这里设置layoutInDisplayCutoutMode为其他的值
149 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
150 | WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
151 | lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
152 | activity.getWindow().setAttributes(lp);
153 | }
154 | }
155 |
156 |
157 | private SpannableString buildSpanString() {
158 | String operatorText = "";
159 | if (OperatorUtils.getCellularOperatorType() == 1) {
160 | operatorText = "《中国移动认证服务条款》";
161 | url = "https://wap.cmpassport.com/resources/html/contract.html";
162 | } else if (OperatorUtils.getCellularOperatorType() == 2) {
163 | operatorText = "《中国联通认证服务条款》";
164 | url = "https://ms.zzx9.cn/html/oauth/protocol2.html";
165 | } else if (OperatorUtils.getCellularOperatorType() == 3) {
166 | operatorText = "《中国电信认证服务条款》";
167 | url = "https://e.189.cn/sdk/agreement/content.do?type=main&appKey=&hidetop=true&returnUrl=";
168 | }
169 | String ageementText = "同意" + operatorText + "及《自有隐私协议》和" +
170 | "《自有服务策略》、《其他隐私协议》并授权秒验使用本机号码登录";
171 | String cusPrivacy1 = "《自有隐私协议》";
172 | String cusPrivacy2 = "《自有服务策略》";
173 | String cusPrivacy3 = "《其他隐私协议》";
174 | int baseColor = MobSDK.getContext().getResources().getColor(R.color.sec_verify_demo_text_color_common_black);
175 | int privacyColor = Color.parseColor("#FFFE7A4E");
176 | int cusPrivacyColor1 = Color.parseColor("#FF4E96FF");
177 | int cusPrivacyColor2 = Color.parseColor("#FF4E96FF");
178 | int cusPrivacyColor3 = Color.parseColor("#FFFE7A4E");
179 | SpannableString spanStr = new SpannableString(ageementText);
180 | int privacyIndex = ageementText.indexOf(operatorText);
181 | spanStr.setSpan(new ForegroundColorSpan(baseColor)
182 | , 0, ageementText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
183 | //设置文字的单击事件
184 | spanStr.setSpan(new ClickableSpan() {
185 | @Override
186 | public void updateDrawState(TextPaint ds) {
187 | ds.setUnderlineText(false);
188 | }
189 |
190 | @Override
191 | public void onClick(View widget) {
192 | gotoAgreementPage(url, "");
193 | }
194 | }, privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
195 | //设置文字的前景色
196 | spanStr.setSpan(new ForegroundColorSpan(privacyColor), privacyIndex, privacyIndex + operatorText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
197 | if (!TextUtils.isEmpty(cusPrivacy1)) {
198 | int privacy1Index = ageementText.indexOf(cusPrivacy1);
199 | //设置文字的单击事件
200 | spanStr.setSpan(new ClickableSpan() {
201 | @Override
202 | public void updateDrawState(TextPaint ds) {
203 | ds.setUnderlineText(false);
204 | }
205 |
206 | @Override
207 | public void onClick(View widget) {
208 | gotoAgreementPage("https://www.mob.com", null);
209 | // if (wrapper != null && wrapper.cusAgreement1Clicked != null){
210 | // wrapper.cusAgreement1Clicked.handle();
211 | // }
212 | }
213 | }, privacy1Index, privacy1Index + "《自有隐私协议》".length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
214 | //设置文字的前景色
215 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor1), privacy1Index, privacy1Index + cusPrivacy1.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
216 | }
217 | if (!TextUtils.isEmpty(cusPrivacy2)) {
218 | int privacy2Index = ageementText.lastIndexOf(cusPrivacy2);
219 | //设置文字的单击事件
220 | spanStr.setSpan(new ClickableSpan() {
221 | @Override
222 | public void updateDrawState(TextPaint ds) {
223 | ds.setUnderlineText(false);
224 | }
225 |
226 | @Override
227 | public void onClick(View widget) {
228 | gotoAgreementPage("https://www.baidu.com", null);
229 | }
230 | }, privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
231 | //设置文字的前景色
232 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor2), privacy2Index, privacy2Index + cusPrivacy2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
233 | }
234 | if (!TextUtils.isEmpty(cusPrivacy3)) {
235 | int privacy3Index = ageementText.lastIndexOf(cusPrivacy3);
236 | //设置文字的单击事件
237 | spanStr.setSpan(new ClickableSpan() {
238 | @Override
239 | public void updateDrawState(TextPaint ds) {
240 | ds.setUnderlineText(false);
241 | ds.linkColor = Color.parseColor("#FFFFFF");
242 | }
243 |
244 | @Override
245 | public void onClick(View widget) {
246 | gotoAgreementPage("https://www.baidu.com", null);
247 | }
248 | }, privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
249 | //设置文字的前景色
250 | spanStr.setSpan(new ForegroundColorSpan(cusPrivacyColor3), privacy3Index, privacy3Index + cusPrivacy3.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
251 | }
252 | return spanStr;
253 | }
254 |
255 | //可替换为跳转自己的webview
256 | private static void gotoAgreementPage(String agreementUrl, String title) {
257 | if (TextUtils.isEmpty(agreementUrl)) {
258 | return;
259 | }
260 | AgreementPage page = new AgreementPage();
261 | Intent i = new Intent();
262 | i.putExtra("extra_agreement_url", agreementUrl);
263 | if (!TextUtils.isEmpty(title)) {
264 | i.putExtra("privacy", title);
265 | }
266 | page.show(MobSDK.getContext(), i);
267 | }
268 | }
269 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/ui/component/PrivacyDialog.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.ui.component;
2 |
3 | import android.app.Dialog;
4 | import android.content.Context;
5 | import android.os.Bundle;
6 | import android.text.SpannableString;
7 | import android.text.method.LinkMovementMethod;
8 | import android.util.DisplayMetrics;
9 | import android.view.KeyEvent;
10 | import android.view.View;
11 | import android.view.WindowManager;
12 | import android.widget.LinearLayout;
13 | import android.widget.TextView;
14 |
15 | import com.mob.secverify.demo.ResultListener;
16 | import com.mob.tools.utils.ResHelper;
17 |
18 | public class PrivacyDialog extends Dialog implements View.OnClickListener {
19 |
20 | private static PrivacyDialog dialog;
21 | private Context context;
22 | private WindowManager windowManager;
23 | private SpannableString dialogText;
24 | private ResultListener callback;
25 |
26 | public PrivacyDialog(Context context) {
27 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
28 | this.context = context;
29 | }
30 |
31 | public PrivacyDialog(Context context, SpannableString dialogText, ResultListener callback) {
32 | super(context, ResHelper.getStyleRes(context, "Dialog_Common"));
33 | this.context = context;
34 | this.dialogText = dialogText;
35 | this.callback = callback;
36 | }
37 |
38 | public PrivacyDialog(Context context, int themeResId) {
39 | super(context, themeResId);
40 | this.context = context;
41 | }
42 |
43 | // public static void showPrivacyDialog(Context context) {
44 | // showPrivacyDialog(context, "", null);
45 | // }
46 |
47 | public static void showPrivacyDialog(Context context, SpannableString dialogText, ResultListener callback) {
48 | dismissPrivacyDialog();
49 | dialog = new PrivacyDialog(context, dialogText, callback);
50 | dialog.show();
51 | }
52 |
53 | public static void dismissPrivacyDialog() {
54 | try {
55 | if ((dialog != null) && dialog.isShowing()) {
56 | dialog.dismiss();
57 | }
58 | } catch (final IllegalArgumentException e) {
59 | // Handle or log or ignore
60 | } catch (final Exception e) {
61 | // Handle or log or ignore
62 | } finally {
63 | dialog = null;
64 | }
65 |
66 | // if (dialog != null && dialog.isShowing()) {
67 | // dialog.dismiss();
68 | // dialog = null;
69 | // }
70 | }
71 |
72 | @Override
73 | protected void onCreate(Bundle savedInstanceState) {
74 | super.onCreate(savedInstanceState);
75 | setCancelable(false);
76 | setCanceledOnTouchOutside(false);
77 | View view = getLayoutInflater().inflate(ResHelper.getLayoutRes(context, "sec_verify_demo_common_alert_dialog"), null);
78 | int width = (int) (getDeviceWidth(context) * 0.8);
79 | int height = LinearLayout.LayoutParams.WRAP_CONTENT;
80 | setContentView(view, new LinearLayout.LayoutParams(width, height));
81 |
82 | initView();
83 | }
84 |
85 | private void initView() {
86 | TextView dialogCancel = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_cancel"));
87 | TextView dialogAllow = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_allow"));
88 | TextView dialogTitle = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_title"));
89 | TextView dialogTextTv = findViewById(ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_text"));
90 | dialogTitle.setText("服务授权");
91 | dialogAllow.setText("同意");
92 | dialogCancel.setText("拒绝");
93 | dialogAllow.setOnClickListener(this);
94 | dialogCancel.setOnClickListener(this);
95 |
96 | dialogTextTv.setText(dialogText);
97 | dialogTextTv.setMovementMethod(LinkMovementMethod.getInstance());
98 | }
99 |
100 | private int getDeviceWidth(Context context) {
101 | if (windowManager == null) {
102 | windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
103 | }
104 | DisplayMetrics dm = new DisplayMetrics();
105 | windowManager.getDefaultDisplay().getMetrics(dm);
106 | return dm.widthPixels;
107 | }
108 |
109 | @Override
110 | public boolean onKeyDown(int keyCode, KeyEvent event) {//按键回调方法
111 | if (keyCode == KeyEvent.KEYCODE_BACK) {//判断按键键值做出相应操作
112 | dismissPrivacyDialog();
113 | }
114 | return super.onKeyDown(keyCode, event);//其他按键继承系统属性
115 | }
116 |
117 | @Override
118 | public void onClick(View v) {
119 | int id = v.getId();
120 | if (id == ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_cancel")) {
121 | dismissPrivacyDialog();
122 | callback.onFailure(null);
123 | } else if (id == ResHelper.getIdRes(context, "sec_verify_demo_alert_dialog_allow")) {
124 | dismissPrivacyDialog();
125 | callback.onComplete(null);
126 | }
127 | }
128 | }
129 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/util/Const.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.util;
2 |
3 | public class Const {
4 | public static final String SMS_TEMP_CODE = "1319972";
5 | public static final String EXTRAS_DEMO_LOGIN_RESULT = "extras_demo_login_result";
6 | }
7 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/util/NetWorkUtil.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.util;
2 | import android.annotation.TargetApi;
3 | import android.content.Context;
4 | import android.net.ConnectivityManager;
5 | import android.net.Network;
6 | import android.net.NetworkCapabilities;
7 | import android.net.NetworkInfo;
8 | import android.net.NetworkRequest;
9 | import android.os.Build;
10 | import android.telephony.TelephonyManager;
11 | import android.util.Log;
12 |
13 | import java.io.BufferedReader;
14 | import java.io.IOException;
15 | import java.io.InputStreamReader;
16 | import java.net.URL;
17 | import java.net.URLConnection;
18 | import java.util.concurrent.Callable;
19 | import java.util.concurrent.FutureTask;
20 |
21 | public class NetWorkUtil {
22 |
23 | public static final int NET_ETHNET = 0;
24 | public static final int NET_CELLULAR = 1;
25 | public static int CURRENT_TAG = NET_ETHNET;
26 |
27 |
28 | public static void getNetState(Context context, int tag) {
29 | CURRENT_TAG = tag;
30 | Log.e("cdl", "========000=========");
31 | if (Build.VERSION.SDK_INT >= 21) {
32 | Log.e("cdl", "======111===========");
33 | final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
34 | NetworkRequest.Builder builder = new NetworkRequest.Builder();
35 | Log.e("cdl", "=======222==========");
36 | builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
37 | // builder.addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET);
38 | // builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
39 | if (tag == NET_ETHNET) {
40 | builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
41 | } else if (tag == NET_CELLULAR) {
42 | builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);
43 | }
44 | NetworkRequest request = builder.build();
45 | Log.e("cdl", "=======333==========");
46 | ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {
47 |
48 | @TargetApi(Build.VERSION_CODES.M)
49 | @Override
50 | public void onAvailable(Network network) {
51 | super.onAvailable(network);
52 | Log.e("cdl", "==========已根据功能和传输类型找到合适的网络=======");
53 | if (Build.VERSION.SDK_INT >= 23) {
54 | Log.e("cdl", "=====44444==23==========");
55 | connectivityManager.bindProcessToNetwork(network);
56 | } else {
57 | Log.e("cdl", "===444444====<<<<23==========");
58 | ConnectivityManager.setProcessDefaultNetwork(network);
59 | }
60 | // get("https://www.baidu.com");
61 | Log.e("cdl", "=========4444========");
62 | connectivityManager.unregisterNetworkCallback(this);
63 | }
64 | };
65 | connectivityManager.requestNetwork(request, callback);
66 | }
67 | }
68 |
69 | public static String get(final String url) {
70 | Log.e("cdl", "=========5555555==========");
71 | final StringBuilder sb = new StringBuilder();
72 | FutureTask task = new FutureTask(new Callable() {
73 | @Override
74 | public String call() throws Exception {
75 | BufferedReader br = null;
76 | InputStreamReader isr = null;
77 | URLConnection conn;
78 | try {
79 | URL geturl = new URL(url);
80 | conn = geturl.openConnection();//创建连接
81 | conn.connect();//get连接
82 | isr = new InputStreamReader(conn.getInputStream());//输入流
83 | br = new BufferedReader(isr);
84 | String line = null;
85 | while ((line = br.readLine()) != null) {
86 | sb.append(line);//获取输入流数据
87 | }
88 | Log.e("cdl", "==" + sb.toString());
89 | } catch (Exception e) {
90 | Log.e("cdl", "=====6666666==============");
91 | e.printStackTrace();
92 | } finally {//执行流的关闭
93 | if (br != null) {
94 | try {
95 | if (br != null) {
96 | br.close();
97 | }
98 | if (isr != null) {
99 | isr.close();
100 | }
101 | } catch (IOException e) {
102 | e.printStackTrace();
103 | }
104 | }
105 | }
106 | return sb.toString();
107 | }
108 | });
109 | new Thread(task).start();
110 | String s = null;
111 | try {
112 | s = task.get();//异步获取返回值
113 | } catch (Exception e) {
114 | e.printStackTrace();
115 | }
116 | return s;
117 | }
118 |
119 |
120 | public static NetworkInfo getNetworkState(Context context) {
121 |
122 | ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
123 | if (null == connManager)
124 | return null;
125 | NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
126 | if (activeNetInfo == null || !activeNetInfo.isAvailable()) {
127 | return null;
128 | }
129 | return activeNetInfo;
130 | }
131 |
132 |
133 | public static String GetNetworkType(Context context) {
134 | String strNetworkType = "";
135 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
136 | NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
137 | if (networkInfo != null && networkInfo.isConnected()) {
138 | if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
139 | strNetworkType = "WIFI";
140 | } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
141 | String _strSubTypeName = networkInfo.getSubtypeName();
142 |
143 | Log.e("cocos2d-x", "Network getSubtypeName : " + _strSubTypeName);
144 |
145 | // TD-SCDMA networkType is 17
146 | int networkType = networkInfo.getSubtype();
147 | switch (networkType) {
148 | case TelephonyManager.NETWORK_TYPE_GPRS:
149 | case TelephonyManager.NETWORK_TYPE_EDGE:
150 | case TelephonyManager.NETWORK_TYPE_CDMA:
151 | case TelephonyManager.NETWORK_TYPE_1xRTT:
152 | case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
153 | strNetworkType = "2G";
154 | break;
155 | case TelephonyManager.NETWORK_TYPE_UMTS:
156 | case TelephonyManager.NETWORK_TYPE_EVDO_0:
157 | case TelephonyManager.NETWORK_TYPE_EVDO_A:
158 | case TelephonyManager.NETWORK_TYPE_HSDPA:
159 | case TelephonyManager.NETWORK_TYPE_HSUPA:
160 | case TelephonyManager.NETWORK_TYPE_HSPA:
161 | case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
162 | case TelephonyManager.NETWORK_TYPE_EHRPD: //api<11 : replace by 12
163 | case TelephonyManager.NETWORK_TYPE_HSPAP: //api<13 : replace by 15
164 | strNetworkType = "3G";
165 | break;
166 | case TelephonyManager.NETWORK_TYPE_LTE: //api<11 : replace by 13
167 | strNetworkType = "4G";
168 | break;
169 | default:
170 | // http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
171 | if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
172 | strNetworkType = "3G";
173 | } else {
174 | strNetworkType = _strSubTypeName;
175 | }
176 |
177 | break;
178 | }
179 | Log.e("cocos2d-x", "Network getSubtype : " + Integer.valueOf(networkType).toString());
180 | }
181 | }
182 | Log.e("cocos2d-x", "Network Type : " + strNetworkType);
183 | return strNetworkType;
184 | }
185 |
186 |
187 | }
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/util/OperatorUtils.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.util;
2 |
3 | import android.content.Context;
4 | import android.net.ConnectivityManager;
5 | import android.telephony.TelephonyManager;
6 |
7 | import com.mob.MobSDK;
8 |
9 | import java.lang.reflect.Method;
10 |
11 | public class OperatorUtils {
12 |
13 | /**
14 | * 获取设备蜂窝网络运营商
15 | *
16 | * @return ["中国电信CTCC":3]["中国联通CUCC:2]["中国移动CMCC":1]["other":0]["无sim卡":-1]["数据流量未打开":-2]
17 | */
18 | public static int getCellularOperatorType() {
19 | int opeType = -1;
20 | // No sim
21 | if (!hasSim()) {
22 | return opeType;
23 | }
24 | // Mobile data disabled
25 | if (!isMobileDataEnabled(MobSDK.getContext())) {
26 | opeType = -2;
27 | return opeType;
28 | }
29 | // Check cellular operator
30 | TelephonyManager tm = (TelephonyManager) MobSDK.getContext().getSystemService(Context.TELEPHONY_SERVICE);
31 | String operator = tm.getSimOperator();
32 | // 中国联通
33 | if ("46001".equals(operator) || "46006".equals(operator) || "46009".equals(operator)) {
34 | opeType = 2;
35 | // 中国移动
36 | } else if ("46000".equals(operator) || "46002".equals(operator) || "46004".equals(operator) || "46007".equals(operator)) {
37 | opeType = 1;
38 | // 中国电信
39 | } else if ("46003".equals(operator) || "46005".equals(operator) || "46011".equals(operator)) {
40 | opeType = 3;
41 | } else {
42 | opeType = 0;
43 | }
44 | return opeType;
45 | }
46 |
47 | public static boolean hasSim() {
48 | TelephonyManager tm = (TelephonyManager) MobSDK.getContext().getSystemService(Context.TELEPHONY_SERVICE);
49 | if (tm.getSimState() == TelephonyManager.SIM_STATE_READY) {
50 | return true;
51 | } else {
52 | return false;
53 | }
54 | }
55 |
56 | /**
57 | * 判断数据流量开关是否打开
58 | *
59 | * @param context
60 | * @return
61 | */
62 | public static boolean isMobileDataEnabled(Context context) {
63 | try {
64 | Method method = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
65 | method.setAccessible(true);
66 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
67 | return (Boolean) method.invoke(connectivityManager);
68 | } catch (Throwable t) {
69 | return false;
70 | }
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/SecVerify-Demo/src/com/mob/secverify/demo/util/PrivacyDialogUtils.java:
--------------------------------------------------------------------------------
1 | package com.mob.secverify.demo.util;
2 |
3 | import android.app.Activity;
4 | import android.app.AlertDialog;
5 | import android.content.Context;
6 | import android.content.DialogInterface;
7 | import android.content.SharedPreferences;
8 | import android.net.http.SslError;
9 | import android.os.Build;
10 | import android.util.DisplayMetrics;
11 | import android.view.View;
12 | import android.webkit.SslErrorHandler;
13 | import android.webkit.WebSettings;
14 | import android.webkit.WebView;
15 | import android.webkit.WebViewClient;
16 | import android.widget.LinearLayout;
17 |
18 | import com.mob.MobSDK;
19 |
20 | public class PrivacyDialogUtils {
21 | public static final String KEY_PRIVACY = "privacy";
22 | private SharedPreferences sharedPreferences;
23 | private AlertDialog downloadDialog;
24 | private DialogInterface.OnDismissListener dismissListener;
25 |
26 | public void setDismissListener(DialogInterface.OnDismissListener dismissListener) {
27 | this.dismissListener = dismissListener;
28 | }
29 |
30 | public boolean showPrivacyDialogIfNeed(Activity activity, String sdkName) {
31 | if (downloadDialog != null && downloadDialog.isShowing()) {
32 | return true;
33 | }
34 | sharedPreferences = activity.getSharedPreferences("privacy", Context.MODE_PRIVATE);
35 | if (sharedPreferences.getBoolean(KEY_PRIVACY, false)) {
36 | return false;
37 | }
38 | DisplayMetrics displayMetrics = new DisplayMetrics();
39 | activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
40 | int screenWidth = displayMetrics.widthPixels;
41 | LinearLayout linearLayout = new LinearLayout(activity);
42 | linearLayout.setOrientation(LinearLayout.VERTICAL);
43 | WebView webView = new WebView(activity);
44 | int width = screenWidth - 2 * 30;
45 | LinearLayout.LayoutParams webViewParams = new LinearLayout.LayoutParams(width, (int) (1.1f * width));
46 | webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
47 | WebSettings webSettings = webView.getSettings();
48 | webSettings.setJavaScriptEnabled(true);
49 | webSettings.setBuiltInZoomControls(false);
50 | webSettings.setDomStorageEnabled(true);
51 | webSettings.setAllowFileAccess(false);
52 | webSettings.setSavePassword(false);
53 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
54 | webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
55 | }
56 | webView.setWebViewClient(new WebViewClient() {
57 | @Override
58 | public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
59 | try {
60 | handler.proceed();
61 | } catch (Throwable e) {
62 | }
63 | }
64 | });
65 | linearLayout.addView(webView, webViewParams);
66 | try {
67 | AlertDialog.Builder b = new AlertDialog.Builder(activity, android.R.style.Theme_Material_Light_Dialog);
68 | b.setTitle(sdkName + " 隐私政策");
69 | b.setCancelable(false);
70 | b.setView(linearLayout);
71 |
72 | b.setPositiveButton("同意", new DialogInterface.OnClickListener() {
73 | @Override
74 | public void onClick(DialogInterface dialogInterface, int i) {
75 | MobSDK.submitPolicyGrantResult(true);
76 | sharedPreferences.edit().putBoolean(KEY_PRIVACY, true).apply();
77 | }
78 | });
79 | b.setNegativeButton("取消", new DialogInterface.OnClickListener() {
80 | @Override
81 | public void onClick(DialogInterface dialog, int which) {
82 | }
83 | });
84 | webView.loadUrl("file:///android_asset/www/privacySec.html");
85 | downloadDialog = b.create();
86 | if(dismissListener != null) {
87 | downloadDialog.setOnDismissListener(dismissListener);
88 | }
89 | downloadDialog.show();
90 | } catch (Throwable e) {
91 | }
92 | return true;
93 | }
94 |
95 | }
96 |
--------------------------------------------------------------------------------