简体   繁体   English

如何在android中使用计时器,这会导致程序在按下按钮时运行2分钟,然后在两分钟后自动停止

[英]how to use a timer in android which causes a program to run for 2 minutes when a button is pressed and then stop automatically after two minutes

I am making an app in which i have a button which clicks pictures.Till here I have done.Now I want that the user can take pictures for only two minutes after clicking the button.And also he has to take 5 pictures.So if the timer expires and 5 pics are not taken then restart the camera or else save the picture.I don't understand how to automatically stop a timer after two minutes. 我正在制作一个应用程序,其中有一个单击图片的按钮。到此为止,我已经完成了。现在我希望用户单击该按钮后只能在两分钟内拍摄照片,而且他还必须拍摄5张照片。计时器到期且无法拍摄5张照片,然后重新启动相机或保存图片。我不知道如何在两分钟后自动停止计时器。

Please guide.I am new to android. 请指导。我是android新手。

package com.mycamera2;



public class MainActivity extends ActionBarActivity
{
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

// directory name to store captured images and videos
private static final String IMAGE_DIRECTORY_NAME = "Car Camera";
private Uri fileUri; // file url to store image/video
private ImageView imgPreview;
private Button btnCapturePicture;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imgPreview = (ImageView) findViewById(R.id.imgPreview);
    btnCapturePicture = (Button) findViewById(R.id.btnCapturePicture);
    btnCapturePicture.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            // capture picture
            captureImage();
        }
    });
    // Checking camera availability
    if (!isDeviceSupportCamera())
    {
        Toast.makeText(getApplicationContext(),"Sorry! Your device doesn't support      camera",Toast.LENGTH_LONG).show();
        // will close the app if the device does't have camera
        finish();
    }
   }
  private boolean isDeviceSupportCamera()
  {
     if (getApplicationContext().getPackageManager().hasSystemFeature(   PackageManager.FEATURE_CAMERA))
    {
        // this device has a camera
        return true;
    } else
    {
        // no camera on this device
        return false;
    }
   }

private void captureImage()
{
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
    super.onSaveInstanceState(outState);
    outState.putParcelable("file_uri", fileUri);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
    super.onRestoreInstanceState(savedInstanceState);
    // get the file url
    fileUri = savedInstanceState.getParcelable("file_uri");
}
/**
 * Receiving activity result method will be called after closing the camera
 * */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE)
    {
        if (resultCode == RESULT_OK)
        {
            // successfully captured the image
            // display it in image view
            previewCapturedImage();
        } else if (resultCode == RESULT_CANCELED)
        {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),"User cancelled image capture", Toast.LENGTH_SHORT).show();
        } else
        {
            // failed to capture image
            Toast.makeText(getApplicationContext(),"Sorry! Failed to capture image", Toast.LENGTH_SHORT).show();
        }
    }
}

/**
 * Display image from a path to ImageView
 */
private void previewCapturedImage()
{
    try
    {
        imgPreview.setVisibility(View.VISIBLE);
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();
        // downsizing image as it throws OutOfMemory Exception for larger
        // images
        options.inSampleSize = 8;
        final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),options);
        imgPreview.setImageBitmap(bitmap);
    } catch (NullPointerException e)
    {
        e.printStackTrace();
    }
}

 /**
 * Creating file uri to store image/video
 */
public Uri getOutputMediaFileUri(int type)
{
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type)
{
    // External sdcard location
    String root = Environment.getExternalStorageDirectory().toString();
    //File myDir = new File(root + "/vanjasaved_images");
   // File mediaStorageDir = new File(root + "/.sidvanjasaved_images");
    File mediaStorageDir = new File(root + "/.external_sd");

    if (!mediaStorageDir.exists())
    {
        if (!mediaStorageDir.mkdirs())
        {
            Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
                    + IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }
    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE)
    {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator+ "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO)
    {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else
    {
        return null;
    }
    return mediaFile;
   }
} 

You can use android Timer Timer doc 您可以使用android Timer 计时器doc

Start timer when button is clicked 单击按钮时启动计时器

TimerTask timerTask = new TimerTask () {
    @Override
    public void run () {
        // your code here... check if 5 image taken and cancel the timer
    }
}; 
new Timer().schedule(timerTask, 2*60*1000);

I didn't test it, you can try it... every Url that you get in your activityResult , you put it in the ArrayList. 我没有测试过,您可以尝试一下...在activityResult中获得的每个网址,都将其放入ArrayList中。

/**
* flag to check if you have already lunched the handler
*/
private static boolean isHandlerLunched = false;  

/**
* Delay max to take 5 pictures
*
* @value in milliseconds
*/  
private static final int DELAY_MAX = 60*1000*2;

/**
* ArrayList<String> containing the URLS of the pictures
*/
private static ArrayList<String> pictureUrls = new ArrayList<String>();

/**
* open the camera activity for result
*/
private void captureImage()
{
// if it is the first click to take the first picture
if (!isHandlerLunched){
// initialize the list again
pictureUrls = new ArrayList<String>();
// lunch the handler to delay 
Handler handler = new Handler();
handler.postDelayed(new Runnable(){
                    public void run() {
                        //TODO the delay is finished , you do your staff of checking
                        // I propose you to add the URLs of each picture in an ArrayList<String>,
                        //  and here you check the size of this list
                        if (pictureUrls.size()<5) {
                           // do staff 
                        } else {
                          // do staff
                        }
                    }                   
                }, DELAY_MAX );
}
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM