Java tutorial
/* * Copyright (C) 2008 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kuaichumen.whistle.admin; import java.io.IOException; import java.lang.reflect.Field; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Rect; import android.hardware.Camera; import android.os.Bundle; import android.os.Handler; 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.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.zxing.Result; import com.kuaichumen.whistle.BaseActivity; import com.kuaichumen.whistle.R; import org.json.JSONObject; import KSData.ApplicationSettings; import KSData.KSHttpRequestCollection; import KSModel.Event; import KSModel.HttpRequestResult; import KSUtil.BeepManager; import KSUtil.CaptureActivityHandler; import KSUtil.InactivityTimer; import KSUtil.LogUtil; import camera.CameraManager; import de.greenrobot.event.EventBus; import decode.DecodeThread; /** * This activity opens the camera and does the actual scanning on a background * thread. It draws a viewfinder to help the user place the barcode correctly, * shows feedback as the image processing is happening, and then overlays the * results when a scan is successful. * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen */ public final class CaptureActivity extends BaseActivity implements SurfaceHolder.Callback { private static final String TAG = CaptureActivity.class.getSimpleName(); private CameraManager cameraManager; private Camera camera; private Camera.Parameters parameter; private CaptureActivityHandler handler; private InactivityTimer inactivityTimer; private BeepManager beepManager; private LinearLayout flashLight; private SurfaceView scanPreview = null; private RelativeLayout scanContainer; private RelativeLayout scanCropView; private ImageView scanLine; private ImageView flash; private TextView title; private LinearLayout ll_back; private Rect mCropRect = null; public Handler getHandler() { return handler; } public CameraManager getCameraManager() { return cameraManager; } private boolean isHasSurface = false; private boolean flag; private int type = 0;//1?? 0? private int SUCCESS = 1; private int FAIL = 0; String result; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_capture); getSupportActionBar().hide(); CameraManager.init(getApplication()); scanPreview = (SurfaceView) findViewById(R.id.capture_preview); scanContainer = (RelativeLayout) findViewById(R.id.capture_container); scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view); scanLine = (ImageView) findViewById(R.id.capture_scan_line); title = (TextView) findViewById(R.id.title); flashLight = (LinearLayout) findViewById(R.id.flash_light); ll_back = (LinearLayout) findViewById(R.id.ll_back); flash = (ImageView) findViewById(R.id.flash); flashLight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { light(); } }); ll_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); inactivityTimer = new InactivityTimer(this); beepManager = new BeepManager(this); TranslateAnimation animation = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.9f); animation.setDuration(4500); animation.setRepeatCount(-1); animation.setRepeatMode(Animation.RESTART); scanLine.startAnimation(animation); EventBus.getDefault().register(this); InitData(); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("isLoginOut", type); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); type = savedInstanceState.getInt("type"); } private void InitData() { Bundle bundle = getIntent().getExtras(); if (bundle != null) { type = bundle.getInt("type"); if (type == 0) { title.setText("?"); } else { title.setText("??"); } } ksHttpRequestCollection.setRequestFinishListener(new KSHttpRequestCollection.RequestFinishListener() { @Override public void onSuccess(HttpRequestResult httpRequestResult) { try { dismissLoadingDialog(); JSONObject jsonObject = new JSONObject(httpRequestResult.getResult()); LogUtil.d(TAG, jsonObject.toString()); int resultcode = jsonObject.getJSONObject("error").getInt("errorno"); Intent intent = null; switch (resultcode) { case 0: result = jsonObject.getString("result"); switch (httpRequestResult.getRequestType()) { case KSHttpRequestCollection.activitySigninURL://? ToSigninResultActivity(SUCCESS, result); break; case KSHttpRequestCollection.welfareVerifyURL://??? //? ToBenefitsGrantResultActivity(SUCCESS, result); break; } break; case 323: result = jsonObject.getString("result"); ToSigninResultActivity(FAIL, result); break; case 331://? result = jsonObject.getString("result"); ToBenefitsGrantResultActivity(FAIL, result); break; case 330: showMessage(ksHttpRequestCollection.requestResultCodeMap.get(resultcode)); break; case 321: showMessage(ksHttpRequestCollection.requestResultCodeMap.get(resultcode)); break; default: showMessage(ksHttpRequestCollection.requestResultCodeMap.get(resultcode)); finish(); break; } } catch (Exception e) { } } @Override public void onFailure(HttpRequestResult httpRequestResult) { if (type == 1) { showMessage("???"); } else { showMessage("??"); } LogUtil.d(TAG, httpRequestResult.getResult()); dismissLoadingDialog(); } }); } private void ToBenefitsGrantResultActivity(int result, String benefitsinfo) { Intent intent = new Intent(this, BenefitsGrantResultActivity.class); intent.putExtra("result", result); intent.putExtra("benefitsinfo", benefitsinfo); intent.putExtra("type", 0); startActivity(intent); finish(); } private void ToSigninResultActivity(int result, String signResult) { Intent intent = new Intent(this, SigninResultActivity.class); intent.putExtra("result", result); intent.putExtra("signResult", signResult); intent.putExtra("type", 0); startActivity(intent); finish(); } protected void light() { camera = CameraManager.getCamera(); parameter = camera.getParameters(); if (flag) {// flash.setImageResource(R.drawable.flash_on); parameter.setFlashMode(Camera.Parameters.FLASH_MODE_OFF); camera.setParameters(parameter); flag = false; } else { // flash.setImageResource(R.drawable.flash_off); parameter.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH); camera.setParameters(parameter); flag = true; } } @Override protected void onResume() { super.onResume(); cameraManager = new CameraManager(getApplication()); handler = null; if (isHasSurface) { // The activi) won't be called, so init the camera here. initCamera(scanPreview.getHolder()); } else { // Install the callback and wait for surfaceCreated() to init the // camera. scanPreview.getHolder().addCallback(this); } inactivityTimer.onResume(); } @Override protected void onPause() { if (handler != null) { handler.quitSynchronously(); handler = null; } inactivityTimer.onPause(); beepManager.close(); cameraManager.closeDriver(); if (!isHasSurface) { scanPreview.getHolder().removeCallback(this); } super.onPause(); } @Override protected void onDestroy() { inactivityTimer.shutdown(); EventBus.getDefault().unregister(this); super.onDestroy(); } public void onEventMainThread(Event.NoNet noNet) { dismissLoadingDialog(); } @Override public void surfaceCreated(SurfaceHolder holder) { if (holder == null) { Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!"); } if (!isHasSurface) { isHasSurface = true; initCamera(holder); } } @Override public void surfaceDestroyed(SurfaceHolder holder) { isHasSurface = false; } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { } /** * A valid barcode has been found, so give an indication of success and show * the results. * * @param rawResult The contents of the barcode. * @param bundle The extras */ public void handleDecode(Result rawResult, Bundle bundle) { inactivityTimer.onActivity(); beepManager.playBeepSoundAndVibrate(); String code = rawResult.getText(); String hash = ApplicationSettings.getString("activity_hash", context); if (type == 1) { showLoadingDialog("?"); ksHttpRequestCollection.welfareVerifyRequest(hash, code, 0); } else { showLoadingDialog(""); ksHttpRequestCollection.activitySigninRequest(hash, code, 0); } } private void initCamera(SurfaceHolder surfaceHolder) { if (surfaceHolder == null) { throw new IllegalStateException("No SurfaceHolder provided"); } if (cameraManager.isOpen()) { Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?"); return; } try { cameraManager.openDriver(surfaceHolder); // Creating the handler starts the preview, which can also throw a // RuntimeException. if (handler == null) { handler = new CaptureActivityHandler(this, cameraManager, DecodeThread.ALL_MODE); } initCrop(); } catch (IOException ioe) { Log.w(TAG, ioe); displayFrameworkBugMessageAndExit(); } catch (RuntimeException e) { // Barcode Scanner has seen crashes in the wild of this variety: // java.?lang.?RuntimeException: Fail to connect to camera service Log.w(TAG, "Unexpected error initializing camera", e); displayFrameworkBugMessageAndExit(); } } private void displayFrameworkBugMessageAndExit() { // camera error AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(com.kuaichumen.whistle.R.string.app_name)); builder.setMessage("???"); builder.setPositiveButton("", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }); builder.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { finish(); } }); builder.show(); } public void restartPreviewAfterDelay(long delayMS) { if (handler != null) { handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS); } } public Rect getCropRect() { return mCropRect; } /** * ?? */ private void initCrop() { int cameraWidth = cameraManager.getCameraResolution().y; int cameraHeight = cameraManager.getCameraResolution().x; /** ????? */ int[] location = new int[2]; scanCropView.getLocationInWindow(location); int cropLeft = location[0]; int cropTop = location[1] - getStatusBarHeight(); int cropWidth = scanCropView.getWidth(); int cropHeight = scanCropView.getHeight(); /** ? */ int containerWidth = scanContainer.getWidth(); int containerHeight = scanContainer.getHeight(); /** ?x?? */ int x = cropLeft * cameraWidth / containerWidth; /** ?y?? */ int y = cropTop * cameraHeight / containerHeight; /** ? */ int width = cropWidth * cameraWidth / containerWidth; /** ? */ int height = cropHeight * cameraHeight / containerHeight; /** ?? */ mCropRect = new Rect(x, y, width + x, height + y); } private int getStatusBarHeight() { try { Class<?> c = Class.forName("com.android.internal.R$dimen"); Object obj = c.newInstance(); Field field = c.getField("status_bar_height"); int x = Integer.parseInt(field.get(obj).toString()); return getResources().getDimensionPixelSize(x); } catch (Exception e) { e.printStackTrace(); } return 0; } }