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.
Related
I am a beginner learning android development and I started learning about permissions but it is not working nor appearing in the emulator and when I go to the settings of the apps it is showing that there are no permissions asked for this app can anyone help me, please
the Actvity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnOPenCamera;
private ImageView imgPhotoFromCamera;
private ConstraintLayout parent;
private static final int PERMISSION_REQUEST_CODE = 909;
private static final int OPEN_CAMERA_INTENT = 808;
private static final int OPEN_SETTINGS_INTENT = 707;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOPenCamera = findViewById(R.id.btnOPenCamera);
imgPhotoFromCamera = findViewById(R.id.imgPhotoFromCamera);
parent = findViewById(R.id.parent);
btnOPenCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handlePermession();
}
});
}
private void handlePermession(){
if (ActivityCompat.checkSelfPermission(this , Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "handlePermession: it is working");
openCamera();
}else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)){
showSnackBar();
}else{
Log.d(TAG, "handlePermession: it is working in the request");
ActivityCompat.requestPermissions(this , new String[] {Manifest.permission.CAMERA} , PERMISSION_REQUEST_CODE);
}
}
}
private void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , OPEN_CAMERA_INTENT);
}
private void showSnackBar(){
Snackbar.make(parent , "This app need your permission to the camera" , BaseTransientBottomBar.LENGTH_INDEFINITE)
.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent , OPEN_SETTINGS_INTENT );
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA_INTENT:
if (resultCode == PackageManager.PERMISSION_GRANTED && data != null){
Bundle bundle = data.getExtras();
if (null != bundle){
Bitmap bitmap =(Bitmap) bundle.get("data");
imgPhotoFromCamera.setImageBitmap(bitmap);
}
}
break;
case OPEN_SETTINGS_INTENT:
handlePermession();
break;
default:
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}else{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
and there are no errors in the logcat which is something confusing for me, Thanks
Your code seems to work for me. The only difference is that I have added the camera permission to the AndroidManifest.xml file
<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
...
<application ...>
...
</application>
</manifest>
I'm working on an app similar to a gallery, and I'm trying delete option. As suggested in other threads I tried to use media scan after deleting but for some unknown reason, it is not working. The file is getting deleted but in my app, it is showing a file is still there.
In other Gallery APPS I can see the file being deleted, but even after uninstalling my app and re-installing, in list file is available but on click of it I get an empty screen for preview.
This is my activity :
package com.example.sumukha.galleri.Activities;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.example.sumukha.galleri.Adapter.FullScreenImageAdapter;
import com.example.sumukha.galleri.R;
import com.example.sumukha.galleri.Utils.Function;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
public class FullScreenImageActivity extends AppCompatActivity {
ArrayList<HashMap<String, String>> imageList = new ArrayList<HashMap<String, String>>();
String imagePath;
int position;
ArrayList<String> allPaths;
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_image);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
imageList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("list");
imagePath = getIntent().getStringExtra("path");
position = getIntent().getIntExtra("position",0);
viewPager = findViewById(R.id.media_pager);
updatePageTitle(position);
allPaths = new ArrayList<>();
System.out.println("******* imageList.size() "+imageList.size());
for(int i=0; i<imageList.size();i++){
allPaths.add(imageList.get(i).get(Function.KEY_PATH));
System.out.println("******* path at "+i+" is "+imageList.get(i).get(Function.KEY_PATH));
}
adapter = new FullScreenImageAdapter(FullScreenImageActivity.this,
allPaths);
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(position);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
updatePageTitle(position);
imagePath = imageList.get(position).get(Function.KEY_PATH);
System.out.println("******* new path "+imagePath);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void updatePageTitle(int position) {
getSupportActionBar().setTitle(getString(R.string.of, (position+1), imageList.size()));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
this.finish();
return true;
case R.id.action_share :
shareImage(imagePath);
//Toast.makeText(FullScreenImageActivity.this,"ABt to share",Toast.LENGTH_SHORT).show();
break;
case R.id.action_settings :
Toast.makeText(FullScreenImageActivity.this,"ABt d pic..",Toast.LENGTH_SHORT).show();
break;
case R.id.fav_image :
Toast.makeText(FullScreenImageActivity.this,"Mark himmmm",Toast.LENGTH_SHORT).show();
break;
case R.id.delete_image :
deleteImage(imagePath);
//Toast.makeText(FullScreenImageActivity.this,"ABt to delete",Toast.LENGTH_SHORT).show();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.viewimage_menu, menu);
return true;
}
public void shareImage(String filePath){
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
Uri uri = Uri.fromFile(new File(filePath));
share.putExtra(Intent.EXTRA_STREAM, Uri.parse(String.valueOf(uri)));
startActivity(Intent.createChooser(share, "Share Image"));
Uri.fromFile(new File(filePath));
}
public void deleteImage(String filePath) {
System.out.println("******* imgpth recvd to delete "+filePath);
//String file_dj_path = filePath;
String smallPath = filePath.substring(19);
File fdelete = new File(Environment.getExternalStorageDirectory()+smallPath);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("******* imgpth deleted "+filePath);
callBroadCast();
} else {
System.out.println("******* imgpth not deleted "+filePath);
}
}
}
public void callBroadCast() {
if (Build.VERSION.SDK_INT >= 14) {
System.out.println("******* callBroadCast > 14");
MediaScannerConnection.scanFile(this, new String[]{Environment.getExternalStorageDirectory().toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
/*
* (non-Javadoc)
* #see android.media.MediaScannerConnection.OnScanCompletedListener#onScanCompleted(java.lang.String, android.net.Uri)
*/
public void onScanCompleted(String path, Uri uri) {
System.out.println("******* Scanned "+path);
System.out.println("******* uri "+uri);
}
});
} else {
System.out.println("******* SDK < 14 ");
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
}
}
I am fairly new to android studio and developing with android. I have been trying this for months now, I need to record and save a video using Google Glass. The code that I currently have follows. This is code inspired from https://developers.google.com/glass/develop/gdk/camera#images
When I run this process, the video will start recording and then when the recording is stopped, it will give me the option "tap to accept" When I tap, nothing happens. I understand this is because my method "processVideoWhenReady" does absolutely nothing.
I would like to know if anyone could help me with what I should include in that method to save the video and allow it to be viewed by the user within my application.
Any literature or websites that have useful information about developing for Google Glass would also be a huge help if possible. Google's documentation doesn't seem very helpful to me and very limited.
import android.app.Activity;
import android.graphics.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.content.Intent;
import android.os.FileObserver;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.VideoView;
import com.google.android.glass.content.Intents;
import com.google.android.glass.widget.CardBuilder;
import java.io.File;
import java.io.IOException;
public class RecordActivity extends Activity {
private static final int CAMERA_VID_REQUEST = 1337;
static final int REQUEST_VIDEO_CAPTURE = 1;
public VideoView mVideoView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_record);
takeVideo();
}
private void takeVideo(){
Intent startVideo = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (startVideo.resolveActivity(getPackageManager()) != null){
startActivityForResult(startVideo, REQUEST_VIDEO_CAPTURE);
}
//RecordActivity.this.startActivityForResult(startVideo, CAMERA_VID_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
//System.out.println("Entered onActivityResult() method");
String a = getIntent().getStringExtra("record");
System.out.println(a);
if(requestCode == CAMERA_VID_REQUEST && resultCode == RESULT_OK) {
//System.out.println("Result Okay");
Uri videoUri = data.getData();
mVideoView.setVideoURI(videoUri);
String videoPath = data.getStringExtra(Intents.EXTRA_VIDEO_FILE_PATH);
processVideoWhenReady(videoPath);
}
super.onActivityResult(requestCode, resultCode, data);
}
protected void processVideoWhenReady(final String videoPath){
final File videoFile = new File(videoPath);
if (videoFile.exists()){
//Process Video
}
else {
final File parentDirectory = videoFile.getParentFile();
FileObserver observer = new FileObserver(parentDirectory.getPath(), FileObserver.CLOSE_WRITE | FileObserver.MOVED_TO) {
private boolean isFileWritten;
#Override
public void onEvent(int event, String path) {
if (!isFileWritten) {
//make sure file was created in directory expected
File affectedFile = new File(parentDirectory, path);
isFileWritten = affectedFile.equals(videoFile);
if (isFileWritten) {
stopWatching();
runOnUiThread(new Runnable() {
#Override
public void run() {
processVideoWhenReady(videoPath);
}
});
}
}
}
};
observer.startWatching();
}
}
}
I'm doing a aplication to recorder the sound, but when I try to record the sound,the emulator is stopped because it ask me to insert an SD card. What I have to do? I couldn't do without an SD card ?
Thank you!
package proiektua.proiektua;
import java.io.FileDescriptor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
int peticion = 1;
Uri url1;
private int STATE_CONFIGURE;
private int mState = STATE_CONFIGURE;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void grabar(View v) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(intent, peticion);}
public void setOutputFile(FileDescriptor fd) {
switch (mState) {
case STATE_RECORD:
throw new RuntimeException("setOutputFile cannot be called while recording!");
case STATE_RELEASED:
throw new RuntimeException("setOutputFile called on an already released recorder!");
default:
break;
}
}
public void reproducir(View v) {
MediaPlayer mediaPlayer = MediaPlayer.create(this, url1);
mediaPlayer.start();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK && requestCode == peticion) {
url1 = data.getData();
}
}
}
You have the option to create an SDCard through the mksdcard command and associate it with the amulator.
please look at this function:
public void setOutputFile (FileDescriptor fd)
Added in API level 3
Pass in the file descriptor of the file to be written. Call this after setOutputFormat() but before prepare().
You can decide where to store the file.
also look at this example.
http://androidfreakers.blogspot.co.il/2011/09/using-mediarecorder.html
I am creating an intent to play videos stored in the sdcard. It happens that I play the first one, everything is OK. But when I play another one, it just plays everytime the first one I played. Here is my code:
package com.remote;
import java.io.File;
import java.io.IOException;
import com.remote.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.VideoView;
public class MyVideos extends Activity{
private String path="/sdcard/Movies/Telmex";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.myvideos);
createLinks(new File(path));
}
public void createLinks(File path)
{
LinearLayout layout = (LinearLayout) findViewById(R.id.myvideoslayout);
if( path.exists() ) {
File[] files = path.listFiles();
for(int i=0; i<files.length; i++)
{
if(files[i].getName().toString().charAt(0)!='.')
{
String videoName;
Button video=new Button(this);
video.setBackgroundColor(2);
video.setTextSize(23);
video.setCompoundDrawablesWithIntrinsicBounds(0,0,drawable.videoicon,0);
videoName=new String(files[i].getName());
video.setText(videoName);
createListener(video,videoName);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(video,p);
}
}
}
}
public void createListener(Button video, final String name)
{
video.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
videoPlayer(path,name,true);
}
});
}
public void videoPlayer(String path, String fileName, boolean autoplay)
{
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
Uri data = Uri.parse(path+"/"+fileName);
intent.setDataAndType(data, "video/mp4");
startActivity(intent);
}
}
Rewrite
I did some digging and wrote the code below, if this has the same problem then it is your external video player not you app.
public class ExampleActivity extends Activity {
// Change this path
private final String path = Environment.getExternalStorageDirectory() + "/android/data/com.example/files/";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
File dir = new File(path);
List<String> files = new ArrayList<String>();
Collections.addAll(files, dir.list());
Collections.sort(files);
while(files.get(0).startsWith("."))
files.remove(0);
ListView listView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, files);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String uri = path + ((TextView) view).getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(uri), "video/*");
startActivity(intent);
}
});
}
}
Addition
I'm glad the internal video player works. The reason why it resets is that every time you change orientation the OS destroys and rebuilds your app from scratch... It's the same as if you exited the app by pressing the back button and ran it again. If you are using the tutorial from below, you need to save the video's location in onDestroy() to a class variable and in your onCreate() check to see if that variable has a valid location or just start at the beginning of the video.