CaptureActivity.java 15.0 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
package com.yinhebairong.clasmanage.zxing.android;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.donkingliang.imageselector.utils.ImageSelector;
import com.github.mikephil.charting.utils.Utils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Result;
import com.yinhebairong.clasmanage.Config;
import com.yinhebairong.clasmanage.R;
import com.yinhebairong.clasmanage.entity.ErweimaEntity;
import com.yinhebairong.clasmanage.m.M;
import com.yinhebairong.clasmanage.network.ApiService;
import com.yinhebairong.clasmanage.network.ApiStore;
import com.yinhebairong.clasmanage.ui.login.LoginActivity;
import com.yinhebairong.clasmanage.zxing.Jifen_Activity;
import com.yinhebairong.clasmanage.zxing.camera.CameraManager;
import com.yinhebairong.clasmanage.zxing.jafsbActivity;
import com.yinhebairong.clasmanage.zxing.view.ViewfinderView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.autosize.utils.LogUtils;

import static android.service.notification.Condition.SCHEME;

/**
 * 这个activity打开相机,在后台线程做常规的扫描;它绘制了一个结果view来帮助正确地显示条形码,在扫描的时候显示反馈信息,
 * 然后在扫描成功的时候覆盖扫描结果
 */
public final class CaptureActivity extends Activity implements
        SurfaceHolder.Callback {
    private static final String TAG = CaptureActivity.class.getSimpleName();

    // 相机控制
    private CameraManager cameraManager;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private static final int REQUEST_CODE = 0x00000011;   // 图片
    private static final int PERMISSION_WRITE_EXTERNAL_REQUEST_CODE = 0x00000012;  // 图片
    private static final int APP_PKG_NAME_22 = 0001;
    private static final int APP_PKG_NAME_21 = 0002;
    private static final int APP_DETAILS_PACKAGE_NAME = 0003;
    private static final int APP_DETAILS_CLASS_NAME = 0004;
    private static final int TAKE_PHOTO = 0;
    private IntentSource source;
    private Collection<BarcodeFormat> decodeFormats;
    private Map<DecodeHintType, ?> decodeHints;
    private String characterSet;
    private TextView tv_cx;

    // 电量控制
    private InactivityTimer inactivityTimer;
    // 声音、震动控制
    private BeepManager beepManager;

    private ImageButton imageButton_back;

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public CameraManager getCameraManager() {
        return cameraManager;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    /**
     * OnCreate中初始化一些辅助类,如InactivityTimer(休眠)、Beep(声音)以及AmbientLight(闪光灯)
     */
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        // 保持Activity处于唤醒状态
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.capture);

        hasSurface = false;

        inactivityTimer = new InactivityTimer(this);
        beepManager = new BeepManager(this);

        imageButton_back = (ImageButton) findViewById(R.id.capture_imageview_back);
        imageButton_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tv_cx = findViewById(R.id.tv_cx);
        tv_cx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onJumpPictures();

            }
        });

    }

    private void onJumpPictures() {
        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()));
        //判断有没有android.permission.WRITE_EXTERNAL_STORAGE权限
        if (permission) {
            //如果有权限则激活系统相册
            // 激活系统图库,选择一张图片
            Intent innerIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
            startActivityForResult(wrapperIntent, TAKE_PHOTO);
            return;
        }else {
            //请求存储权限
            displayFrameworkBugMessageAndExit();
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        } else {
            //此处的用于判断接收的Activity是不是你想要的那个
            //这说明是用户点击了图片返回到的app界面
            if (requestCode == REQUEST_CODE) {

                Result result = null;
                try {
                    String[] proj = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(data.getData(),
                            proj, null, null, null);

                    if (cursor.moveToFirst()) {
                        int column_index = cursor
                                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//                        path = cursor.getString(column_index);
//                        if (path == null) {
//                            path = Utils.getPath(getApplicationContext(),
//                                    data.getData());
//                        }

                    }

                    cursor.close();

//                    result = scanningImage(path);

                    if (result == null) {
                        Log.i(TAG,"未识别到二维码");
                    } else {
                        Log.i(TAG,"识别到的二维码" + result.toString());
                    }

                } catch (Exception e) {
                    Log.i(TAG,"报错信息");
                }
            }

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // CameraManager必须在这里初始化,而不是在onCreate()中。
        // 这是必须的,因为当我们第一次进入时需要显示帮助页,我们并不想打开Camera,测量屏幕大小
        // 当扫描框的尺寸不正确时会出现bug
        cameraManager = new CameraManager(getApplication());

        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        viewfinderView.setCameraManager(cameraManager);

        handler = null;

        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            // activity在paused时但不会stopped,因此surface仍旧存在;
            // surfaceCreated()不会调用,因此在这里初始化camera
            initCamera(surfaceHolder);
        } else {
            // 重置callback,等待surfaceCreated()来初始化camera
            surfaceHolder.addCallback(this);
        }

        beepManager.updatePrefs();
        inactivityTimer.onResume();

        source = IntentSource.NONE;
        decodeFormats = null;
        characterSet = null;
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        inactivityTimer.onPause();
        beepManager.close();
        cameraManager.closeDriver();
        if (!hasSurface) {
            SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    /**
     * 扫描成功,处理反馈信息
     *
     * @param rawResult
     * @param barcode
     * @param scaleFactor
     */
    public void handleDecode(Result rawResult, Bitmap barcode, float scaleFactor) {
        inactivityTimer.onActivity();
        boolean fromLiveScan = barcode != null;
        //这里处理解码完成后的结果,此处将参数回传到Activity处理
        if (fromLiveScan) {
            beepManager.playBeepSoundAndVibrate();
            Intent intent = getIntent();
            intent.putExtra("codedContent", rawResult.getText());
            Log.i(TAG, "handleDecode: " + rawResult.getText());
           getStatus(intent,rawResult);
        }
    }
    int currentIdSize = 0;
    private void getStatus(Intent intent,Result rawResult){
        ApiStore.createApi(ApiService.class)
                .erweima(Config.Token, Config.id, rawResult.getText())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ErweimaEntity>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ErweimaEntity erweimaEntity) {
                        Log.e("TageA", "onNext: "+erweimaEntity);
                        ErweimaEntity.DataBean data = erweimaEntity.getData();
                        if (erweimaEntity.getCode() == M.success) {
                            ErweimaEntity.DataBean.EvaluateBean evaluate = data.getEvaluate();
                            ErweimaEntity.DataBean.StudentBean studentBean = data.getStudent();
                            Log.d("TagA",evaluate.getStatus()+"");
                            Log.d("TagA", LoginActivity.ids.get(currentIdSize) + "success");
                            intent.setClass(CaptureActivity.this, Jifen_Activity.class);//成功
                            intent.putExtra("score", evaluate.getScore());
                            intent.putExtra("status", evaluate.getStatus());
                            intent.putExtra("name", evaluate.getName());
                            intent.putExtra("qrcode", evaluate.getQrcode());
                            intent.putExtra("names", studentBean.getName());
                            intent.putExtra("base_name", evaluate.getBase_name());
                            startActivity(intent);
//                            switch (evaluate.getStatus()) {
//                                case 1:
//                                    intent.setClass(CaptureActivity.this, Jifen_Activity.class);//成功
//                                    intent.putExtra("score", evaluate.getScore());
//                                    intent.putExtra("status", evaluate.getStatus());
//                                    intent.putExtra("name", evaluate.getName());
//                                    intent.putExtra("qrcode", evaluate.getQrcode());
//                                    intent.putExtra("names", studentBean.getName());
//                                    intent.putExtra("base_name", evaluate.getBase_name());
//                                    startActivity(intent);
//                                    break;
//                            }
                        }
                        else if (erweimaEntity.getData().getStudent().getId() == 1) {
                            intent.setClass(CaptureActivity.this, jafsbActivity.class);//失败
                            startActivity(intent);
                        }else {
                            Toast.makeText(CaptureActivity.this, ""+erweimaEntity.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                        finish();
                    }
                    @Override
                    public void onError(Throwable e) {
                        intent.setClass(CaptureActivity.this, jafsbActivity.class);//失败
                        startActivity(intent);
                    }
                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 初始化Camera
     *
     * @param surfaceHolder
     */
    private void initCamera(SurfaceHolder surfaceHolder) {
        if (surfaceHolder == null) {
            throw new IllegalStateException("No SurfaceHolder provided");
        }
        if (cameraManager.isOpen()) {
            return;
        }
        try {
            // 打开Camera硬件设备
            cameraManager.openDriver(surfaceHolder);
            // 创建一个handler来打开预览,并抛出一个运行时异常
            if (handler == null) {
                handler = new CaptureActivityHandler(this, decodeFormats,
                        decodeHints, characterSet, cameraManager);
            }
        } catch (IOException ioe) {
            Log.w(TAG, ioe);
            displayFrameworkBugMessageAndExit();
        } catch (RuntimeException e) {
            Log.w(TAG, "Unexpected error initializing camera", e);
            displayFrameworkBugMessageAndExit();
        }
    }

    /**
     * 显示底层错误信息并退出应用
     */
    private void displayFrameworkBugMessageAndExit() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(getString(R.string.app_name));
        builder.setMessage(getString(R.string.msg_camera_framework_bug));
        builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
        builder.setOnCancelListener(new FinishListener(this));
        builder.show();
    }

}