MipcaActivityCapture代碼閱讀-surfaceview的生命周期

前言

源代碼來自http://blog.csdn.net/xiaanming/article/details/10163203,由于不懂surfaceDestroyed的調用時機,網上一般都說在surfaceview隱藏的時候調用,但是按back鍵、按home鍵、鎖屏、跳轉到另一個非完全覆蓋的activity是否會調用surfaceDestroyed,不是很清楚。 所以用打印日志的方式分析了下各個函數的執行調用過程。
很多surfaceview的demo中都用到了hasSurface,但是hasSurface又有什么作用呢?曾經深表懷疑,仔細分析過代碼才明白
四種方式的日志

back

進入MipcaActivityCapture這個activity
01-09 16:59:51.118:E/MipcaActivityCapture(25152): onCreate
01-09 16:59:51.141:E/MipcaActivityCapture(25152): onResume
01-09 16:59:51.141:E/MipcaActivityCapture(25152): hasSurface=false
01-09 16:59:51.259:E/MipcaActivityCapture(25152): surfaceCreated
01-09 16:59:51.259:E/MipcaActivityCapture(25152): initCamera

點back

01-09 16:59:54.102:E/MipcaActivityCapture(25152): onPause
01-09 16:59:54.227:E/MipcaActivityCapture(25152): surfaceDestroyed
01-09 16:59:54.391:E/MipcaActivityCapture(25152): onStop
01-09 16:59:54.399:E/MipcaActivityCapture(25152): onDestroy

home

進入MipcaActivityCapture這個activity
01-09 16:59:51.118:E/MipcaActivityCapture(25152): onCreate
01-09 16:59:51.141:E/MipcaActivityCapture(25152): onResume
01-09 16:59:51.141:E/MipcaActivityCapture(25152): hasSurface=false
01-09 16:59:51.259:E/MipcaActivityCapture(25152): surfaceCreated
01-09 16:59:51.259:E/MipcaActivityCapture(25152): initCamera

點home

01-09 17:28:47.196:E/MipcaActivityCapture(26547): onPause
01-09 17:28:47.321:E/MipcaActivityCapture(26547): surfaceDestroyed
01-09 17:28:47.704:E/MipcaActivityCapture(26547): onStop

鎖屏

進入MipcaActivityCapture這個activity
01-09 17:31:03.259:E/MipcaActivityCapture(26655): onCreate
01-09 17:31:03.282:E/MipcaActivityCapture(26655): hasSurface=false
01-09 17:31:03.282:E/MipcaActivityCapture(26655): onResume
01-09 17:31:03.438:E/MipcaActivityCapture(26655): surfaceCreated
01-09 17:31:03.438:E/MipcaActivityCapture(26655): initCamera

鎖屏(按關機鍵)

01-09 17:31:09.907:E/MipcaActivityCapture(26655): onPause
01-09 17:31:09.938:E/MipcaActivityCapture(26655): onStop

解鎖(按關機鍵)

01-09 17:35:51.509:E/MipcaActivityCapture(27383): onResume
01-09 17:35:51.509:E/MipcaActivityCapture(27383): hasSurface=true
01-09 17:35:51.509:E/MipcaActivityCapture(27383): initCamera

跳轉到一個非完全覆蓋的activity

進入MipcaActivityCapture這個activity
01-09 17:43:38.126:E/MipcaActivityCapture(27383): onCreate
01-09 17:43:38.165:E/MipcaActivityCapture(27383): onResume
01-09 17:43:38.165:E/MipcaActivityCapture(27383): hasSurface=false
01-09 17:43:38.251:E/MipcaActivityCapture(27383): surfaceCreated
01-09 17:43:38.251:E/MipcaActivityCapture(27383): initCamera

跳轉到一個非完全覆蓋的activity時

01-09 17:43:44.446:E/MipcaActivityCapture(27383): onPause
01-09 17:43:44.477: E/OtherActivity(27383):---------------onCreate--------------------
01-09 17:43:44.477: E/OtherActivity(27383):---------------onStart--------------------
01-09 17:43:44.477: E/OtherActivity(27383):---------------onResume--------------------

按back

01-09 17:43:50.954: E/OtherActivity(27383):---------------onPause--------------------
01-09 17:43:50.977:E/MipcaActivityCapture(27383): onResume
01-09 17:43:50.977: E/MipcaActivityCapture(27383):hasSurface=true
01-09 17:43:50.977:E/MipcaActivityCapture(27383): initCamera
01-09 17:43:51.954: E/OtherActivity(27383):---------------onStop--------------------
01-09 17:43:51.954: E/OtherActivity(27383):---------------onDestroy--------------------

總結

