Commit 962bcd79 authored by JingChao's avatar JingChao

'init'

parents
File added
# cordova-plugin-barcode 二维码扫描Cordova插件
This plugin implements barcode scanner on Cordova 4.0
## Supported Cordova Platforms
* Android 4.0.0 or above
* iOS 7.0.0 or above
## Usage
cordova plugin add https://github.com/MrLiZ/HuiLianYi-barCode.git
## JS
``` js
com.hls.plugins.barcode.startScan({
message:{
barTitle:'标题栏文案',
explainFlag: false,//是否显示说明按钮
title:'扫码上方描述',
tipScan:'扫码下方描述',
inputFlag: true,//是否显示输入按钮
lightFlag: true,//是否显示照亮按钮
tipInput:'输入单号提示',
tipLightOn:'打开照亮提示',
tipLightOff:'关闭照亮提示',
tipLoading:'调接口的过程中的提示',
tipNetworkError:'网络错误时的提示',
tipOffline:'没有打开web时的提示',
openButton:'我已打开按钮文字',
footerFirst:'底部提示第一行,可空',
footerSecond:'底部提示第二行,可空',
delayTime:'1000'
},
operationType:'REVIEW',
requests:[
{
url:'www.huilianyi.com',
method:'POST',
headers:{
Authorization:'Bearer xxxxx',
Content-Type:'xxxx'
},
config: {
timeout: 10000 (单位是毫秒)
},
data:{
code:'xxxx-xxxx',
operate:'xxxx'
}
},
...
]
},function(success){
alert(JSON.stringify(success));
}, function(error){
alert(JSON.stringify(error));
});
```
This diff is collapsed.
#!/usr/bin/env node
module.exports = function (context) {
var path = context.requireCordovaModule('path'),
fs = context.requireCordovaModule('fs'),
shell = context.requireCordovaModule('shelljs'),
projectRoot = context.opts.projectRoot,
ConfigParser = context.requireCordovaModule('cordova-common').ConfigParser,
config = new ConfigParser(path.join(context.opts.projectRoot, "config.xml")),
packageName = config.android_packageName() || config.packageName();
if (!packageName) {
console.error("Package name could not be found!");
return ;
}
if (context.opts.cordova.platforms.indexOf("android") === -1) {
console.info("Android platform has not been added.");
return ;
}
var targetDir = path.join(projectRoot, "platforms", "android", "src", "com", "hls", "plugins", "barcode");
var targetFiles = ["CaptureActivity.java", "decode/DecodeHandler.java", "decode/CaptureActivityHandler.java","activity/DialogToast.java","activity/NetWorkErrorActivity.java","activity/UnOpenWebActivity.java"];
if (['after_plugin_add', 'after_plugin_install', 'after_platform_add'].indexOf(context.hook) === -1) {
try {
if(context.opts.plugins && context.opts.plugins.indexOf(context.opts.plugin.id) !== -1){
targetFiles.forEach(function(file){
var targetFile = path.join(targetDir, file);
fs.unlinkSync(targetFile);
});
}
} catch (err) {}
} else {
targetFiles.forEach(function(file){
var targetFile = path.join(targetDir, file);
fs.readFile(targetFile, {encoding: 'utf-8'}, function (err, data) {
if (err) {
throw err;
}
data = data.replace(/^import __ANDROID_PACKAGE__.R;/m, 'import ' + packageName + '.R;');
fs.writeFileSync(targetFile, data);
});
});
}
};
\ No newline at end of file
File added
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/qrcode_ligth_on_normal" />
<item android:state_pressed="true" android:drawable="@drawable/qrcode_ligth_on_pressed" />
<item android:state_focused="true" android:drawable="@drawable/qrcode_ligth_on_pressed" />
<item android:drawable="@drawable/qrcode_ligth_on_normal" />
</selector>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#91918d" />
<corners android:radius="25dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#5591918d" />
<corners android:radius="25dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#0092DA" />
<corners android:radius="30dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#0c72a4" />
<corners android:radius="30dp" />
</shape>
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#ff404040" />
<corners
android:bottomLeftRadius="50dp"
android:bottomRightRadius="50dp"
android:topLeftRadius="50dp"
android:topRightRadius="50dp" />
</shape>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/corner_input" />
<item android:state_pressed="true" android:drawable="@drawable/corner_input_pressed" />
<item android:state_focused="true" android:drawable="@drawable/corner_input_pressed" />
<item android:drawable="@drawable/corner_input" />
</selector>
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@drawable/corner_textview" />
<item android:state_pressed="true" android:drawable="@drawable/corner_textview_pressed" />
<item android:state_focused="true" android:drawable="@drawable/corner_textview_pressed" />
<item android:drawable="@drawable/corner_textview" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="44dp"
>
<ImageView
android:id="@+id/imgBtnBack"
android:layout_width="44dp"
android:layout_height="44dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#00000000"
android:clickable="true"
android:src="@drawable/btn_back" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="22sp"
android:layout_centerInParent="true"
android:text="扫一扫"
/>
</RelativeLayout>
<ImageView
android:id="@+id/img_network_error"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/network_error"
android:layout_centerHorizontal="true"
android:layout_marginTop="130dp"
/>
<TextView
android:id="@+id/txt_tipNetworkError"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/white"
android:text="当前网络不可用,请检查网络设置"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:layout_below="@+id/img_network_error"
/>
<TextView
android:id="@+id/txt_tip1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:textColor="@android:color/white"
android:text="123"
android:textSize="15sp" />
<TextView
android:id="@+id/txt_tip2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:textColor="@android:color/white"
android:text="456"
android:textSize="15sp" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/capture_containter"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:id="@+id/capture_preview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ImageView
android:id="@+id/top_mask"
android:layout_width="match_parent"
android:layout_height="110dp"
android:layout_alignParentTop="true"
android:background="#EE010713" />
<RelativeLayout
android:id="@+id/capture_crop_layout"
android:layout_width="220dp"
android:layout_height="220dp"
android:layout_below="@id/top_mask"
android:layout_centerHorizontal="true"
android:background="@drawable/capture">
<ImageView
android:id="@+id/capture_scan_line"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_margin="5dp"
android:src="@drawable/kakalib_scan_ray" />
</RelativeLayout>
<ImageView
android:id="@+id/bottom_mask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_below="@+id/capture_crop_layout"
android:background="#EE010713" />
<ImageView
android:id="@+id/left_mask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_mask"
android:layout_alignParentLeft="true"
android:layout_below="@id/top_mask"
android:layout_toLeftOf="@id/capture_crop_layout"
android:background="#EE010713" />
<ImageView
android:id="@+id/right_mask"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/bottom_mask"
android:layout_alignParentRight="true"
android:layout_below="@id/top_mask"
android:layout_toRightOf="@id/capture_crop_layout"
android:background="#EE010713" />
<TextView
android:id="@+id/txtScanTip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/capture_crop_layout"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="请扫描单据上的二维码"
android:textColor="#808080"
android:textSize="14dp" />
<LinearLayout
android:layout_width="240dp"
android:layout_height="90dp"
android:layout_below="@id/capture_crop_layout"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:orientation="horizontal">
<LinearLayout
android:id="@+id/lyt_input"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:clickable="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:layout_width="54dp"
android:layout_height="54dp"
android:src="@drawable/input" />
<TextView
android:id="@+id/txt_input"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_marginTop="4dp"
android:ellipsize="end"
android:gravity="center"
android:singleLine="true"
android:text="手工输入"
android:textColor="#FFFFFF"
android:textSize="14dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/lyt_light"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="@+id/img_light"
android:layout_width="54dp"
android:layout_height="54dp"
android:src="@drawable/light" />
<TextView
android:id="@+id/txt_light"
android:layout_width="110dp"
android:layout_height="30dp"
android:layout_marginTop="4dp"
android:ellipsize="end"
android:gravity="center"
android:singleLine="true"
android:text="打开照亮"
android:textColor="#FFFFFF"
android:textSize="14dp" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="@+id/txt_tip1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:textColor="#808080"
android:textSize="14dp" />
<TextView
android:id="@+id/txt_tip2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:textColor="#808080"
android:textSize="14dp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="44dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true">
<ImageView
android:id="@+id/imgBtnBack"
android:layout_width="44dp"
android:layout_height="44dp"
android:background="#00000000"
android:paddingBottom="12dp"
android:paddingTop="12dp"
android:src="@drawable/btn_back" />
<TextView
android:id="@+id/txt_title"
android:layout_width="100dp"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:gravity="center"
android:singleLine="false"
android:text="扫 一 扫"
android:textColor="@android:color/white"
android:textSize="18dp" />
<RelativeLayout
android:id="@+id/rel_tip"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_marginRight="12dp"
android:layout_alignParentRight="true">
<ImageView
android:id="@+id/img_tip"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/tip" />
</RelativeLayout>
</RelativeLayout>
<TextView
android:id="@+id/tv_type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/top_mask"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:gravity="center"
android:text="锁定审核驳回"
android:textColor="#808080"
android:textSize="14dp" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="44dp"
>
<ImageView
android:id="@+id/imgBtnBack"
android:layout_width="44dp"
android:layout_height="44dp"
android:paddingTop="8dp"
android:paddingBottom="8dp"
android:background="#00000000"
android:src="@drawable/btn_back" />
<TextView
android:id="@+id/scanTitile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="22sp"
android:layout_centerInParent="true"
android:text="扫一扫"
/>
</RelativeLayout>
<ImageView
android:id="@+id/img_pc"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:src="@drawable/pc"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
/>
<TextView
android:id="@+id/txt_tipOffLine"
android:layout_width="176dp"
android:gravity="center"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textColor="@android:color/white"
android:text="请按照页面下方提示先打开汇联易网站"
android:layout_centerHorizontal="true"
android:layout_marginTop="30dp"
android:layout_below="@+id/img_pc"
/>
<TextView
android:id ="@+id/txt_open"
android:layout_width="180dp"
android:layout_height="60dp"
android:gravity="center"
android:text="我已打开"
android:clickable="true"
android:textColor="@android:color/white"
android:textSize="22sp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/txt_tipOffLine"
android:layout_marginTop="30dp"
android:background="@drawable/selector_open_web"
/>
<TextView
android:id="@+id/txt_tip1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="38dp"
android:textColor="@android:color/white"
android:text="123"
android:textSize="15sp" />
<TextView
android:id="@+id/txt_tip2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:textColor="@android:color/white"
android:text="456"
android:textSize="15sp" />
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@drawable/progress_custom_bg"
android:paddingRight="25dp"
android:paddingLeft="25dp"
android:paddingTop="15dp"
android:paddingBottom="15dp"
>
<TextView
android:id = "@+id/txt_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:textSize="22sp"
android:text="正在处理"
android:textColor="#FFFFFF"
/>
<View
android:layout_width="1dp"
android:layout_height="24dp"
android:background="#FFFFFF"
android:layout_gravity="center_vertical"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
/>
<ImageView
android:id = "@+id/txt_cancel"
android:layout_width="24dp"
android:layout_height="24dp"
android:gravity="center"
android:src="@drawable/cancel"
android:textColor="#FFFFFF"
android:fontFamily="monospace"
android:layout_gravity="center_vertical"
/>
</LinearLayout>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 自定义Dialog -->
<style name="Custom_Progress" parent="@android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
</style>
</resources>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="auto_focus" type="id"/>
<item name="decode" type="id"/>
<item name="decode_failed" type="id"/>
<item name="decode_succeeded" type="id"/>
<item name="restart_preview" type="id"/>
<item name="quit" type="id"/>
</resources>
\ No newline at end of file
package com.hls.plugins.barcode;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PermissionHelper;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.util.Log;
import android.widget.Toast;
import com.hls.plugins.barcode.Util.Util;
import com.hls.plugins.barcode.activity.NetWorkErrorActivity;
import com.hls.plugins.barcode.activity.UnOpenWebActivity;
import com.hls.plugins.barcode.bean.ArgsBean;
import com.hls.plugins.barcode.bean.ArgsBiz;
/**
* Created by Administrator on 2016/3/16.
*/
public class BarcodePlugin extends CordovaPlugin {
public static CallbackContext cbContext = null;
private static final String LOG_TAG = "BarcodeScanner";
private String[] permissions = {Manifest.permission.CAMERA};
private JSONArray args;
@Override
public boolean execute(String action, final JSONArray args, CallbackContext callbackContext) throws JSONException {
cbContext = callbackContext;
if (action.equals("startScan")) {
this.args =args;
if (!hasPermission()) {
requestPermissions(0);
} else {
scan(args);
}
} else if (action.equals("hasPermission")) {
if (!hasPermission()) {
requestPermissions(0);
}
cbContext.success(hasPermission() + "");
return true;
}
return true;
}
/**
* Starts an intent to scan and decode a barcode.
*/
public void scan(final JSONArray args) {
try {
ArgsBiz argsBiz = new ArgsBiz();
ArgsBean argsBean ;
argsBean = argsBiz.getArgsBeanByJSONObject(args.getJSONObject(0));
if (!Util.isNetworkAvailable(cordova.getActivity())) {
Intent intent = new Intent(cordova.getActivity(), NetWorkErrorActivity.class);
intent.putExtra("ARGS",argsBean);
this.cordova.getActivity().startActivity(intent);
return;
}
if(argsBean!=null) {
Intent intentScan = new Intent(this.cordova.getActivity().getApplicationContext(), CaptureActivity.class);
intentScan.putExtra("ARGS", argsBean);
this.cordova.getActivity().startActivity(intentScan);
}else{
cbContext.success("请检查参数");
}
} catch (JSONException e) {
e.printStackTrace();
cbContext.success("请检查参数");
}
}
/**
* check application's permissions
*/
public boolean hasPermission() {
for (String p : permissions) {
if (!PermissionHelper.hasPermission(this, p)) {
return false;
} else {
boolean isCanUse = true;
Camera mCamera = null;
try {
mCamera = Camera.open();
Camera.Parameters mParameters = mCamera.getParameters(); // 针对魅族手机
mCamera.setParameters(mParameters);
} catch (Exception e) {
isCanUse = false;
}
if (mCamera != null) {
try {
mCamera.release();
} catch (Exception e) {
e.printStackTrace();
return isCanUse;
}
}
return isCanUse;
}
}
return true;
}
/**
* We override this so that we can access the permissions variable, which no
* longer exists in the parent class, since we can't initialize it reliably
* in the constructor!
*
* @param requestCode The code to get request action
*/
public void requestPermissions(int requestCode) {
PermissionHelper.requestPermissions(this, requestCode, permissions);
}
/**
* processes the result of permission request
*
* @param requestCode The code to get request action
* @param permissions The collection of permissions
* @param grantResults The result of grant
*/
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults)
throws JSONException {
PluginResult result;
// Toast.makeText(this.cordova.getActivity().getApplicationContext(), grantResults.toString(), 3).show();
for (int r : grantResults) {
if (r == PackageManager.PERMISSION_DENIED) {
Log.d(LOG_TAG, "Permission Denied!");
result = new PluginResult(PluginResult.Status.ILLEGAL_ACCESS_EXCEPTION);
cbContext.sendPluginResult(result);
return;
}
}
if(args!=null){
scan(args);
}
}
}
This diff is collapsed.
package com.hls.plugins.barcode;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.hls.plugins.barcode.Util.Util;
import com.hls.plugins.barcode.bean.ArgsBean;
import com.hls.plugins.barcode.bean.CodeInfoBean;
import com.hls.plugins.barcode.http.HttpManager;
import com.hls.plugins.barcode.http.ResultCallback;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by panx on 2017/3/16.
*/
public class CapturePresenter {
private ICaptureActivity iCaptureActivity;
private Context context;
private final static String TAG = "CapturePresenter";
private ArgsBean argsBean;
public CapturePresenter(ICaptureActivity iCaptureActivity,Context context) {
this.iCaptureActivity = iCaptureActivity;
this.context = context;
}
/**
* 向后端发送验证请求
* @param argsBean
* @param code
*/
public void toValidation(ArgsBean argsBean,final String code) {
this.argsBean = makeArguments(argsBean, code);
if (argsBean == null) return;
iCaptureActivity.showProgressDialog(true);
HttpManager.post(argsBean.getHttpInfos().get(0), new ResultCallback<String>() {
//条码处理失败
@Override
public void onError(Exception e, String error) {
iCaptureActivity.showProgressDialog(false);
iCaptureActivity.ToastCenter(error);
if(!Util.isNetworkAvailable(context)){
iCaptureActivity.goNetworkErrorPage();
}else{
iCaptureActivity.reStartActivity();
}
}
//条码处理成功
@Override
public void onResponse(String response, String extra) {
iCaptureActivity.showProgressDialog(false);
CodeInfoBean codeInfoBean = doCodeResult(response);
if(codeInfoBean!=null) {
doResultBiz(codeInfoBean, response,code);
}else{
iCaptureActivity.ToastCenter(HttpManager.NETWORK_ERROR);
}
}
});
}
/**
* 处理网络请求参数
* @param argsBean
* @param code
* @return
*/
private ArgsBean makeArguments(ArgsBean argsBean, String code) {
String data = argsBean.getHttpInfos().get(0).getData();
try {
JSONObject object = new JSONObject(data);
object.put("code", code);
object.put("operate", argsBean.getOperateMethod());
argsBean.getHttpInfos().get(0).setData(object.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "wrog arguments for http data");
return null;
}
return argsBean;
}
/**
* 处理扫码结果
*/
private CodeInfoBean doCodeResult(String response) {
Log.e(TAG, response);
try {
JSONObject object = new JSONObject(response);
CodeInfoBean codeInfoBean = new CodeInfoBean();
codeInfoBean.setCode(object.getString(CodeInfoBean.CODE));
codeInfoBean.setMsg(object.getString(CodeInfoBean.MSG));
codeInfoBean.setOnline(object.optString(CodeInfoBean.ONLINE));
codeInfoBean.setExpenseReport(object.optString(CodeInfoBean.EXPENSE_REPORT));
return codeInfoBean;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
/**
* 根据扫码结果做出相应的反馈
*/
private void doResultBiz(CodeInfoBean codeInfoBean, String response,String code) {
String operateMethod = argsBean.getOperateMethod();
if (operateMethod != null && operateMethod.equals(ArgsBean.REVIEW)) {
doReviewBiz(codeInfoBean, response);
} else if (operateMethod != null && operateMethod.equals(ArgsBean.AUDIT_PASS)) {
doAuditPassBiz(codeInfoBean, response);
} else if (operateMethod != null && operateMethod.equals(ArgsBean.AUDIT)) {
doAuditBiz(codeInfoBean, response, code);
}else if (operateMethod != null && operateMethod.equals(ArgsBean.BACK)) {
doBackBiz(codeInfoBean, response, code);
}
else if (operateMethod != null && operateMethod.equals(ArgsBean.RECEIVE)) {
doReceiveBiz(codeInfoBean,response);
} else if (operateMethod != null && operateMethod.equals(ArgsBean.INVOICE)){
doInvoiceBiz(codeInfoBean,response,code);
}
}
/**
* 处理REVIEW的业务逻辑
*/
private void doReviewBiz(CodeInfoBean codeInfoBean, String response) {
if (codeInfoBean.getCode() != null && codeInfoBean.getCode().equals(CodeInfoBean.SUCCESS)) {
//审核成功
JSONObject object = new JSONObject();
try {
object.put("type", ArgsBean.REVIEW);
JSONObject responseObject = new JSONObject(response);
object.put("message", responseObject);
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.scanFinish(object);
} catch (JSONException e) {
e.printStackTrace();
}
} else if (codeInfoBean.getOnline() == null || !codeInfoBean.getOnline().equals("1")) {
iCaptureActivity.goUnOpenWebPage();//未打开中控页面
} else {
//审核没有成功
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
/**
* 处理ADDIT_PASS逻辑
*/
private void doAuditPassBiz(CodeInfoBean codeInfoBean, String response) {
if(codeInfoBean.getCode()!=null && codeInfoBean.getCode().equals(CodeInfoBean.SUCCESS)){
try {
JSONObject object = new JSONObject(codeInfoBean.getExpenseReport());
String applicantName = object.getString("applicantName");
String businessCode = object.getString("businessCode");
String msg = String.format("%s\n%s\n%s",applicantName,businessCode,codeInfoBean.getMsg());
iCaptureActivity.ToastCenter(msg);
} catch (JSONException e) {
e.printStackTrace();
}
iCaptureActivity.reStartActivity();
}else{
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
/**
* 处理AUDIT逻辑
*/
private void doAuditBiz(CodeInfoBean codeInfoBean, String response,String code) {
if(codeInfoBean.getCode()!=null && codeInfoBean.getCode().equals(CodeInfoBean.SUCCESS)){
JSONObject object = new JSONObject();
try {
object.put("type","AUDIT");
JSONObject msgObject = new JSONObject();
msgObject.put("code",code);
JSONObject responseObject = new JSONObject(response);
msgObject.put("response",responseObject);
object.put("message",msgObject);
} catch (JSONException e) {
e.printStackTrace();
}
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.scanFinish(object);
}else{
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
/**
* 处理BACK逻辑
*/
private void doBackBiz(CodeInfoBean codeInfoBean, String response,String code) {
if(codeInfoBean.getCode()!=null && codeInfoBean.getCode().equals(CodeInfoBean.SUCCESS)){
JSONObject object = new JSONObject();
try {
object.put("type","BACK");
JSONObject msgObject = new JSONObject();
msgObject.put("code",code);
JSONObject responseObject = new JSONObject(response);
msgObject.put("response",responseObject);
object.put("message",msgObject);
} catch (JSONException e) {
e.printStackTrace();
}
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.scanFinish(object);
}else{
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
/**
* 处理INVOICE逻辑
*/
private void doInvoiceBiz(CodeInfoBean codeInfoBean, String response,String code) {
if(codeInfoBean.getCode()!=null && codeInfoBean.getCode().equals(CodeInfoBean.SUCCESS)){
JSONObject object = new JSONObject();
try {
object.put("type",ArgsBean.INVOICE);
JSONObject msgObject = new JSONObject();
msgObject.put("code",code);
JSONObject responseObject = new JSONObject(response);
msgObject.put("response",responseObject);
object.put("message",msgObject);
} catch (JSONException e) {
e.printStackTrace();
}
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.scanFinish(object);
}else{
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
/**
* 处理RECEIVE逻辑
*/
private void doReceiveBiz(CodeInfoBean codeInfoBean, String response) {
iCaptureActivity.ToastCenter(codeInfoBean.getMsg());
iCaptureActivity.reStartActivity();
}
}
package com.hls.plugins.barcode;
import org.json.JSONObject;
/**
* Created by panx on 2017/3/16.
*/
public interface ICaptureActivity {
void goNetworkErrorPage();
void goUnOpenWebPage();
void reStartActivity();
void scanFinish(JSONObject result);
void ToastCenter(String msg);
void showProgressDialog(boolean flag);
}
package com.hls.plugins.barcode.Util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Created by panx on 2017/3/15.
*/
public class Util {
public static boolean isNetworkAvailable(Context context){
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isAvailable()){
return true;
}
return false;
}
}
package com.zbar.lib;
public class ZbarManager {
static {
System.loadLibrary("zbar");
}
public native String decode(byte[] data, int width, int height, boolean isCrop, int x, int y, int cwidth, int cheight);
}
package com.hls.plugins.barcode.activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import __ANDROID_PACKAGE__.R;
/**
* Created by panx on 2017/3/17.
*/
public class DialogToast extends Dialog {
public DialogToast(Context context) {
super(context);
}
protected DialogToast(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, cancelable, cancelListener);
}
public DialogToast(Context context, int themeResId) {
super(context, themeResId);
}
public static class Builder {
private Context context;
private String msg;
private OnClickListener onClickListener;
public Builder(Context context) {
this.context = context;
}
public Builder setMsg(String msg){
this.msg = msg;
return this;
}
public Builder setOnClickListener(OnClickListener onClickListener){
this.onClickListener = onClickListener;
return this;
}
public DialogToast create(){
LayoutInflater inflater = LayoutInflater.from(context);
final DialogToast dialogToast = new DialogToast(context,R.style.Custom_Progress);
View view = inflater.inflate(R.layout.dialog_cancel_layout,null);
dialogToast.setContentView(view);
TextView txtMsg =(TextView) view.findViewById(R.id.txt_msg);
ImageView imgCancel = (ImageView) view.findViewById(R.id.txt_cancel);
if(msg!=null){
txtMsg.setText(msg);
}
imgCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickListener.onClick(dialogToast, DialogInterface.BUTTON_NEGATIVE);
}
});
WindowManager.LayoutParams lp = dialogToast.getWindow().getAttributes();
// 设置背景层透明度
lp.dimAmount = 0.0f;
dialogToast.getWindow().setAttributes(lp);
dialogToast.setCancelable(false);
return dialogToast;
}
}
}
package com.hls.plugins.barcode.activity;
/**
* Created by panx on 2017/3/16.
*/
public interface IUnOpenWebActivity {
void stillUnOpen();
void hasOpen();
void ToastCenter(String msg);
void showProgressDialog(boolean flag);
void goNetworkErrorPage();
}
package com.hls.plugins.barcode.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import __ANDROID_PACKAGE__.R;
import com.hls.plugins.barcode.bean.ArgsBean;
/**
* Created by panx on 2017/3/15.
*/
public class NetWorkErrorActivity extends Activity implements View.OnClickListener{
private ArgsBean argsBean;
private TextView txtTipNetworkError;
private TextView txtTip1;
private TextView txtTip2;
private ImageView imgBtnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_network_error);
readIntent();
initView();
initListener();
initData();
}
private void readIntent(){
argsBean = getIntent().getParcelableExtra("ARGS");
}
private void initView(){
txtTipNetworkError = (TextView)findViewById(R.id.txt_tipNetworkError);
txtTip1 = (TextView)findViewById(R.id.txt_tip1);
txtTip2 = (TextView)findViewById(R.id.txt_tip2);
imgBtnBack = (ImageView) findViewById(R.id.imgBtnBack);
}
private void initListener(){
imgBtnBack.setOnClickListener(this);
}
private void initData(){
txtTipNetworkError.setText(argsBean.getPageInfoBean().getTipNetworkError());
txtTip1.setText(argsBean.getPageInfoBean().getFooterFirst());
txtTip2.setText(argsBean.getPageInfoBean().getFooterSecond());
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.imgBtnBack:{
onBackPressed();
break;
}default:
break;
}
}
}
package com.hls.plugins.barcode.activity;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import __ANDROID_PACKAGE__.R;
import com.hls.plugins.barcode.Util.Util;
import com.hls.plugins.barcode.bean.ArgsBean;
/**
* Created by panx on 2017/3/15.
*/
public class UnOpenWebActivity extends Activity implements View.OnClickListener,IUnOpenWebActivity {
private ImageView imgBtnBack;
private TextView txtTipOffline;
private TextView txtOpen;
private TextView txtTip1;
private TextView txtTip2;
private TextView scanTitile;
private ArgsBean argsBean;
private DialogToast dialogToast;
private UnOpenWebActivityPresenter unOpenWebActivityPresenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_unopen_web);
unOpenWebActivityPresenter = new UnOpenWebActivityPresenter(this,this);
readIntent();
initView();
initData();
initListener();
}
private void readIntent() {
argsBean = getIntent().getParcelableExtra("ARGS");
}
private void initView() {
txtTipOffline = (TextView) findViewById(R.id.txt_tipOffLine);
txtOpen = (TextView) findViewById(R.id.txt_open);
txtTip1 = (TextView) findViewById(R.id.txt_tip1);
txtTip2 = (TextView) findViewById(R.id.txt_tip2);
imgBtnBack = (ImageView) findViewById(R.id.imgBtnBack);
scanTitile=(TextView) findViewById(R.id.scanTitile);
}
private void initData() {
txtTipOffline.setText(argsBean.getPageInfoBean().getTipOffline());
txtOpen.setText(argsBean.getPageInfoBean().getOpenButton());
txtTip1.setText(argsBean.getPageInfoBean().getFooterFirst());
txtTip2.setText(argsBean.getPageInfoBean().getFooterSecond());
scanTitile.setText(argsBean.getPageInfoBean().getBarTitle());
}
private void initListener(){
txtOpen.setOnClickListener(this);
imgBtnBack.setOnClickListener(this);
}
@Override
public void onClick(View view) {
int id = view.getId();
switch (id){
case R.id.imgBtnBack:
onBackPressed();
break;
case R.id.txt_open:
unOpenWebActivityPresenter.toValidation(argsBean);
break;
default:
break;
}
}
/**
* 扔未打开
*/
@Override
public void stillUnOpen(){
ToastCenter(argsBean.getPageInfoBean().getTipOffline());
}
@Override
public void hasOpen(){
onBackPressed();
}
@Override
public void ToastCenter(String msg) {
Toast toast = Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
@Override
public void showProgressDialog(boolean isShow) {
if(dialogToast == null&&isShow){
DialogToast.Builder builder = new DialogToast.Builder(this);
dialogToast = builder.setMsg(argsBean.getPageInfoBean().getTipLoading())
.setOnClickListener(new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
}).create();
dialogToast.show();
}else if(isShow){
dialogToast.show();
}else if(!isShow&&dialogToast!=null){
dialogToast.dismiss();
}
}
@Override
public void goNetworkErrorPage() {
Intent intent = new Intent(this, NetWorkErrorActivity.class);
intent.putExtra("ARGS",argsBean);
startActivity(intent);
}
}
package com.hls.plugins.barcode.activity;
import android.content.Context;
import com.hls.plugins.barcode.Util.Util;
import com.hls.plugins.barcode.bean.ArgsBean;
import com.hls.plugins.barcode.http.HttpManager;
import com.hls.plugins.barcode.http.ResultCallback;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by panx on 2017/3/16.
*/
public class UnOpenWebActivityPresenter {
private IUnOpenWebActivity iUnOpenWebActivity;
private Context context;
public UnOpenWebActivityPresenter(IUnOpenWebActivity iUnOpenWebActivity,Context context) {
this.iUnOpenWebActivity = iUnOpenWebActivity;
this.context = context;
}
public void toValidation(ArgsBean argsBean){
iUnOpenWebActivity.showProgressDialog(true);
HttpManager.get(argsBean.getHttpInfos().get(1), new ResultCallback<String>() {
@Override
public void onError(Exception e, String error) {
iUnOpenWebActivity.showProgressDialog(false);
if(!Util.isNetworkAvailable(context)){
iUnOpenWebActivity.goNetworkErrorPage();
}else{
iUnOpenWebActivity.ToastCenter(error);
}
}
@Override
public void onResponse(String response, String result) {
iUnOpenWebActivity.showProgressDialog(false);
doResultBiz(response);
}
});
}
private void doResultBiz(String response){
try {
JSONObject object = new JSONObject(response);
int online = object.getInt("online");
if(online!=1){
iUnOpenWebActivity.stillUnOpen();
}else{
iUnOpenWebActivity.hasOpen();
}
} catch (JSONException e) {
iUnOpenWebActivity.ToastCenter(HttpManager.NETWORK_ERROR);
e.printStackTrace();
}
}
}
package com.hls.plugins.barcode.bean;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
/**
* Created by panx on 2017/3/15.
*/
public class ArgsBean implements Parcelable {
public final static String REVIEW = "REVIEW";
public final static String AUDIT = "AUDIT";
public final static String BACK = "BACK";
public final static String AUDIT_PASS = "AUDIT_PASS";
public final static String RECEIVE ="RECEIVE";
public final static String SCAN ="SCAN";
public final static String INVOICE = "INVOICE";
private PageInfoBean pageInfoBean;
private String operateMethod;
private ArrayList<HttpInfoBean> httpInfos;
public ArgsBean() {
}
protected ArgsBean(Parcel in) {
pageInfoBean = in.readParcelable(PageInfoBean.class.getClassLoader());
operateMethod = in.readString();
httpInfos = in.createTypedArrayList(HttpInfoBean.CREATOR);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeParcelable(pageInfoBean, flags);
dest.writeString(operateMethod);
dest.writeTypedList(httpInfos);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<ArgsBean> CREATOR = new Creator<ArgsBean>() {
@Override
public ArgsBean createFromParcel(Parcel in) {
return new ArgsBean(in);
}
@Override
public ArgsBean[] newArray(int size) {
return new ArgsBean[size];
}
};
public PageInfoBean getPageInfoBean() {
return pageInfoBean;
}
public void setPageInfoBean(PageInfoBean pageInfoBean) {
this.pageInfoBean = pageInfoBean;
}
public String getOperateMethod() {
return operateMethod;
}
public void setOperateMethod(String operateMethod) {
this.operateMethod = operateMethod;
}
public ArrayList<HttpInfoBean> getHttpInfos() {
return httpInfos;
}
public void setHttpInfos(ArrayList<HttpInfoBean> httpInfos) {
this.httpInfos = httpInfos;
}
}
package com.hls.plugins.barcode.bean;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by panx on 2017/3/15.
*/
public class ArgsBiz {
private final static String TAG = "ArgsBiz";
public ArgsBean getArgsBeanByJSONObject(JSONObject object) {
ArgsBean argsBean = new ArgsBean();
try {
JSONObject pageObject = object.getJSONObject("message");
argsBean.setPageInfoBean(getPageInfoBeanByJsonObject(pageObject));
String operateMethod = object.optString("operationType", "");
argsBean.setOperateMethod(operateMethod);
JSONArray httpArray = object.optJSONArray("requests");
argsBean.setHttpInfos(getHttpInfosByJsonArray(httpArray));
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return argsBean;
}
private PageInfoBean getPageInfoBeanByJsonObject(JSONObject object) {
PageInfoBean pageInfoBean = new PageInfoBean();
pageInfoBean.setTitle(object.optString("title", ""));
pageInfoBean.setTipScan(object.optString("tipScan", ""));
pageInfoBean.setTipInput(object.optString("tipInput", ""));
pageInfoBean.setTipLoading(object.optString("tipLoading", ""));
pageInfoBean.setTipNetworkError(object.optString("tipNetworkError", ""));
pageInfoBean.setTipOffline(object.optString("tipOffline", ""));
pageInfoBean.setOpenButton(object.optString("openButton", ""));
pageInfoBean.setFooterFirst(object.optString("footerFirst", ""));
pageInfoBean.setFooterSecond(object.optString("footerSecond", ""));
pageInfoBean.setBarTitle(object.optString("barTitle", ""));
pageInfoBean.setExplainFlag(object.optBoolean("explainFlag", false));
pageInfoBean.setInputFlag(object.optBoolean("inputFlag", true));
pageInfoBean.setLightFlag(object.optBoolean("lightFlag", true));
pageInfoBean.setTipLightOff(object.optString("tipLightOff", ""));
pageInfoBean.setTipLightOn(object.optString("tipLightOn", ""));
pageInfoBean.setDelayTime(object.optLong("delayTime"));
return pageInfoBean;
}
private ArrayList<HttpInfoBean> getHttpInfosByJsonArray(JSONArray array) {
if (array == null) return null;
ArrayList<HttpInfoBean> httpInfos = new ArrayList<HttpInfoBean>();
try {
for (int i = 0; i < array.length(); i++) {
HttpInfoBean httpInfoBean = getHttpInfoBeanByJsonObject(array.getJSONObject(i));
httpInfos.add(httpInfoBean);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "wrong arguments http infos");
return null;
}
return httpInfos;
}
private HttpInfoBean getHttpInfoBeanByJsonObject(JSONObject object) {
HttpInfoBean httpInfoBean = new HttpInfoBean();
HttpInfoBean.Config config = new HttpInfoBean.Config();
HttpInfoBean.Headers headers = new HttpInfoBean.Headers();
try {
httpInfoBean.setUrl(object.getString("url"));
httpInfoBean.setMethod(object.getString("method"));
JSONObject headerObject = object.getJSONObject("headers");
JSONObject configObject = object.getJSONObject("config");
JSONObject dataObject = object.optJSONObject("data");
if (dataObject == null) {
dataObject = new JSONObject();
}
headers.setAuthorization(headerObject.getString("Authorization"));
headers.setContentType(headerObject.getString("Content-Type"));
config.setTimeout(configObject.getInt("timeout"));
httpInfoBean.setConfig(config);
httpInfoBean.setData(dataObject.toString());
httpInfoBean.setHeaders(headers);
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "wrong arguments http info");
return null;
}
return httpInfoBean;
}
}
package com.hls.plugins.barcode.bean;
/**
* Created by panx on 2017/3/9.
*/
public class CodeInfoBean {
public final static String SUCCESS = "0000";
public final static String CODE = "code";
public final static String MSG = "msg";
public final static String ONLINE = "online";
public final static String EXPENSE_REPORT = "expenseReport";
private String code;
private String msg;
private String online;
private String expenseReport;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getOnline() {
return online;
}
public void setOnline(String online) {
this.online = online;
}
public String getExpenseReport() {
return expenseReport;
}
public void setExpenseReport(String expenseReport) {
this.expenseReport = expenseReport;
}
}
package com.hls.plugins.barcode.bean;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by panx on 2017/3/15.
*/
public class HttpInfoBean implements Parcelable{
private String url;
private String method;
private Headers headers;
private String data;
private Config config;
public HttpInfoBean() {
}
/**
* 请求头
*/
public static class Headers implements Parcelable {
private String authorization;
private String contentType;
public Headers() {
}
protected Headers(Parcel in) {
authorization = in.readString();
contentType = in.readString();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(authorization);
dest.writeString(contentType);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Headers> CREATOR = new Creator<Headers>() {
@Override
public Headers createFromParcel(Parcel in) {
return new Headers(in);
}
@Override
public Headers[] newArray(int size) {
return new Headers[size];
}
};
public String getAuthorization() {
return authorization;
}
public void setAuthorization(String authorization) {
this.authorization = authorization;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
/**
* 配置
*/
public static class Config implements Parcelable {
private int timeout;
public Config() {
}
protected Config(Parcel in) {
timeout = in.readInt();
}
public static final Creator<Config> CREATOR = new Creator<Config>() {
@Override
public Config createFromParcel(Parcel in) {
return new Config(in);
}
@Override
public Config[] newArray(int size) {
return new Config[size];
}
};
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(timeout);
}
}
protected HttpInfoBean(Parcel in) {
url = in.readString();
method = in.readString();
headers = in.readParcelable(Headers.class.getClassLoader());
data = in.readString();
config = in.readParcelable(Config.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(url);
dest.writeString(method);
dest.writeParcelable(headers, flags);
dest.writeString(data);
dest.writeParcelable(config, flags);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<HttpInfoBean> CREATOR = new Creator<HttpInfoBean>() {
@Override
public HttpInfoBean createFromParcel(Parcel in) {
return new HttpInfoBean(in);
}
@Override
public HttpInfoBean[] newArray(int size) {
return new HttpInfoBean[size];
}
};
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
public Headers getHeaders() {
return headers;
}
public void setHeaders(Headers headers) {
this.headers = headers;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
package com.hls.plugins.barcode.bean;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by panx on 2017/3/15.
*/
public class PageInfoBean implements Parcelable {
private final static String TAG = "PageInfoBean";
private String title;
private String tipScan;
private String tipInput;
private String tipLoading;
private String tipNetworkError;
private String tipOffline;
private String openButton;
private String footerFirst;
private String footerSecond;
private String barTitle;
private boolean explainFlag;
private boolean inputFlag;
private boolean lightFlag;
private String tipLightOn;
private String tipLightOff;
private long delayTime;
public PageInfoBean() {
}
protected PageInfoBean(Parcel in) {
title = in.readString();
tipScan = in.readString();
tipInput = in.readString();
tipLoading = in.readString();
tipNetworkError = in.readString();
tipOffline = in.readString();
openButton = in.readString();
footerFirst = in.readString();
footerSecond = in.readString();
barTitle = in.readString();
explainFlag = in.readByte() != 0;
inputFlag = in.readByte() != 0;
lightFlag = in.readByte() != 0;
tipLightOn = in.readString();
tipLightOff = in.readString();
delayTime = in.readLong();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeString(tipScan);
dest.writeString(tipInput);
dest.writeString(tipLoading);
dest.writeString(tipNetworkError);
dest.writeString(tipOffline);
dest.writeString(openButton);
dest.writeString(footerFirst);
dest.writeString(footerSecond);
dest.writeString(barTitle);
dest.writeByte((byte) (explainFlag ? 1 : 0));
dest.writeByte((byte) (inputFlag ? 1 : 0));
dest.writeByte((byte) (lightFlag ? 1 : 0));
dest.writeString(tipLightOn);
dest.writeString(tipLightOff);
dest.writeLong(delayTime);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<PageInfoBean> CREATOR = new Creator<PageInfoBean>() {
@Override
public PageInfoBean createFromParcel(Parcel in) {
return new PageInfoBean(in);
}
@Override
public PageInfoBean[] newArray(int size) {
return new PageInfoBean[size];
}
};
public static String getTAG() {
return TAG;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getTipScan() {
return tipScan;
}
public void setTipScan(String tipScan) {
this.tipScan = tipScan;
}
public String getTipInput() {
return tipInput;
}
public void setTipInput(String tipInput) {
this.tipInput = tipInput;
}
public String getTipLoading() {
return tipLoading;
}
public void setTipLoading(String tipLoading) {
this.tipLoading = tipLoading;
}
public String getTipNetworkError() {
return tipNetworkError;
}
public void setTipNetworkError(String tipNetworkError) {
this.tipNetworkError = tipNetworkError;
}
public String getTipOffline() {
return tipOffline;
}
public void setTipOffline(String tipOffline) {
this.tipOffline = tipOffline;
}
public String getOpenButton() {
return openButton;
}
public void setOpenButton(String openButton) {
this.openButton = openButton;
}
public String getFooterFirst() {
return footerFirst;
}
public void setFooterFirst(String footerFirst) {
this.footerFirst = footerFirst;
}
public String getFooterSecond() {
return footerSecond;
}
public void setFooterSecond(String footerSecond) {
this.footerSecond = footerSecond;
}
public String getBarTitle() {
return barTitle;
}
public void setBarTitle(String barTitle) {
this.barTitle = barTitle;
}
public boolean isExplainFlag() {
return explainFlag;
}
public void setExplainFlag(boolean explainFlag) {
this.explainFlag = explainFlag;
}
public boolean isInputFlag() {
return inputFlag;
}
public void setInputFlag(boolean inputFlag) {
this.inputFlag = inputFlag;
}
public boolean isLightFlag() {
return lightFlag;
}
public void setLightFlag(boolean lightFlag) {
this.lightFlag = lightFlag;
}
public String getTipLightOn() {
return tipLightOn;
}
public void setTipLightOn(String tipLightOn) {
this.tipLightOn = tipLightOn;
}
public String getTipLightOff() {
return tipLightOff;
}
public void setTipLightOff(String tipLightOff) {
this.tipLightOff = tipLightOff;
}
public long getDelayTime() {
return delayTime;
}
public void setDelayTime(long delayTime) {
this.delayTime = delayTime;
}
public static Creator<PageInfoBean> getCREATOR() {
return CREATOR;
}
}
package com.hls.plugins.barcode.camera;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
final class AutoFocusCallback implements Camera.AutoFocusCallback {
private static final String TAG = AutoFocusCallback.class.getSimpleName();
private static final long AUTOFOCUS_INTERVAL_MS = 1500L;
private Handler autoFocusHandler;
private int autoFocusMessage;
void setHandler(Handler autoFocusHandler, int autoFocusMessage) {
this.autoFocusHandler = autoFocusHandler;
this.autoFocusMessage = autoFocusMessage;
}
public void onAutoFocus(boolean success, Camera camera) {
if (autoFocusHandler != null) {
Message message = autoFocusHandler.obtainMessage(autoFocusMessage, success);
autoFocusHandler.sendMessageDelayed(message, AUTOFOCUS_INTERVAL_MS);
autoFocusHandler = null;
} else {
Log.d(TAG, "Got auto-focus callback, but no handler for it");
}
}
}
package com.hls.plugins.barcode.camera;
import java.util.regex.Pattern;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
final class CameraConfigurationManager {
private static final String TAG = CameraConfigurationManager.class
.getSimpleName();
private static final int TEN_DESIRED_ZOOM = 27;
private static final Pattern COMMA_PATTERN = Pattern.compile(",");
private final Context context;
private Point screenResolution;
private Point cameraResolution;
private int previewFormat;
private String previewFormatString;
CameraConfigurationManager(Context context) {
this.context = context;
}
@SuppressWarnings("deprecation")
void initFromCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
previewFormat = parameters.getPreviewFormat();
previewFormatString = parameters.get("preview-format");
WindowManager manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
screenResolution = new Point(display.getWidth(), display.getHeight());
Point screenResolutionForCamera = new Point();
screenResolutionForCamera.x = screenResolution.x;
screenResolutionForCamera.y = screenResolution.y;
if (screenResolution.x < screenResolution.y) {
screenResolutionForCamera.x = screenResolution.y;
screenResolutionForCamera.y = screenResolution.x;
}
cameraResolution = getCameraResolution(parameters, screenResolutionForCamera);
}
void setDesiredCameraParameters(Camera camera) {
Camera.Parameters parameters = camera.getParameters();
parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);
setFlash(parameters);
setZoom(parameters);
camera.setDisplayOrientation(90);
camera.setParameters(parameters);
}
Point getCameraResolution() {
return cameraResolution;
}
Point getScreenResolution() {
return screenResolution;
}
int getPreviewFormat() {
return previewFormat;
}
String getPreviewFormatString() {
return previewFormatString;
}
private static Point getCameraResolution(Camera.Parameters parameters,
Point screenResolution) {
String previewSizeValueString = parameters.get("preview-size-values");
if (previewSizeValueString == null) {
previewSizeValueString = parameters.get("preview-size-value");
}
Point cameraResolution = null;
if (previewSizeValueString != null) {
cameraResolution = findBestPreviewSizeValue(previewSizeValueString,
screenResolution);
}
if (cameraResolution == null) {
cameraResolution = new Point((screenResolution.x >> 3) << 3,
(screenResolution.y >> 3) << 3);
}
return cameraResolution;
}
private static Point findBestPreviewSizeValue(
CharSequence previewSizeValueString, Point screenResolution) {
int bestX = 0;
int bestY = 0;
int diff = Integer.MAX_VALUE;
for (String previewSize : COMMA_PATTERN.split(previewSizeValueString)) {
previewSize = previewSize.trim();
int dimPosition = previewSize.indexOf('x');
if (dimPosition < 0) {
continue;
}
int newX;
int newY;
try {
newX = Integer.parseInt(previewSize.substring(0, dimPosition));
newY = Integer.parseInt(previewSize.substring(dimPosition + 1));
} catch (NumberFormatException nfe) {
continue;
}
int newDiff = Math.abs(newX - screenResolution.x)
+ Math.abs(newY - screenResolution.y);
if (newDiff == 0) {
bestX = newX;
bestY = newY;
break;
} else if (newDiff < diff) {
bestX = newX;
bestY = newY;
diff = newDiff;
}
}
if (bestX > 0 && bestY > 0) {
return new Point(bestX, bestY);
}
return null;
}
private static int findBestMotZoomValue(CharSequence stringValues,
int tenDesiredZoom) {
int tenBestValue = 0;
for (String stringValue : COMMA_PATTERN.split(stringValues)) {
stringValue = stringValue.trim();
double value;
try {
value = Double.parseDouble(stringValue);
} catch (NumberFormatException nfe) {
return tenDesiredZoom;
}
int tenValue = (int) (10.0 * value);
if (Math.abs(tenDesiredZoom - value) < Math.abs(tenDesiredZoom
- tenBestValue)) {
tenBestValue = tenValue;
}
}
return tenBestValue;
}
private void setFlash(Camera.Parameters parameters) {
if (Build.MODEL.contains("Behold II") && CameraManager.SDK_INT == 3) { // 3
parameters.set("flash-value", 1);
} else {
parameters.set("flash-value", 2);
}
parameters.set("flash-mode", "off");
}
private void setZoom(Camera.Parameters parameters) {
String zoomSupportedString = parameters.get("zoom-supported");
if (zoomSupportedString != null
&& !Boolean.parseBoolean(zoomSupportedString)) {
return;
}
int tenDesiredZoom = TEN_DESIRED_ZOOM;
String maxZoomString = parameters.get("max-zoom");
if (maxZoomString != null) {
try {
int tenMaxZoom = (int) (10.0 * Double
.parseDouble(maxZoomString));
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad max-zoom: " + maxZoomString);
}
}
String takingPictureZoomMaxString = parameters
.get("taking-picture-zoom-max");
if (takingPictureZoomMaxString != null) {
try {
int tenMaxZoom = Integer.parseInt(takingPictureZoomMaxString);
if (tenDesiredZoom > tenMaxZoom) {
tenDesiredZoom = tenMaxZoom;
}
} catch (NumberFormatException nfe) {
Log.w(TAG, "Bad taking-picture-zoom-max: "
+ takingPictureZoomMaxString);
}
}
String motZoomValuesString = parameters.get("mot-zoom-values");
if (motZoomValuesString != null) {
tenDesiredZoom = findBestMotZoomValue(motZoomValuesString,
tenDesiredZoom);
}
String motZoomStepString = parameters.get("mot-zoom-step");
if (motZoomStepString != null) {
try {
double motZoomStep = Double.parseDouble(motZoomStepString
.trim());
int tenZoomStep = (int) (10.0 * motZoomStep);
if (tenZoomStep > 1) {
tenDesiredZoom -= tenDesiredZoom % tenZoomStep;
}
} catch (NumberFormatException nfe) {
// continue
}
}
// Set zoom. This helps encourage the user to pull back.
// Some devices like the Behold have a zoom parameter
if (maxZoomString != null || motZoomValuesString != null) {
parameters.set("zoom", String.valueOf(tenDesiredZoom / 10.0));
}
// Most devices, like the Hero, appear to expose this zoom parameter.
// It takes on values like "27" which appears to mean 2.7x zoom
if (takingPictureZoomMaxString != null) {
parameters.set("taking-picture-zoom", tenDesiredZoom);
}
}
}
package com.hls.plugins.barcode.camera;
import java.io.IOException;
import android.content.Context;
import android.graphics.Point;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Handler;
import android.view.SurfaceHolder;
public final class CameraManager {
private static CameraManager cameraManager;
static final int SDK_INT;
static {
int sdkInt;
try {
sdkInt = android.os.Build.VERSION.SDK_INT;
} catch (NumberFormatException nfe) {
sdkInt = 10000;
}
SDK_INT = sdkInt;
}
private final CameraConfigurationManager configManager;
private Camera camera;
private boolean initialized;
private boolean previewing;
private final boolean useOneShotPreviewCallback;
private final PreviewCallback previewCallback;
private final AutoFocusCallback autoFocusCallback;
private Parameters parameter;
public static void init(Context context) {
if (cameraManager == null) {
cameraManager = new CameraManager(context);
}
}
public static CameraManager get() {
return cameraManager;
}
private CameraManager(Context context) {
this.configManager = new CameraConfigurationManager(context);
useOneShotPreviewCallback = SDK_INT > 3;
previewCallback = new PreviewCallback(configManager, useOneShotPreviewCallback);
autoFocusCallback = new AutoFocusCallback();
}
public void openDriver(SurfaceHolder holder) throws IOException {
if (camera == null) {
camera = Camera.open();
if (camera == null) {
throw new IOException();
}
camera.setPreviewDisplay(holder);
if (!initialized) {
initialized = true;
configManager.initFromCameraParameters(camera);
}
configManager.setDesiredCameraParameters(camera);
FlashlightManager.enableFlashlight();
}
}
public Point getCameraResolution() {
return configManager.getCameraResolution();
}
public void closeDriver() {
if (camera != null) {
FlashlightManager.disableFlashlight();
camera.release();
camera = null;
}
}
public void startPreview() {
if (camera != null && !previewing) {
camera.startPreview();
previewing = true;
}
}
public void stopPreview() {
if (camera != null && previewing) {
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
camera.stopPreview();
previewCallback.setHandler(null, 0);
autoFocusCallback.setHandler(null, 0);
previewing = false;
}
}
public void requestPreviewFrame(Handler handler, int message) {
if (camera != null && previewing) {
previewCallback.setHandler(handler, message);
if (useOneShotPreviewCallback) {
camera.setOneShotPreviewCallback(previewCallback);
} else {
camera.setPreviewCallback(previewCallback);
}
}
}
public void requestAutoFocus(Handler handler, int message) {
if (camera != null && previewing) {
autoFocusCallback.setHandler(handler, message);
camera.autoFocus(autoFocusCallback);
}
}
public void openLight() {
if (camera != null) {
parameter = camera.getParameters();
parameter.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameter);
}
}
public void offLight() {
if (camera != null) {
parameter = camera.getParameters();
parameter.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameter);
}
}
}
package com.hls.plugins.barcode.camera;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.os.IBinder;
import android.util.Log;
final class FlashlightManager {
private static final String TAG = FlashlightManager.class.getSimpleName();
private static final Object iHardwareService;
private static final Method setFlashEnabledMethod;
static {
iHardwareService = getHardwareService();
setFlashEnabledMethod = getSetFlashEnabledMethod(iHardwareService);
if (iHardwareService == null) {
Log.v(TAG, "This device does supports control of a flashlight");
} else {
Log.v(TAG, "This device does not support control of a flashlight");
}
}
private FlashlightManager() {
}
private static Object getHardwareService() {
Class<?> serviceManagerClass = maybeForName("android.os.ServiceManager");
if (serviceManagerClass == null) {
return null;
}
Method getServiceMethod = maybeGetMethod(serviceManagerClass, "getService", String.class);
if (getServiceMethod == null) {
return null;
}
Object hardwareService = invoke(getServiceMethod, null, "hardware");
if (hardwareService == null) {
return null;
}
Class<?> iHardwareServiceStubClass = maybeForName("android.os.IHardwareService$Stub");
if (iHardwareServiceStubClass == null) {
return null;
}
Method asInterfaceMethod = maybeGetMethod(iHardwareServiceStubClass, "asInterface", IBinder.class);
if (asInterfaceMethod == null) {
return null;
}
return invoke(asInterfaceMethod, null, hardwareService);
}
private static Method getSetFlashEnabledMethod(Object iHardwareService) {
if (iHardwareService == null) {
return null;
}
Class<?> proxyClass = iHardwareService.getClass();
return maybeGetMethod(proxyClass, "setFlashlightEnabled", boolean.class);
}
private static Class<?> maybeForName(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException cnfe) {
// OK
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while finding class " + name, re);
return null;
}
}
private static Method maybeGetMethod(Class<?> clazz, String name, Class<?>... argClasses) {
try {
return clazz.getMethod(name, argClasses);
} catch (NoSuchMethodException nsme) {
// OK
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while finding method " + name, re);
return null;
}
}
private static Object invoke(Method method, Object instance, Object... args) {
try {
return method.invoke(instance, args);
} catch (IllegalAccessException e) {
Log.w(TAG, "Unexpected error while invoking " + method, e);
return null;
} catch (InvocationTargetException e) {
Log.w(TAG, "Unexpected error while invoking " + method, e.getCause());
return null;
} catch (RuntimeException re) {
Log.w(TAG, "Unexpected error while invoking " + method, re);
return null;
}
}
static void enableFlashlight() {
setFlashlight(true);
}
static void disableFlashlight() {
setFlashlight(false);
}
private static void setFlashlight(boolean active) {
if (iHardwareService != null) {
invoke(setFlashEnabledMethod, iHardwareService, active);
}
}
}
package com.hls.plugins.barcode.camera;
import android.graphics.Point;
import android.hardware.Camera;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
final class PreviewCallback implements Camera.PreviewCallback {
private static final String TAG = PreviewCallback.class.getSimpleName();
private final CameraConfigurationManager configManager;
private final boolean useOneShotPreviewCallback;
private Handler previewHandler;
private int previewMessage;
PreviewCallback(CameraConfigurationManager configManager, boolean useOneShotPreviewCallback) {
this.configManager = configManager;
this.useOneShotPreviewCallback = useOneShotPreviewCallback;
}
void setHandler(Handler previewHandler, int previewMessage) {
this.previewHandler = previewHandler;
this.previewMessage = previewMessage;
}
public void onPreviewFrame(byte[] data, Camera camera) {
Point cameraResolution = configManager.getCameraResolution();
if (!useOneShotPreviewCallback) {
camera.setPreviewCallback(null);
}
if (previewHandler != null) {
Message message = previewHandler.obtainMessage(previewMessage, cameraResolution.x,
cameraResolution.y, data);
message.sendToTarget();
previewHandler = null;
} else {
Log.d(TAG, "Got preview callback, but no handler for it");
}
}
}
package com.hls.plugins.barcode.decode;
import android.os.Handler;
import android.os.Message;
import __ANDROID_PACKAGE__.R;
import com.hls.plugins.barcode.CaptureActivity;
import com.hls.plugins.barcode.camera.CameraManager;
public final class CaptureActivityHandler extends Handler {
DecodeThread decodeThread = null;
CaptureActivity activity = null;
private State state;
private enum State {
PREVIEW, SUCCESS, DONE
}
public CaptureActivityHandler(CaptureActivity activity) {
this.activity = activity;
decodeThread = new DecodeThread(activity);
decodeThread.start();
state = State.SUCCESS;
CameraManager.get().startPreview();
restartPreviewAndDecode();
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case R.id.auto_focus:
if (state == State.PREVIEW) {
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
}
break;
case R.id.restart_preview:
restartPreviewAndDecode();
break;
case R.id.decode_succeeded:
state = State.SUCCESS;
activity.handleDecode((String) message.obj);// 解析成功,回调
break;
case R.id.decode_failed:
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(),
R.id.decode);
break;
}
}
public void quitSynchronously() {
state = State.DONE;
CameraManager.get().stopPreview();
removeMessages(R.id.decode_succeeded);
removeMessages(R.id.decode_failed);
removeMessages(R.id.decode);
removeMessages(R.id.auto_focus);
}
private void restartPreviewAndDecode() {
if (state == State.SUCCESS) {
state = State.PREVIEW;
CameraManager.get().requestPreviewFrame(decodeThread.getHandler(),
R.id.decode);
CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
}
}
}
package com.hls.plugins.barcode.decode;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import __ANDROID_PACKAGE__.R;
import com.hls.plugins.barcode.CaptureActivity;
import com.zbar.lib.ZbarManager;
final class DecodeHandler extends Handler {
CaptureActivity activity = null;
DecodeHandler(CaptureActivity activity) {
this.activity = activity;
}
@Override
public void handleMessage(Message message) {
switch (message.what) {
case R.id.decode:
decode((byte[]) message.obj, message.arg1, message.arg2);
break;
case R.id.quit:
Looper.myLooper().quit();
break;
}
}
private void decode(byte[] data, int width, int height) {
byte[] rotatedData = new byte[data.length];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++)
rotatedData[x * height + height - y - 1] = data[x + y * width];
}
int tmp = width;// Here we are swapping, that's the difference to #11
width = height;
height = tmp;
ZbarManager manager = new ZbarManager();
String result = manager.decode(rotatedData, width, height, true,
activity.getX(), activity.getY(), activity.getCropWidth(),
activity.getCropHeight());
if (result != null) {
if(null != activity.getHandler()){
Message msg = new Message();
msg.obj = result;
msg.what = R.id.decode_succeeded;
activity.getHandler().sendMessage(msg);
}
} else {
if (null != activity.getHandler()) {
activity.getHandler().sendEmptyMessage(R.id.decode_failed);
}
}
}
}
package com.hls.plugins.barcode.decode;
import java.util.concurrent.CountDownLatch;
import com.hls.plugins.barcode.CaptureActivity;
import android.os.Handler;
import android.os.Looper;
final class DecodeThread extends Thread {
CaptureActivity activity;
private Handler handler;
private final CountDownLatch handlerInitLatch;
DecodeThread(CaptureActivity activity) {
this.activity = activity;
handlerInitLatch = new CountDownLatch(1);
}
Handler getHandler() {
try {
handlerInitLatch.await();
} catch (InterruptedException ie) {
// continue?
}
return handler;
}
@Override
public void run() {
Looper.prepare();
handler = new DecodeHandler(activity);
handlerInitLatch.countDown();
Looper.loop();
}
}
package com.hls.plugins.barcode.decode;
import android.app.Activity;
import android.content.DialogInterface;
public final class FinishListener
implements DialogInterface.OnClickListener, DialogInterface.OnCancelListener, Runnable {
private final Activity activityToFinish;
public FinishListener(Activity activityToFinish) {
this.activityToFinish = activityToFinish;
}
public void onCancel(DialogInterface dialogInterface) {
run();
}
public void onClick(DialogInterface dialogInterface, int i) {
run();
}
public void run() {
activityToFinish.finish();
}
}
package com.hls.plugins.barcode.decode;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
public final class InactivityTimer {
private static final int INACTIVITY_DELAY_SECONDS = 5 * 60;
private final ScheduledExecutorService inactivityTimer = Executors.newSingleThreadScheduledExecutor(new DaemonThreadFactory());
private final Activity activity;
private ScheduledFuture<?> inactivityFuture = null;
public InactivityTimer(Activity activity) {
this.activity = activity;
onActivity();
}
public void onActivity() {
cancel();
inactivityFuture = inactivityTimer.schedule(new FinishListener(activity), INACTIVITY_DELAY_SECONDS, TimeUnit.SECONDS);
}
private void cancel() {
if (inactivityFuture != null) {
inactivityFuture.cancel(true);
inactivityFuture = null;
}
}
public void shutdown() {
cancel();
inactivityTimer.shutdown();
}
private static final class DaemonThreadFactory implements ThreadFactory {
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setDaemon(true);
return thread;
}
}
}
package com.hls.plugins.barcode.http;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import com.hls.plugins.barcode.bean.ArgsBean;
import com.hls.plugins.barcode.bean.CodeInfoBean;
import com.hls.plugins.barcode.bean.HttpInfoBean;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by panx on 2017/3/8.
*/
public class HttpManager {
public static final String TAG = "HttpManager";
public static final String NETWORK_ERROR = "请求发生错误,请稍后再试!";
public static Handler handler = new Handler(Looper.getMainLooper());
public static void get(final HttpInfoBean httpInfoBean, final ResultCallback<String> callback){
new Thread(){
@Override
public void run() {
super.run();
doGet(httpInfoBean,callback);
}
}.start();
}
private static void doGet(HttpInfoBean httpInfoBean, final ResultCallback<String> callback){
HttpUtil.get(httpInfoBean, new ResultCallback<String>() {
@Override
public void onError(Exception e, String error) {
handlerError(e,callback);
}
@Override
public void onResponse(String response, String result) {
handlerSuccess(response,callback);
}
});
}
public static void post(final HttpInfoBean httpInfoBean, final ResultCallback<String> callback) {
new Thread() {
@Override
public void run() {
super.run();
doPost(httpInfoBean, callback);
}
}.start();
}
private static void doPost(HttpInfoBean httpInfoBean, final ResultCallback<String> callback) {
HttpUtil.post(httpInfoBean, new ResultCallback<String>() {
@Override
public void onError(Exception e, String error) {
handlerError(e, callback);
}
@Override
public void onResponse(String response,String result) {
handlerSuccess(response, callback);
}
});
}
/**
* 网络请求成功时的处理
* @param response
* @param callback
*/
private static void handlerSuccess(final String response, final ResultCallback callback) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onResponse(response,"");
}
});
}
/**
* 网络请求失败的处理
* @param e
* @param callback
*/
private static void handlerError(final Exception e, final ResultCallback callback) {
handler.post(new Runnable() {
@Override
public void run() {
callback.onError(e, NETWORK_ERROR);
}
});
}
}
package com.hls.plugins.barcode.http;
import android.content.Intent;
import android.util.Log;
import com.hls.plugins.barcode.Util.NoSSLv3SocketFactory;
import com.hls.plugins.barcode.bean.ArgsBean;
import com.hls.plugins.barcode.bean.HttpInfoBean;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
/**
* Created by panx on 2017/3/8.
*/
public class HttpUtil {
/**
* 从网络获取json数据,(String byte[})
*
* @param httpInfoBean
* @return
*/
public static String get(HttpInfoBean httpInfoBean, ResultCallback<String> callback) {
try {
URL url = new URL(httpInfoBean.getUrl());
//打开连接
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setSSLSocketFactory(new NoSSLv3SocketFactory());
urlConnection.setRequestProperty("Authorization", httpInfoBean.getHeaders().getAuthorization());
urlConnection.setRequestProperty("Content-Type", httpInfoBean.getHeaders().getContentType());
if (200 == urlConnection.getResponseCode()) {
//得到输入流
InputStream is = urlConnection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while (-1 != (len = is.read(buffer))) {
baos.write(buffer, 0, len);
baos.flush();
}
System.out.println(baos.toString());
baos.close();
urlConnection.disconnect();
callback.onResponse(baos.toString(), "");
return baos.toString("utf-8");
}
} catch (IOException e) {
e.printStackTrace();
callback.onError(e, null);
}
return null;
}
//获取其他页面的数据
/**
* POST请求获取数据
*/
public static String post(HttpInfoBean httpInfoBean, ResultCallback<String> callback) {
URL url = null;
try {
url = new URL(httpInfoBean.getUrl());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setConnectTimeout(httpInfoBean.getConfig().getTimeout());
connection.setReadTimeout(30000);
connection.setDoOutput(true);// 是否输入参数
connection.setDoInput(true);
connection.setSSLSocketFactory(new NoSSLv3SocketFactory());
connection.setRequestProperty("Authorization", httpInfoBean.getHeaders().getAuthorization());
connection.setRequestProperty("Content-Type", httpInfoBean.getHeaders().getContentType());
connection.connect();
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes(httpInfoBean.getData());
out.flush();
out.close();
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
callback.onResponse(sb.toString(), null);
reader.close();
// 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
callback.onError(e, null);
}
return null;
}
}
package com.hls.plugins.barcode.http;
/**
* Created by panx on 2017/3/8.
*/
public abstract class ResultCallback<T> {
public abstract void onError(Exception e,String error);
public abstract void onResponse(T response,String result);
}
This diff is collapsed.
//
// BarcodeScannerViewController.h
// barcode
//
// Created by jingren on 16/9/11.
// Copyright © 2016年 jieweifu. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol BarcodeScannerDelegate <NSObject>
@optional
#pragma mark - Listening for Reader Status
- (void)reader:(NSDictionary *)result;
/**
* @abstract Tells the delegate that the user wants to stop scanning QRCodes.
* @param reader The reader view controller that the user wants to stop.
* @since 1.0.0
*/
- (void)readerDidCancel;
@end
@interface BarcodeScannerViewController : UIViewController
@property (nonatomic, weak) id<BarcodeScannerDelegate> delegate;
@property (weak, nonatomic) IBOutlet UILabel *firstSubLabel;
@property (weak, nonatomic) IBOutlet UILabel *secondSubLabel;
@property (nonatomic,strong) NSDictionary *requestDic;
@property (nonatomic,strong) NSString *firstString;
@property (nonatomic,strong) NSString *secondString;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanWidthConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scanHeightConstraint;
@property (nonatomic,strong) NSDictionary *messageDic;//显示信息
@property (nonatomic,strong) NSString *operationType;//处理类型
@property (nonatomic,strong) NSArray *requestList;//http请求列表
@end
This diff is collapsed.
//
// CDVBarcodeScanner.h
// HelloCordova
//
// Created by jingren on 16/9/11.
//
//
#import <Cordova/CDV.h>
#import "BarcodeScannerViewController.h"
@interface CDVBarcodeScanner : CDVPlugin<BarcodeScannerDelegate>
@property (nonatomic, strong) NSString *currentCallbackId;
- (void)startScan:(CDVInvokedUrlCommand *)command;
- (void)hasPermission:(CDVInvokedUrlCommand *)command;
@end
//
// CDVBarcodeScanner.m
// HelloCordova
//
// Created by jingren on 16/9/11.
//
//
#import "CDVBarcodeScanner.h"
#import <AVFoundation/AVFoundation.h>
#import "BarcodeScannerViewController.h"
@implementation CDVBarcodeScanner
- (void)startScan:(CDVInvokedUrlCommand *)command{
self.currentCallbackId = command.callbackId;
NSLog(@"args: %@", [command argumentAtIndex:0]);
NSDictionary *dic = command.arguments.count == 0 ? [NSNull null] : [command argumentAtIndex:0];
[self.commandDelegate runInBackground:^{
BarcodeScannerViewController *barcodeCtrl = [[BarcodeScannerViewController alloc] initWithNibName:@"BarcodeScannerViewController" bundle:nil];
barcodeCtrl.delegate = self;
barcodeCtrl.messageDic = dic[@"message"];
// @{@"barTitle":@"在头部栏显示的标题,可空",
// @"explainFlag":@(YES),
// @"title":@"扫码框上方的标题,可空",
// @"tipScan":@"扫码框下方的提示,可空",
// @"inputFlag":@(YES),
// @"lightFlag":@(YES),
// @"tipInput":@"输入单号提示,可空",
// @"tipLightOn":@"打开",
// @"tipLightOff":@"关闭",
// @"tipLoading":@"调接口的过程中的提示",
// @"tipNetworkError":@"网络错误时的提示",
// @"tipOffline":@"没有打开web时的提示",
// @"openButton":@"我已打开按钮文字",
// @"footerFirst":@"底部提示第一行,可空",
// @"footerSecond": @"底部提示第二行,可空",
// @"delayTime":@"2"
// };
//REVIEW: 读图审核 AUDIT_PASS: 通过 AUDIT: 驳回 RECEIVE: 收到 SCAN:扫码 INVOICE:发票验证
barcodeCtrl.operationType = dic[@"operationType"];
barcodeCtrl.requestList = dic[@"requests"];
// @[@{@"url":@"https://apiuat.huilianyi.com/api/audit/scancode",@"method":@"POST",@"headers":@{@"Authorization":@"Bearer b46e27f1-5277-485b-817a-3ed2f26e4175",@"Content-Type":@"application/json"},@"data":@{@"operate":barcodeCtrl.operationType}},@{@"url":@"https://apiuat.huilianyi.com/api/audit/scancode/online/check",@"method":@"GET",@"headers":@{@"Authorization":@"Bearer b46e27f1-5277-485b-817a-3ed2f26e4175",@"Content-Type":@"application/json"}}];
barcodeCtrl.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
dispatch_async(dispatch_get_main_queue(), ^{
[self.viewController presentViewController:barcodeCtrl animated:YES completion:nil];
});
}];
}
- (void)reader:(NSDictionary *)result{
[self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:result] callbackId:self.currentCallbackId];
}
- (void)readerDidCancel{
[self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus: CDVCommandStatus_ERROR] callbackId:self.currentCallbackId];
}
-(void)hasPermission:(CDVInvokedUrlCommand *)command {
Boolean result = false;
//判断是否已授权
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
if (authStatus == AVAuthorizationStatusDenied||authStatus == AVAuthorizationStatusRestricted) {
result = false;
}
}
// 判断是否可以打开相机
if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
result = true;
} else {
result = false;
}
AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
switch (status) {
// case AVAuthorizationStatusNotDetermined:{
// 许可对话没有出现,发起授权许可
//
// [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
//
// if (granted) {
// //第一次用户接受
// return true;
// }else{
// //用户拒绝
// return false;
// }
// }];
//
// [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
// if (!granted) { //用户拒绝
//
// }
// }];
// break;
// }
// case AVAuthorizationStatusAuthorized:{
// // 已经开启授权,可继续
// result = true;
// break;
// }
case AVAuthorizationStatusDenied:
case AVAuthorizationStatusRestricted:
// 用户明确地拒绝授权,或者相机设备无法访问
result = false;
break;
default:
break;
}
CDVPluginResult *pluginResult;
if(!result){
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"false"];
}else{
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"true"];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
//
// CustomScanView.h
// HandTest
//
// Created by Mr.xiao on 17/3/15.
//
//
#import <UIKit/UIKit.h>
@interface CustomScanView : UIView
@property (nonatomic,strong) UIImageView *imgView;
@property (nonatomic,strong) UILabel *msgLabel;
@property (nonatomic,strong) UIButton *openBtn;
@property (nonatomic,strong) UILabel *firstLabel;
@property (nonatomic,strong) UILabel *secondLabel;
@end
@interface NetWorkView : UIView
@property (nonatomic,strong) UIImageView *imgView;
@property (nonatomic,strong) UILabel *msgLabel;
@end
@interface NetWorkTool : NSObject
+ (instancetype)shareInstance;
+ (NSURLSessionDataTask *)request:(NSString *)url header:(NSDictionary *)header method:(NSString *)method params:(NSDictionary *)params success:(void (^)(id response))successBlock failure:(void(^)(NSError *error))failure;
@end
//
// CustomScanView.m
// HandTest
//
// Created by Mr.xiao on 17/3/15.
//
//
#import "CustomScanView.h"
@implementation CustomScanView
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self initSubViews];
}
return self;
}
- (void)initSubViews{
CGSize size = self.frame.size;
self.backgroundColor = [UIColor colorWithRed:127.0/255.0 green:127.0/255.0 blue:127.0/255.0 alpha:1];
_imgView = [[UIImageView alloc] initWithFrame:CGRectMake((size.width-200)/2, 30, 200, 200)];
_imgView.image = [UIImage imageNamed:@"hly_pc"];
[self addSubview:_imgView];
_msgLabel = [[UILabel alloc] initWithFrame:CGRectMake((size.width-200)/2, CGRectGetMaxY(_imgView.frame)+20, 200, 50)];
_msgLabel.numberOfLines = 0;
_msgLabel.text = @"请按照页面下方提示\n先打开汇联易网站";
_msgLabel.textColor = [UIColor whiteColor];
_msgLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_msgLabel];
_openBtn = [UIButton buttonWithType:UIButtonTypeCustom];
_openBtn.frame = CGRectMake((size.width-140)/2, CGRectGetMaxY(_msgLabel.frame)+20, 140, 35);
[_openBtn setTitle:@"我已打开" forState:UIControlStateNormal];
_openBtn.layer.cornerRadius = 15;
[_openBtn setBackgroundColor:[UIColor colorWithRed:23/255.0 green:147/255.0 blue:215/255.0 alpha:1]];
[self addSubview:_openBtn];
_secondLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, size.height-25-30, size.width-40, 30)];
_secondLabel.textColor = [UIColor whiteColor];
_secondLabel.font = [UIFont systemFontOfSize:15];
_secondLabel.numberOfLines = 0;
_secondLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_secondLabel];
_firstLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, CGRectGetMinY(_secondLabel.frame)-55, size.width-40, 50)];
_firstLabel.numberOfLines = 0;
_firstLabel.textColor = [UIColor whiteColor];
_firstLabel.font = [UIFont systemFontOfSize:15];
_firstLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_firstLabel];
}
@end
@implementation NetWorkView
- (instancetype)initWithFrame:(CGRect)frame{
if (self = [super initWithFrame:frame]) {
[self initSubViews];
}
return self;
}
- (void)initSubViews{
CGSize size = self.frame.size;
self.backgroundColor = [UIColor colorWithRed:127.0/255.0 green:127.0/255.0 blue:127.0/255.0 alpha:1];
_imgView = [[UIImageView alloc] initWithFrame:CGRectMake((size.width-200)/2, 50, 200, 200)];
_imgView.image = [UIImage imageNamed:@"hly_net"];
[self addSubview:_imgView];
_msgLabel = [[UILabel alloc] initWithFrame:CGRectMake((size.width-200)/2, 275, 200, 50)];
_msgLabel.numberOfLines = 0;
_msgLabel.text = @"当前网络不可用,请检查网络!";
_msgLabel.textColor = [UIColor whiteColor];
_msgLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:_msgLabel];
}
@end
@implementation NetWorkTool
+ (instancetype)shareInstance{
static NetWorkTool *network;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
network = [[NetWorkTool alloc] init];
});
return network;
}
+ (NSURLSessionDataTask *)request:(NSString *)url header:(NSDictionary *)header method:(NSString *)method params:(NSDictionary *)params success:(void (^)(id response))successBlock failure:(void(^)(NSError *error))failure{
NSURL *Url = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Url];
[request setHTTPMethod:[method uppercaseString]];
if(params){ //设置请求体
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:nil]];
}//设置请求头
if(header){
[request setAllHTTPHeaderFields:header];
}
NSURLSessionDataTask *task = [[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if(!error){
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
successBlock(result);
}else{
failure(error);
}
}];
[task resume];
return task;
}
@end
//
// CustomButton.h
// IonicTest
//
// Created by Mr.xiao on 2017/8/7.
//
//
#import <UIKit/UIKit.h>
@interface HLYCustomButton : UIButton
- (instancetype)initWithFrame:(CGRect)frame imgName:(NSString *)imgName titleString:(NSString *)title;
- (void)setClickTitle:(NSString *)title isOpen:(BOOL)isOpen;
@end
//
// CustomButton.m
// IonicTest
//
// Created by Mr.xiao on 2017/8/7.
//
//
#import "HLYCustomButton.h"
#define kImgWidth 60
@interface HLYCustomButton ()
@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, strong) UILabel *btnNameLabel;
@end
@implementation HLYCustomButton
- (instancetype)initWithFrame:(CGRect)frame imgName:(NSString *)imgName titleString:(NSString *)title{
if(self = [super initWithFrame:frame]){
[self initSubViewsWithImgName:imgName title:title];
}
return self;
}
- (void)initSubViewsWithImgName:(NSString *)imgName title:(NSString *)title{
CGSize size = self.frame.size;
if(size.width == 0){
return;
}
_imgView = [[UIImageView alloc] initWithFrame:CGRectMake((size.width-kImgWidth)/2, 0, kImgWidth, kImgWidth)];
_imgView.image = [UIImage imageNamed:imgName];
[self addSubview:_imgView];
_btnNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_imgView.frame)+8, size.width, 25)];
_btnNameLabel.font = [UIFont fontWithName:title size:14];
_btnNameLabel.text = title;
_btnNameLabel.textAlignment = NSTextAlignmentCenter;
_btnNameLabel.textColor = [UIColor whiteColor];
[self addSubview:_btnNameLabel];
}
- (void)setClickTitle:(NSString *)title isOpen:(BOOL)isOpen{
dispatch_async(dispatch_get_main_queue(), ^{
_btnNameLabel.text = title;
if(isOpen){
_imgView.image = [UIImage imageNamed:@"light_open"];
_btnNameLabel.textColor = [UIColor colorWithRed:25/255.0f green:120/255.0f blue:209/255.0f alpha:1];
}else{
_btnNameLabel.textColor = [UIColor whiteColor];
_imgView.image = [UIImage imageNamed:@"light_close"];
}
});
}
@end
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment