使用AsyncTask时的手电筒

时间:2016-06-12 05:33:53

标签: android flashlight

我正在尝试编写一个Flashlight应用程序。我想在应用程序上添加一个SOS按钮。我将从AsyncTask开始,可以停止while循环一次,但我不能再次运行它。我怎么能这样做?

MainActivity.java

sosbutton.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {

        if(AlertFlashlightWhile == 1){
            AlertFlashlightWhile = 0;
            sos.isCancelled();
        }
        else{
            AlertFlashlightWhile = 1;
            sos.execute(AlertFlashlightWhile);
        }
    }

SOS.java

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.AsyncTask;

public class sos extends AsyncTask<Integer, Integer, Integer> 
{
    @Override protected Integer doInBackground(Integer... playerNums) 
    {
        Camera camera;
        camera = Camera.open();

        final Parameters p = camera.getParameters();

        int AlertFlashLightWhile = playerNums [0];

        while(AlertFlashlightWhile == 1){
            p.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(p);
            camera.startPreview();

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            p.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(p);
            camera.stopPreview();

            if (isCancelled ()) {
                break;
            }
        }
        return AlertFlashlightWhile;
    }

    @Override protected void onProgressUpdate(Integer... test) 
    {
    }

    @Override protected void onCancelled ()
    {
    }

    @Override protected void onPostExecute (Integer test)
    {
    }
}

0 个答案:

没有答案