Typical Android (java) callback function example: android callback function

Source: Internet
Author: User
Tags call back

Typical Android (java) callback function example: android callback function

Typical callback function example


1. Use the java callback function to implement a tool class for testing the function running time

Public class TestObject {/*** a method used for testing, and a time-consuming cycle */public static void testMethod () {for (int I = 0; I <100000000; I ++) {}}/*** a simple test method */public void testTime () {long begin = System. currentTimeMillis (); // Test start time testMethod (); // test method long end = System. currentTimeMillis (); // test end time System. out. println ("[use time]:" + (end-begin); // print the time used} public static void main (String [] args) {TestObject test = new TestObject (); test. testTime ();}}


As you can see, only the "// test method" of the testTime () method needs to be changed. Let's create a function to implement the same function but be more flexible:


2. First define a callback Interface

Public interface CallBack {// Method for executing the CallBack operation void execute ();}


3. Define a tool class

Public class Tools {/*** test the function usage time by defining the execute method of the CallBack interface * @ param callBack */public void testTime (CallBack callBack) {long begin = System. currentTimeMillis (); // Test start time callBack.exe cute (); // perform the callback operation long end = System. currentTimeMillis (); // test end time System. out. println ("[use time]:" + (end-begin); // print the time used}

?

? 4. Test Method

Public static void main (String [] args) {Tools tool = new Tools (); tool. testTime (new CallBack () {// defines the execute method public void execute () {// here you can add one or more methods TestObject to test the running time. testMethod ();}});}


Use of callback in Project

Requirement Description:

After a custom camera takes a photo, Use callback in the PictureCallback for processing the image data.

Purpose:

After the image is processed (such as quality, size, and proportional compression) during image generation, Jni is used in the callback to extract image features and access the network to achieve image recognition.

1. Declare the interface

Package app. ui. callback;/*** @ author gao_chun **/public interface MyCallBack {public void cameraHasOpened (); // Camera public void toDistinguish (); // recognition}


2. PictureCallback in the CameraInterface class, which provides the callback set Method

Public class CameraInterface {private static final String TAG = "gao_chun"; public boolean isCameraStop = false; // mark whether the Camera is on or off private Camera mCamera; private Camera. parameters mParams; private boolean isPreviewing = false; private float mPreviwRate =-1f; // identifies the callback private MyCallBack mCallBack; public void setmCallBack (MyCallBack mCallBack) {this. mCallBack = mCallBack;}/*** photograph */public void doT AkePicture () {if (isPreviewing & (mCamera! = Null) {mCamera. takePicture (mShutterCallback, null, mJpegPictureCallback) ;}// callback of jpeg image data. The most important callback is PictureCallback m?picturecallback = new PictureCallback () {public void onPictureTaken (byte [] data, Camera camera) {Log. I (TAG, "mycallback callback: onPictureTaken... "); Bitmap mBitmap = null; if (null! = Data) {// data is byte data, which is parsed into bitmap mBitmap = BitmapFactory. decodeByteArray (data, 0, data. length); mCamera. stopPreview (); isPreviewing = false;} if (null! = MBitmap) {Bitmap newBitmap = FileOperation. scaleToBitmap (mBitmap, FileOperation. scale); // calculate the image width and height based on Bitmap in proportion/* int w = mBitmap. getWidth (); int h = mBitmap. getHeight (); int scale = 512; // default proportion int max = w> h? W: h; float r = scale * 1.0f/max; int ww = (int) Math. ceil (w * r); int hh = (int) Math. ceil (h * r); Bitmap mBitmap = FileOperation. zoomImg (rotaBitmap, ww, hh); * // FileOperation. delFile (FileOperation. FILENAME_ICON); // Delete the image FileOperation. saveBitmap (newBitmap, FileOperation. FILENAME_ICON); // Save the image // callback method, the Operation mCallBack to be executed. toDistinguish (); mBitmap = null; newBitmap = null;} // preview mCamera again. startPreview (); isPreviewing = true ;}};}


3. The CameraActivity class implements this interface and method.

Public class CameraActivity extends TitleActivity implements MyCallBack {/* (non-Javadoc) * @ see app. ui. widget. titleActivity # onClick (android. view. view) * click to take the image and call back for processing */@ Override public void onClick (View v) {super. onClick (v); switch (v. getId () {case R. id. shutter: CameraInterface. getInstance (). doTakePicture (); // take a photo // determine if (! FileOperation. checkFileExist (FileOperation. FILENAME_AVG) |! FileOperation. checkFileExist (FileOperation. FILENAME_VEC) {// read the files in the assets Directory and write them to sdcard FileOperation. readAssetsAndWrite (this, "avg.txt"); FileOperation. readAssetsAndWrite (this, "vec.txt");} mLoading. show (); // sets the CameraInterface for recognition callback. getInstance (). setmCallBack (this); // you cannot click shutterView again. setClickable (false); break; default: break;}/* (non-Javadoc) * @ see app. ui. callback. myCallBack # toDistinguish () * image recognition */@ Override public void toDistinguish () {// TODO Auto-generated method stub if (FileOperation. checkFileExist (FileOperation. FILENAME_ICON) {getPictureFeature (); // extract image features} else {DialogUtils. showToast (CameraActivity. this, "the image is not completely saved, please rephotograph") ;}/ *** 1. obtain the image path and feature file * 2. use jni to extract features * 3. access Server */private void getPictureFeature () {// read image and extract feature parameter mPicPath = FileOperation. getFilePath () + FileOperation. FILENAME_ICON; mVecPath = FileOperation. getFilePath () + FileOperation. FILENAME_VEC; mAvgPath = FileOperation. getFilePath () + FileOperation. FILENAME_AVG; // Log. I (TAG, "mPicPath ------------->" + mPicPath + "\ n mVecPath ---->" + mVecPath + "\ n mAvgPath ---->" + mAvgPath); new Thread () {public void run () {UseOpensift obj = new UseOpensift (); mTempData = obj. getFeature (mPicPath, mVecPath, mAvgPath); imageRecognition (mTempData); // submit data }}. start ();}}

?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.