onPause會調用CameraManager.get().closeDriver();
surfaceCreated一般在OnResume之后調用,
按back或home都會調用surfaceDestroyed ,surfaceDestroyed在OnPause和OnStop之間調用。
但是鎖屏不會調用surfaceDestroyed,解鎖也不會調surfaceCreated
跳轉到一個非完全覆蓋的activity時也不會調surfaceDestroyed,返回時也不會調surfaceCreated

按back/home或者鎖屏都會調用OnPause,導致CameraManager.get().closeDriver();所以下次進入activity的時候要initCamera,這是怎么實現的呢?看下面這段代碼,展現了hasSurface的作用。

        if(hasSurface) {
            initCamera(surfaceHolder);
        }else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

鎖屏解鎖后hasSurface為true,調用initCamera。
按back或者home再回來時hasSurface為false,此時在onResume之后會調用surfaceCreated,在surfaceCreated里面會調用initCamera。
代碼
稍微改了下原代碼

view plain copy

派生到我的代碼片
派生到我的代碼片

package com.example.qr_codescan;  
  
import java.io.IOException;  
import java.util.Vector;  
  
import android.app.Activity;  
import android.app.AlertDialog;  
import android.app.Dialog;  
import android.content.Intent;  
import android.content.res.AssetFileDescriptor;  
import android.graphics.Bitmap;  
import android.media.AudioManager;  
import android.media.MediaPlayer;  
import android.media.MediaPlayer.OnCompletionListener;  
import android.os.Bundle;  
import android.os.Handler;  
import android.os.Vibrator;  
import android.util.Log;  
import android.view.SurfaceHolder;  
import android.view.SurfaceHolder.Callback;  
import android.view.SurfaceView;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.Toast;  
  
import com.google.zxing.BarcodeFormat;  
import com.google.zxing.Result;  
import com.mining.app.zxing.camera.CameraManager;  
import com.mining.app.zxing.decoding.CaptureActivityHandler;  
import com.mining.app.zxing.decoding.InactivityTimer;  
import com.mining.app.zxing.view.ViewfinderView;  
/** 
 * Initial the camera 
 * @author Ryan.Tang 
 */  
public class MipcaActivityCapture extends Activity implements Callback {  
  
    private static final String TAG = MipcaActivityCapture.class.getSimpleName();  
    private CaptureActivityHandler handler;  
    private ViewfinderView viewfinderView;  
    private boolean hasSurface;  
    private Vector<BarcodeFormat> decodeFormats;  
    private String characterSet;  
    private InactivityTimer inactivityTimer;  
    private MediaPlayer mediaPlayer;  
    private boolean playBeep;  
    private static final float BEEP_VOLUME = 0.10f;  
    private boolean vibrate;  
    Button btn;  
  
    /** Called when the activity is first created. */  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        Log.e(TAG, "onCreate");  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_capture1);  
        //ViewUtil.addTopView(getApplicationContext(), this, R.string.scan_card);  
        CameraManager.init(getApplication());  
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);  
          
        Button mButtonBack = (Button) findViewById(R.id.button_back);  
        mButtonBack.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View v) {  
                MipcaActivityCapture.this.finish();  
                  
            }  
        });  
        hasSurface = false;  
        inactivityTimer = new InactivityTimer(this);  
          
        btn=(Button) findViewById(R.id.btn1);  
        btn.setOnClickListener(new OnClickListener() {  
              
            @Override  
            public void onClick(View v) {  
  
                Intent intent=new Intent(MipcaActivityCapture.this, OtherActivity.class);  
                startActivity(intent);  
                  
            }  
        });  
    }  
  
    @Override  
    protected void onResume() {  
        Log.e(TAG, "onResume");  
        super.onResume();  
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);  
        SurfaceHolder surfaceHolder = surfaceView.getHolder();  
        Log.e(TAG, "hasSurface="+hasSurface);  
        if (hasSurface) {  
            initCamera(surfaceHolder);  
        } else {  
            surfaceHolder.addCallback(this);  
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);  
        }  
        decodeFormats = null;  
        characterSet = null;  
  
        playBeep = true;  
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);  
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {  
            playBeep = false;  
        }  
        initBeepSound();  
        vibrate = true;  
   
          
    }  
  
    @Override  
    protected void onPause() {  
        super.onPause();  
        if (handler != null) {  
            handler.quitSynchronously();  
            handler = null;  
        }  
        CameraManager.get().closeDriver();  
  
        Log.e(TAG, "onPause");  
    }  
  
    @Override  
    protected void onStop() {  
        // TODO Auto-generated method stub  
        super.onStop();  
        Log.e(TAG, "onStop");  
    }  
    @Override  
    protected void onDestroy() {  
        inactivityTimer.shutdown();  
        super.onDestroy();  
        Log.e(TAG, "onDestroy");  
    }  
      
    /** 
     * 處理掃描結果 
     * @param result 
     * @param barcode 
     */  
    public void handleDecode(Result result, Bitmap barcode) {  
        inactivityTimer.onActivity();  
        playBeepSoundAndVibrate();  
        String resultString = result.getText();  
        if (resultString.equals("")) {  
            Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();  
        }else {  
            Intent resultIntent = new Intent();  
            Bundle bundle = new Bundle();  
            bundle.putString("result", resultString);  
            bundle.putParcelable("bitmap", barcode);  
            resultIntent.putExtras(bundle);  
            this.setResult(RESULT_OK, resultIntent);  
        }  
        MipcaActivityCapture.this.finish();  
    }  
      
    private void initCamera(SurfaceHolder surfaceHolder) {  
  
        Log.e(TAG, "initCamera");  
        try {  
            CameraManager.get().openDriver(surfaceHolder);  
        } catch (IOException ioe) {  
            return;  
        } catch (RuntimeException e) {  
            return;  
        }  
        if (handler == null) {  
            handler = new CaptureActivityHandler(this, decodeFormats,  
                    characterSet);  
        }  
    }  
  
    @Override  
    public void surfaceChanged(SurfaceHolder holder, int format, int width,  
            int height) {  
  
    }  
  
    @Override  
    public void surfaceCreated(SurfaceHolder holder) {  
  
        Log.e(TAG, "surfaceCreated");  
        if (!hasSurface) {  
            hasSurface = true;  
            initCamera(holder);  
        }  
  
    }  
  
    @Override  
    public void surfaceDestroyed(SurfaceHolder holder) {  
        hasSurface = false;  
  
        Log.e(TAG, "surfaceDestroyed");  
  
    }  
  
    public ViewfinderView getViewfinderView() {  
        return viewfinderView;  
    }  
  
    public Handler getHandler() {  
        return handler;  
    }  
  
    public void drawViewfinder() {  
        viewfinderView.drawViewfinder();  
  
    }  
  
    private void initBeepSound() {  
        if (playBeep && mediaPlayer == null) {  
            // The volume on STREAM_SYSTEM is not adjustable, and users found it  
            // too loud,  
            // so we now play on the music stream.  
            setVolumeControlStream(AudioManager.STREAM_MUSIC);  
            mediaPlayer = new MediaPlayer();  
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);  
            mediaPlayer.setOnCompletionListener(beepListener);  
  
            AssetFileDescriptor file = getResources().openRawResourceFd(  
                    R.raw.beep);  
            try {  
                mediaPlayer.setDataSource(file.getFileDescriptor(),  
                        file.getStartOffset(), file.getLength());  
                file.close();  
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);  
                mediaPlayer.prepare();  
            } catch (IOException e) {  
                mediaPlayer = null;  
            }  
        }  
    }  
  
    private static final long VIBRATE_DURATION = 200L;  
  
    private void playBeepSoundAndVibrate() {  
        if (playBeep && mediaPlayer != null) {  
            mediaPlayer.start();  
        }  
        if (vibrate) {  
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);  
            vibrator.vibrate(VIBRATE_DURATION);  
        }  
    }  
  
    /** 
     * When the beep has finished playing, rewind to queue up another one. 
     */  
    private final OnCompletionListener beepListener = new OnCompletionListener() {  
        public void onCompletion(MediaPlayer mediaPlayer) {  
            mediaPlayer.seekTo(0);  
        }  
    };  
}  
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 曾經有一份美好的愛情放在我的面前我沒有珍惜。等到失去后才后悔莫及。如果可以再對小李說。毛欣想說。這輩子無緣再牽手。...
    毛欣與小李閱讀 2,661評論 0 13
  • 夏日的傍晚 你盯著一面鏡子 那里有一雙憂郁的眼神 是百無聊懶后的清澈 門前的廣場 兩個小孩并排走過望了你一眼 你的...
    一塵九九閱讀 198評論 2 0
  • 20年前,那時大學剛剛畢業,閑暇時間,我不去逛街購物,對衣服、包包、化妝品不感興趣,唯一吸引我的是,去電腦市場“欣...
    V騰飛閱讀 514評論 9 6
  • 連續靈修128天【經文】他祈禱耶和華,耶和華就允準他的祈求,垂聽他的禱告,使他歸回耶路撒冷,仍坐國位。瑪拿西這才知...
    喜樂付閱讀 5,768評論 0 0
  • 吟詩, 毋須模仿、毋須創作, 吟詩只是一種生活。 唱詞, 毋須刻意、毋須雕琢, 唱詞只是一腔烈火。 每天都是一首新...
    羽扇閑人閱讀 199評論 1 0