I need to use camera intent and keep track of the new images taken by the intent. As I need to take multiple photos at a time, I used the intent MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA
. Here is my code:
package com.arko.cameraintent;
import android.content.Intent;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.io.File;
public class CameraMainActivity extends AppCompatActivity {
private static final int REQ_CODE = 0;
AppCompatActivity main_activity = this; // save it for future use
DirectoryFileObserver directoryFileObserver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_main);
}
public void takePhoto(View view) // fired when a button in the main application is clicked. This starts the camera application.
{
Intent callCamAppIntent = new Intent();
callCamAppIntent.setAction(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
Toast.makeText(this, dir, Toast.LENGTH_SHORT).show();
directoryFileObserver = new DirectoryFileObserver(dir);
directoryFileObserver.startWatching();
startActivityForResult(callCamAppIntent, REQ_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE){
Toast.makeText(this, "picture taken successfully", Toast.LENGTH_SHORT).show();
directoryFileObserver.stopWatching();
}
}
}
The code of DirectoryFileObserver
class:
package com.arko.cameraintent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.FileObserver;
import android.support.annotation.Nullable;
import java.io.File;
public class DirectoryFileObserver extends FileObserver {
String rootDir;
static final int mask = (FileObserver.CREATE | FileObserver.MODIFY | FileObserver.DELETE);
public final String DIRECTORY_NAME = "Simplified Intent";
public DirectoryFileObserver(String path) {
super(path, mask);
rootDir = path;
}
@Override
public void onEvent(int event, @Nullable String path) {
switch(event){
case FileObserver.CREATE:
String outputDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator +
Environment.DIRECTORY_PICTURES +
File.separator + DIRECTORY_NAME;
// do something here
break;
case FileObserver.MODIFY:
// will be implemented later
break;
case FileObserver.DELETE:
// will be implemented later
break;
}
}
}
But the onEvent
function never gets executed, as suggested by Debug. What is the reason behind it? I have even changed the default save location of the camera application to Internal Storage (initially it was set to SD card) and ran my app again, but nothing changed. I have mentioned both READ_EXTERNAL_STORAGE
and WRITE_EXTERNAL_STORAGE
permissions in the manifest file.