android studio 集成文档
android studio集成方法
1.创建一个android工程
2.通过拷贝添加arr文件到libs
image.png3.在app文件的build.gradle配置如下
android{
...
defaultConfig{
...
ndk {
abiFilters "armeabi", "armeabi-v7a", "x86"
//输出指定三种abi体系结构下的so库
}
...
}
...
repositories {
flatDir {
dirs 'libs'
// aar目录
}
}
...
dependencies{
...
implementation(name: "enterplorer_library", ext: "aar")
implementation(name: "xwalk_core_library", ext: "aar")
...
}
}
4.Manifest权限
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
5.项目中的使用
-
使用前请先配置 app/src/main/assets/config.metadata文件
image.png - 内容如下
{"companyName": "you company name", "managerServer": "you manager server address", "managerProxy": ""}
以上详情,请与PM联系,并索要相关信息
5.1初始化SDK
- 在application中初始化SDK
XCloudSDKManager.getInstance().init(this);
- 注意事项:
- 初始化SDK的过程中,需要获取本机信息,android SDK 23版本或以上,需要权限.请修改目标版本至22,否侧可能初始化失败.
targetSdkVersion 22
5.2使用
在使用界面,执行如下代码,进行SDK验证
XCloudSDKManager.getInstance().authRequest(this, new Callback() {
@Override
public void success() {
mLoadingDialog.dismiss();
initTabFragment("目标url");
}
@Override
public void error(String errorMsg) {
mLoadingDialog.dismiss();
Toast.makeText(BrowserActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
});
- 如上,initTabFragment("url")方法如下
private void initTabFragment(String url) {
TabFragment.Builder builder = new TabFragment.Builder();
// ProxyChangeListener.setProxyConfig("192.168.2.18", 8888, null, new String[]{"oa.yunshipei.com"});
/**
* 加载{@link #url}时设置cookie实现单点登录
*/
ArrayList<CookieModel> cookieModelList = new ArrayList<>();
String cookie = CookieManager.getInstance().getCookie(url);cookieModelList.add(new CookieModel(url, cookie));
builder.setCookies(cookieModelList);
/**
* 加载{@link #url}时设置cookie实现单点登录
* builder.setCookies()
*
* //给每个加载的url加参数作为单点登录
* builder.setUrlTokenSSO()
*
* //设置proxy,401,403认证信息;在页面需要做认证时可以在此配置认证信息,在页面需要认证时将自动根据配置信息自动认证将不再弹出认证对话框
* builder.setHttpAuthorizations()
*
* //设置全局运行时版本
* builder.setGlobalRuntime()
*/
//设置webView加载的Url
builder.setUrl(url);
//设置默认是否支持双webView。具体是否支持请询问适配开发工程师。
builder.setDefault2WebView(false);
//设置页面水印
builder.setWaterMark(new WaterMarkConfig.Builder().setShowDateTime(true).setWtmTexts(Arrays.asList("云适配", "适配SDK")).build());
//设置页面字体大小
builder.setTextZoom(100);
//文档预览 使用永中文档转换服务器进行文档预览
FilePreviewConfig.Builder filePreviewConfigBuilder = new FilePreviewConfig.Builder();
//设置永中文档转换服务器地址
filePreviewConfigBuilder.setDocConvertServer("http://139.217.22.35:8080");
HashMap<String, String> map = new HashMap<>();
map.put("rtf", "0");
map.put("eio", "0");
map.put("uof", "0");
map.put("uos", "0");
map.put("xml", "0");
map.put("txt", "0");
filePreviewConfigBuilder.setDocTypes(map);
/**
//设置是否自行处理文档转换后的url(默认状态为false,使用SDK内部默认的文档在线处理逻辑)
filePreviewConfigBuilder.setExternalPreview(false);
//在访问永中转换服务器时如果需要通过代理访问,请设置代理服务信息
filePreviewConfigBuilder.setFilePreviewServerProxy("xxx.xxx.xxx.xxxx", 8787);
**/
builder.setFilePreview(filePreviewConfigBuilder.build());
/**
* TabFragment是用来显示webView窗口的重要组件。tabFragment 必须在{@link XCloudSDKManager#authRequest(Context, Callback)}
* 请求成功回调到{@link Callback#success()}后才可以创建对象并attach到View中。
*/
mTabFragment = builder.build();
ArrayList<HttpAuthModel> httpAuthModels = new ArrayList<>();
httpAuthModels.add(new HttpAuthModel("host","name","psd"));
builder.setHttpAuthorizations(httpAuthModels);
//webView 注入native method
JavascriptExample javascriptExample = new JavascriptExample(this, mTabFragment);
mTabFragment.addJavascriptInterface(javascriptExample, "APIExample");
getSupportFragmentManager().beginTransaction().replace(R.id.fl_browser_tab, mTabFragment, mTabFragment.getClass().getName()).commit();
/**
* webView(crosswalk)文件下载监听设置
*/
// mTabFragment.setEnterDownloadListener(new EnterDownloadListener() {
// @Override
// public void onDownload(String fromUrl, XDownloadModel xDownloadModel) {
// /**
// * 实现具体的下载逻辑...
// */
// }
// });
/**
* 日志上传
*/
YspLogUtils.uploadLog("小明", new Callback() {
@Override
public void success() {
}
@Override
public void error(String errorMsg) {
}
});
//sdk扩展功能
setextralEvent(mTabFragment);
mTabFragment.setOnFragmentInteractionListener(new TabFragment.OnFragmentInteractionListener() {
@Override
public void backTop() {
finish();
}
@Override
public void webViewUrlChanged(String s) {
}
@Override
public void kingGridFile(String s) {
}
private int retry = 3;
@Override
public boolean onReceivedHttpAuthRequest(XWalkView xWalkView, XWalkHttpAuthHandler xWalkHttpAuthHandler, final String host, String s1) {
String u = YspSharePreUtil.getInstance(BrowserActivity.this).getLocalStorage("YSP_" + host + "_username");
String p = YspSharePreUtil.getInstance(BrowserActivity.this).getLocalStorage("YSP_" + host + "_password");
if (retry-- > 0) {
xWalkHttpAuthHandler.proceed(u, p);
return true;
}
final XWalkHttpAuthHandler haHandler = xWalkHttpAuthHandler;
Context context = xWalkView.getContext();
LinearLayout layout = new LinearLayout(context);
final EditText userNameEditText = new EditText(context);
final EditText passwordEditText = new EditText(context);
layout.setOrientation(LinearLayout.VERTICAL);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layout.setPaddingRelative(10, 0, 10, 20);
} else {
layout.setPadding(10, 0, 10, 20);
}
userNameEditText.setHint(R.string.http_auth_user_name);
passwordEditText.setHint(R.string.http_auth_password);
passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
layout.addView(userNameEditText);
layout.addView(passwordEditText);
AlertDialog.Builder httpAuthDialog = new AlertDialog.Builder(BrowserActivity.this);
httpAuthDialog.setTitle(R.string.http_auth_title)
.setView(layout)
.setCancelable(false)
.setPositiveButton(R.string.http_auth_log_in,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
haHandler.proceed(userName, password);
YspSharePreUtil.getInstance(BrowserActivity.this).setLocalStorage("YSP_" + host + "_username", userName);
YspSharePreUtil.getInstance(BrowserActivity.this).setLocalStorage("YSP_" + host + "_password", password);
dialog.dismiss();
}
}).setNegativeButton(android.R.string.cancel, null)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
haHandler.cancel();
}
}).create().show();
return true;
}
@Override
public void tabProgressChanged(int i) {
}
@Override
public void backPreWebView(boolean b) {
}
@Override
public boolean shouldHandleNoMatcherUrlFromOpenWindow(String s) {
return false;
}
@Override
public boolean shouldInterceptWebViewShouldOverrideUrlLoadingMethod(XWalkView xWalkView, String s) {
return false;
}
// 密码代填
@Override
public AutoLoginModel getAutoLoginModel(String s) {
if (s.contains("http://oa.yunshipei.com/")) {
return new AutoLoginModel("//*[@id=\"userId\"]", "//*[@id=\"userPwd\"]", "//*[@id=\"tableheight\"]/tbody/tr[3]/td/table/tbody/tr/td[2]/table/tbody/tr[1]/td[3]/img", "test1", "123456");
}
return null;
}
/**
* 永中文档在线预览开发者自行处理。
* @param s 文档转换后的地址;如:http://192.xxxx.xxx.xxx/prexxxx.html
*/
@Override
public void filePreviewConvertResult(String s) {
/**
* 如果在设置永中文档转换服务器转化后将url暴露出来供开发者自己处理。
* filePreviewConfigBuilder.setExternalPreview(true);
* 此时需要开发者自己处理相关逻辑
*/
}
/**
* 自定义WebView(crosswalk)适配页面加载的loading样式
* @param s 加载适配页面传递过来的提示信息;
* @return true标示使用自定义的loading;false标示使用sdk默认loading
*/
@Override
public boolean showAdapterLoading(String s) {
if(webLoadingDialog != null) {
webLoadingDialog.show();
//使用自定义loading样式时,返回true
return true;
}
//使用默认loading则返回false
return false;
}
/**
* 关闭自定义适配页面加载loading
* 此方法必须和{@link #showAdapterLoading(String)}同时实现
* @return true标示关闭自定义的loading;false标示关闭sdk默认loading
*/
@Override
public boolean hideAdapterLoading() {
if(webLoadingDialog != null && webLoadingDialog.isShowing()) {
webLoadingDialog.cancel();
//关闭自定义loading样式时,返回true
return true;
}
//关闭默认的loading,直接返回false
return false;
}
@Override
public String getSecurityGatewayKey() {
return null;
}
});
}
5.3 全部代码如下
package com.example.app;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.model.JavascriptExample;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yunshipei.core.common.Callback;
import com.yunshipei.core.common.PageLocationListener;
import com.yunshipei.core.common.QRCodeDecoderListener;
import com.yunshipei.core.common.bridge.inter.JsCallback;
import com.yunshipei.core.manager.XCloudSDKManager;
import com.yunshipei.core.model.AutoLoginModel;
import com.yunshipei.core.model.CookieModel;
import com.yunshipei.core.model.FilePreviewConfig;
import com.yunshipei.core.model.HttpAuthModel;
import com.yunshipei.core.model.WaterMarkConfig;
import com.yunshipei.core.ui.TabFragment;
import com.yunshipei.core.utils.YspLogUtils;
import com.yunshipei.core.utils.YspSharePreUtil;
import org.json.JSONException;
import org.json.JSONObject;
import org.xwalk.core.XWalkHttpAuthHandler;
import org.xwalk.core.XWalkView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
public class BrowserActivity extends AppCompatActivity {
private static final String TAG = BrowserActivity.class.getSimpleName();
public static final String EXTRA_URL = "adapter_url";
public static final String EXTRA_TITLE = "adapter_title";
public static final String EXTRA_IDS = "adapters_ids";
private TabFragment mTabFragment;
private LoadingDialog webLoadingDialog = null;
private AMapLocationClient aMapLocationClient = null; //高德定位
private AMapLocationClientOption option = null;
private JsCallback scanQRCodeJsCallback = null; //js二维码扫描结果回调
@BindView(R.id.tv_title)
protected TextView tvTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_browser);
ButterKnife.bind(this);
tvTitle.setText(getIntent().getStringExtra(EXTRA_TITLE));
final String url = getIntent().getStringExtra(EXTRA_URL);
final LoadingDialog mLoadingDialog = new LoadingDialog(this);
mLoadingDialog.setTitle("加载中,请稍候...");
mLoadingDialog.show();
if (savedInstanceState != null) {
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentByTag(TabFragment.class.getName());
if (fragment != null) {
fm.beginTransaction().remove(fragment).commit();
fm.executePendingTransactions();
}
}
// XCloudSDKManager.getInstance().shouldReAuthRequest(); 有重新登录需求的时候需要开启
XCloudSDKManager.getInstance().authRequest(this, new Callback() {
@Override
public void success() {
mLoadingDialog.dismiss();
initTabFragment("目标url");
}
@Override
public void error(String errorMsg) {
mLoadingDialog.dismiss();
Toast.makeText(BrowserActivity.this, errorMsg, Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onResumeFragments() {
super.onResumeFragments();
if (webLoadingDialog == null) {
webLoadingDialog = new LoadingDialog(this);
webLoadingDialog.setTitle("页面加载中...");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//js二维码扫描结果回传给webpage
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null && !TextUtils.isEmpty(intentResult.getContents())) {
if (scanQRCodeJsCallback != null)
scanQRCodeJsCallback.onCallback(intentResult.getContents());
}
super.onActivityResult(requestCode, resultCode, data);
}
private void initTabFragment(String url) {
TabFragment.Builder builder = new TabFragment.Builder();
// ProxyChangeListener.setProxyConfig("192.168.2.18", 8888, null, new String[]{"oa.yunshipei.com"});
/**
* 加载{@link #url}时设置cookie实现单点登录
*/
ArrayList<CookieModel> cookieModelList = new ArrayList<>();
String cookie = CookieManager.getInstance().getCookie(url);cookieModelList.add(new CookieModel(url, cookie));
builder.setCookies(cookieModelList);
/**
* 加载{@link #url}时设置cookie实现单点登录
* builder.setCookies()
*
* //给每个加载的url加参数作为单点登录
* builder.setUrlTokenSSO()
*
* //设置proxy,401,403认证信息;在页面需要做认证时可以在此配置认证信息,在页面需要认证时将自动根据配置信息自动认证将不再弹出认证对话框
* builder.setHttpAuthorizations()
*
* //设置全局运行时版本
* builder.setGlobalRuntime()
*/
//设置webView加载的Url
builder.setUrl(url);
//设置默认是否支持双webView。具体是否支持请询问适配开发工程师。
builder.setDefault2WebView(false);
//设置页面水印
builder.setWaterMark(new WaterMarkConfig.Builder().setShowDateTime(true).setWtmTexts(Arrays.asList("云适配", "适配SDK")).build());
//设置页面字体大小
builder.setTextZoom(100);
//文档预览 使用永中文档转换服务器进行文档预览
FilePreviewConfig.Builder filePreviewConfigBuilder = new FilePreviewConfig.Builder();
//设置永中文档转换服务器地址
filePreviewConfigBuilder.setDocConvertServer("http://139.217.22.35:8080");
HashMap<String, String> map = new HashMap<>();
map.put("rtf", "0");
map.put("eio", "0");
map.put("uof", "0");
map.put("uos", "0");
map.put("xml", "0");
map.put("txt", "0");
filePreviewConfigBuilder.setDocTypes(map);
/**
//设置是否自行处理文档转换后的url(默认状态为false,使用SDK内部默认的文档在线处理逻辑)
filePreviewConfigBuilder.setExternalPreview(false);
//在访问永中转换服务器时如果需要通过代理访问,请设置代理服务信息
filePreviewConfigBuilder.setFilePreviewServerProxy("xxx.xxx.xxx.xxxx", 8787);
**/
builder.setFilePreview(filePreviewConfigBuilder.build());
/**
* TabFragment是用来显示webView窗口的重要组件。tabFragment 必须在{@link XCloudSDKManager#authRequest(Context, Callback)}
* 请求成功回调到{@link Callback#success()}后才可以创建对象并attach到View中。
*/
mTabFragment = builder.build();
ArrayList<HttpAuthModel> httpAuthModels = new ArrayList<>();
httpAuthModels.add(new HttpAuthModel("host","name","psd"));
builder.setHttpAuthorizations(httpAuthModels);
//webView 注入native method
JavascriptExample javascriptExample = new JavascriptExample(this, mTabFragment);
mTabFragment.addJavascriptInterface(javascriptExample, "APIExample");
getSupportFragmentManager().beginTransaction().replace(R.id.fl_browser_tab, mTabFragment, mTabFragment.getClass().getName()).commit();
/**
* webView(crosswalk)文件下载监听设置
*/
// mTabFragment.setEnterDownloadListener(new EnterDownloadListener() {
// @Override
// public void onDownload(String fromUrl, XDownloadModel xDownloadModel) {
// /**
// * 实现具体的下载逻辑...
// */
// }
// });
/**
* 日志上传
*/
YspLogUtils.uploadLog("小明", new Callback() {
@Override
public void success() {
}
@Override
public void error(String errorMsg) {
}
});
//sdk扩展功能
setextralEvent(mTabFragment);
mTabFragment.setOnFragmentInteractionListener(new TabFragment.OnFragmentInteractionListener() {
@Override
public void backTop() {
finish();
}
@Override
public void webViewUrlChanged(String s) {
}
@Override
public void kingGridFile(String s) {
}
private int retry = 3;
@Override
public boolean onReceivedHttpAuthRequest(XWalkView xWalkView, XWalkHttpAuthHandler xWalkHttpAuthHandler, final String host, String s1) {
String u = YspSharePreUtil.getInstance(BrowserActivity.this).getLocalStorage("YSP_" + host + "_username");
String p = YspSharePreUtil.getInstance(BrowserActivity.this).getLocalStorage("YSP_" + host + "_password");
if (retry-- > 0) {
xWalkHttpAuthHandler.proceed(u, p);
return true;
}
final XWalkHttpAuthHandler haHandler = xWalkHttpAuthHandler;
Context context = xWalkView.getContext();
LinearLayout layout = new LinearLayout(context);
final EditText userNameEditText = new EditText(context);
final EditText passwordEditText = new EditText(context);
layout.setOrientation(LinearLayout.VERTICAL);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
layout.setPaddingRelative(10, 0, 10, 20);
} else {
layout.setPadding(10, 0, 10, 20);
}
userNameEditText.setHint(R.string.http_auth_user_name);
passwordEditText.setHint(R.string.http_auth_password);
passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
layout.addView(userNameEditText);
layout.addView(passwordEditText);
AlertDialog.Builder httpAuthDialog = new AlertDialog.Builder(BrowserActivity.this);
httpAuthDialog.setTitle(R.string.http_auth_title)
.setView(layout)
.setCancelable(false)
.setPositiveButton(R.string.http_auth_log_in,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
String userName = userNameEditText.getText().toString();
String password = passwordEditText.getText().toString();
haHandler.proceed(userName, password);
YspSharePreUtil.getInstance(BrowserActivity.this).setLocalStorage("YSP_" + host + "_username", userName);
YspSharePreUtil.getInstance(BrowserActivity.this).setLocalStorage("YSP_" + host + "_password", password);
dialog.dismiss();
}
}).setNegativeButton(android.R.string.cancel, null)
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
haHandler.cancel();
}
}).create().show();
return true;
}
@Override
public void tabProgressChanged(int i) {
}
@Override
public void backPreWebView(boolean b) {
}
@Override
public boolean shouldHandleNoMatcherUrlFromOpenWindow(String s) {
return false;
}
@Override
public boolean shouldInterceptWebViewShouldOverrideUrlLoadingMethod(XWalkView xWalkView, String s) {
return false;
}
// 密码代填
@Override
public AutoLoginModel getAutoLoginModel(String s) {
if (s.contains("http://oa.yunshipei.com/")) {
return new AutoLoginModel("//*[@id=\"userId\"]", "//*[@id=\"userPwd\"]", "//*[@id=\"tableheight\"]/tbody/tr[3]/td/table/tbody/tr/td[2]/table/tbody/tr[1]/td[3]/img", "test1", "123456");
}
return null;
}
/**
* 永中文档在线预览开发者自行处理。
* @param s 文档转换后的地址;如:http://192.xxxx.xxx.xxx/prexxxx.html
*/
@Override
public void filePreviewConvertResult(String s) {
/**
* 如果在设置永中文档转换服务器转化后将url暴露出来供开发者自己处理。
* filePreviewConfigBuilder.setExternalPreview(true);
* 此时需要开发者自己处理相关逻辑
*/
}
/**
* 自定义WebView(crosswalk)适配页面加载的loading样式
* @param s 加载适配页面传递过来的提示信息;
* @return true标示使用自定义的loading;false标示使用sdk默认loading
*/
@Override
public boolean showAdapterLoading(String s) {
if(webLoadingDialog != null) {
webLoadingDialog.show();
//使用自定义loading样式时,返回true
return true;
}
//使用默认loading则返回false
return false;
}
/**
* 关闭自定义适配页面加载loading
* 此方法必须和{@link #showAdapterLoading(String)}同时实现
* @return true标示关闭自定义的loading;false标示关闭sdk默认loading
*/
@Override
public boolean hideAdapterLoading() {
if(webLoadingDialog != null && webLoadingDialog.isShowing()) {
webLoadingDialog.cancel();
//关闭自定义loading样式时,返回true
return true;
}
//关闭默认的loading,直接返回false
return false;
}
@Override
public String getSecurityGatewayKey() {
return null;
}
});
}
@OnClick({R.id.iv_close, R.id.iv_refresh})
protected void onClickEvent(View view) {
switch (view.getId()) {
case R.id.iv_close:
finish();
break;
case R.id.iv_refresh:
if (mTabFragment != null) {
mTabFragment.refresh();
}
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mTabFragment != null) {
//适配页面的返回逻辑
mTabFragment.onTabBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTabFragment != null) {
mTabFragment.release();
}
}
/**
* ----------------------------------------------
* 这部分功能是sdk的相关扩展功能,如果不需要无需关注
* 如果需要使用相关方法可以根据具体需求具体实现
* 一下实现仅为接口调用方法展示
*
* @param tabFragment
*/
private void setextralEvent(TabFragment tabFragment) {
if (tabFragment == null) {
Log.d(TAG, "tabFragment 不能为 null !");
return;
}
/**
* 设置网页调取二维码扫描事件的监听
*/
tabFragment.setQrCodeDecoderListener(new QRCodeDecoderListener() {
@Override
public void scanQRCode(JsCallback jsCallback) {
scanQRCodeJsCallback = jsCallback;
new IntentIntegrator(BrowserActivity.this).initiateScan();
}
});
/**
* 设置网页获取位置信息的监听
*/
tabFragment.setPageLocationListener(pageLocationListener);
}
private YSPPageLocationListener pageLocationListener = new YSPPageLocationListener();
class YSPPageLocationListener implements PageLocationListener {
private JsCallback jsCallback;
@Override
public void locationBegin(final JsCallback jsCallback) {
this.jsCallback = jsCallback;
if (ActivityCompat.checkSelfPermission(BrowserActivity.this, "android.permission.ACCESS_COARSE_LOCATION")
!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(getApplicationContext(),"没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
// 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
ActivityCompat.requestPermissions(BrowserActivity.this,new String[]{"android.permission.ACCESS_COARSE_LOCATION"}, 100);
}else{
System.out.println("定位开始!!!!!!!!!!!!!!!!");
doLocation();
}
}
public void doLocation() {
if (aMapLocationClient == null)
aMapLocationClient = new AMapLocationClient(BrowserActivity.this);
if (option == null)
option = getDefaultOption();
option.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
aMapLocationClient.setLocationListener(new AMapLocationListener() {
@Override
public void onLocationChanged(AMapLocation aMapLocation) {
//定位成功
if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("longitude", aMapLocation.getLongitude());
jsonObject.put("latitude", aMapLocation.getLatitude());
jsonObject.put("address", aMapLocation.getAddress());
} catch (JSONException e) {
e.printStackTrace();
}
jsCallback.onCallback(jsonObject.toString());
} else {
//定位失败
StringBuffer sb = new StringBuffer();
sb.append("定位失败" + "\n");
sb.append("错误码:" + aMapLocation.getErrorCode() + "\n");
sb.append("错误信息:" + aMapLocation.getErrorInfo() + "\n");
sb.append("错误描述:" + aMapLocation.getLocationDetail() + "\n");
jsCallback.onCallback(sb.toString() + "");
}
stopLocation();
destroyLocation();
}
});
aMapLocationClient.setLocationOption(option);
aMapLocationClient.startLocation();
}
};
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
// requestCode即所声明的权限获取码,在checkSelfPermission时传入
case 100:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 获取到权限,作相应处理(调用定位SDK应当确保相关权限均被授权,否则可能引起定位失败)
pageLocationListener.doLocation();
} else {
// 没有获取到权限,做特殊处理
Toast.makeText(getApplicationContext(), "获取位置权限失败,请手动开启", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
/**
* 定位配置
*
* @return
*/
private AMapLocationClientOption getDefaultOption() {
AMapLocationClientOption mOption = new AMapLocationClientOption();
mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选,设置定位模式,可选的模式有高精度、仅设备、仅网络。默认为高精度模式
mOption.setGpsFirst(false);//可选,设置是否gps优先,只在高精度模式下有效。默认关闭
mOption.setHttpTimeOut(30000);//可选,设置网络请求超时时间。默认为30秒。在仅设备模式下无效
mOption.setInterval(2000);//可选,设置定位间隔。默认为2秒
mOption.setNeedAddress(true);//可选,设置是否返回逆地理地址信息。默认是true
mOption.setOnceLocation(false);//可选,设置是否单次定位。默认是false
mOption.setOnceLocationLatest(false);//可选,设置是否等待wifi刷新,默认为false.如果设置为true,会自动变为单次定位,持续定位时不要使用
AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选, 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
mOption.setSensorEnable(false);//可选,设置是否使用传感器。默认是false
mOption.setWifiScan(true); //可选,设置是否开启wifi扫描。默认为true,如果设置为false会同时停止主动刷新,停止以后完全依赖于系统刷新,定位位置可能存在误差
mOption.setLocationCacheEnable(true); //可选,设置是否使用缓存定位,默认为true
return mOption;
}
/**
* 停止定位
*/
private void stopLocation() {
if (aMapLocationClient != null)
aMapLocationClient.stopLocation();
}
/**
* 销毁定位
*/
private void destroyLocation() {
if (aMapLocationClient != null)
aMapLocationClient.onDestroy();
aMapLocationClient = null;
}
}
- 请注意相机/相册等回调
- 请参考书写物理返回键拦截方法
网友评论