I want Save text speech as audio file with pause 5 seconds silent.I am aable to save text to mp3 file .I tried but i did not get anywhere .
Code to save text to mp3 file.i need to add silent 5 seconds.
HashMap<String, String> myHashRender = new HashMap();
String text="Name ,How are you.";//After Name i need to stop 5 seconds silent
String destFileName = Environment.getExternalStorageDirectory()+"/myfolder/tts.mp3";
myHashRender.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, text);
tts.synthesizeToFile(text, myHashRender, destFileName);
// TAKE PERMISSIONS RUNTIME TOO
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
if (StoragePermission && RecordPermission) {
Toast.makeText(MainActivity.this, "Permission Granted",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this,"Permission
Denied",Toast.LENGTH_LONG).show();
}
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
//Prepare RECORDER
String outputFile = Environment.getExternalStorageDirectory().getAbsolutePath() + "/recording.3gp";
private MediaRecorder myAudioRecorder = new MediaRecorder();
myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myAudioRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myAudioRecorder.setOutputFile(outputFile);
// START THE RECORDING
try {
myAudioRecorder.prepare();
myAudioRecorder.start();
// START YOUR TEXT_TO_SPEECH HERE
} catch (IllegalStateException ise) {
// make something ...
} catch (IOException ioe) {
// make something
}
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
// NOW TO STOP OR TO SAVE USE BELOW CODE
// when TTS is done playing, the OnUtteranceCompletedListener() get called automatically, for this your activity needs to IMPLEMENTS OnUtteranceCompletedListener
// It's callback // After 5 sec of TTS's speaking, file have saved
public void onUtteranceCompleted(String utteranceId) {
Log.i(TAG, utteranceId); //utteranceId == "SOME MESSAGE"
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
myAudioRecorder.stop();
myAudioRecorder.release();
myAudioRecorder = null;
Toast.makeText(getApplicationContext(), "Audio Recorder successfully", Toast.LENGTH_LONG).show();
}
}, 5000);
}
Related
I'm creating an application for recognizing landmarks.
When the image is recognized, the result should fall to onSuccess, but instead comes to onFailure.
The following message is displayed in the Log:
If you have not set up billing, please go to the Firebase Console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan= true
If you are specifying a debug API Key override and turning on API Key restrictions, make sure the restrictions are set up correctly.
When I click on the link I see the following page:
https://login.corp.google.com/request?s=firebase.corp.google.com:443/uberproxy/&d=https://firebase.corp.google.com/u/0/project/_/overview%3FpurchaseBillingPlan%3Dtrue%26upxsrf%3DAKKYJRc2HD6ROcy9V9DxnYxw-pd8yGnml-oEi37m5hKhkWurWQ:1557057663745&maxAge=1200&authLevel=2000000&keyIds=X-q,k02
What will I need to to do?
public class RecognizeLandmarks extends AppCompatActivity {
EditText mResultEt;
ImageView mPreviewIv;
TextView tvLName, tvLiD, tvLConfidence, tvLlatitude, tvLlongitude;
public static final int CAMERA_REQUEST_CODE = 200;
public static final int STORAGE_REQUEST_CODE = 400;
public static final int IMAGE_PIC_GALLERY_CODE = 1000;
public static final int IMAGE_PIC_CAMERA_CODE = 1001;
private static final String TAG = "MyLog";
String cameraPermission[];
String storagePermission[];
Uri image_uri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recognize_landmarks);
androidx.appcompat.app.ActionBar actionBar = getSupportActionBar();
actionBar.setSubtitle("Click image button to insert Image");
mResultEt = findViewById(R.id.resultEt);
mPreviewIv = findViewById(R.id.imageIv);
tvLName = findViewById(R.id.tvLName);
tvLiD = findViewById(R.id.tvLiD);
tvLConfidence = findViewById(R.id.tvLConfidence);
tvLlatitude = findViewById(R.id.tvLlatitude);
tvLlongitude = findViewById(R.id.tvLlongitude);
//camera permission
cameraPermission = new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
//storage permission
storagePermission = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//inflate menu
getMenuInflater().inflate(R.menu.menu_recognize_text, menu);
return true;
}
//handle actionbar item clicks
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId( );
if (id == R.id.addImage) {
showImageImportDialog( );
}
if (id == R.id.settings) {
Toast.makeText(this, "Settings", Toast.LENGTH_SHORT).show( );
}
return super.onOptionsItemSelected(item);
}
private void showImageImportDialog() {
// items to display in dialog
String[] items = {" Camera", " Gallery"};
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("Select Image");
dialog.setItems(items, new DialogInterface.OnClickListener( ) {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (i == 0) {
//camera option clicked
/*for os Marshmallow and above we need to ask runtime permission for camera and storage*/
if (!checkCameraPermission()) {
//camera permission not allowed, request it
requestCameraPermission();
} else {
//permission allowed, take picture
pickCamera();
}
}
if (i == 1) {
//gallery option clicked
if (!checkStoragePermission()) {
//storage permission not allowed, request it
requestStoragePermission();
} else {
//permission allowed, take picture
pickGallery();
}
}
}
});
dialog.create().show();
}
private void pickGallery() {
//intent to pick image from gallery
Intent intent = new Intent(Intent.ACTION_PICK);
//set intent type to image
intent.setType("image/*");
startActivityForResult(intent, IMAGE_PIC_GALLERY_CODE);
}
private void pickCamera() {
//intent to take image from camera, it will also be save to storage to get high quality image
ContentValues values = new ContentValues( );
values.put(MediaStore.Images.Media.TITLE, "NewPic"); //title of the picture
values.put(MediaStore.Images.Media.DESCRIPTION, "Image to text"); //description
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PIC_CAMERA_CODE);
}
private void requestStoragePermission() {
ActivityCompat.requestPermissions(this, storagePermission, STORAGE_REQUEST_CODE);
}
private boolean checkStoragePermission() {
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result;
}
private void requestCameraPermission() {
ActivityCompat.requestPermissions(this, cameraPermission, CAMERA_REQUEST_CODE);
}
private boolean checkCameraPermission() {
/*Check camera permission and return the result
* in order to get high quality image we have to save image to external storage first
* before inserting to image view that`s why storage permission will also be required */
boolean result = ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) == (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == (PackageManager.PERMISSION_GRANTED);
return result && result1;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (cameraAccepted && writeStorageAccepted) {
pickCamera();
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
case STORAGE_REQUEST_CODE:
if (grantResults.length > 0) {
boolean writeStorageAccepted = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
if (writeStorageAccepted) {
pickGallery( );
}
else {
Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show( );
}
}
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//got image from camera or gallery
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PIC_GALLERY_CODE) {
//got image from gallery now crop it
CropImage.activity(data.getData( ))
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
if (requestCode == IMAGE_PIC_CAMERA_CODE) {
//got image from camera crop it
CropImage.activity(image_uri)
.setGuidelines(CropImageView.Guidelines.ON) // enable image guidelines
.start(this);
}
}
//get cropped image
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result1 = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result1.getUri( ); // get image uri
//set image to image view
mPreviewIv.setImageURI(resultUri);// past image in iV
//get drawable bitmap for text recognition
BitmapDrawable bitmapDrawable = (BitmapDrawable) mPreviewIv.getDrawable( );
Bitmap bitmap = bitmapDrawable.getBitmap( );
FirebaseVisionImage image = FirebaseVisionImage.fromBitmap(bitmap);
FirebaseVisionCloudDetectorOptions options =
new FirebaseVisionCloudDetectorOptions.Builder( )
.setModelType(FirebaseVisionCloudDetectorOptions.LATEST_MODEL)
.setMaxResults(15)
.build( );
FirebaseVisionCloudLandmarkDetector detector = FirebaseVision.getInstance( )
.getVisionCloudLandmarkDetector(options);
Task<List<FirebaseVisionCloudLandmark>> result = detector.detectInImage(image)
.addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionCloudLandmark>>( ) {
#Override
public void onSuccess(List<FirebaseVisionCloudLandmark> firebaseVisionCloudLandmarks) {
// Task completed successfully
// ...
for(FirebaseVisionCloudLandmark landmark : firebaseVisionCloudLandmarks) {
//Rect bounds = landmark.getBoundingBox();
String landmarkName = landmark.getLandmark( );
tvLName.setText(landmarkName);
String entityId = landmark.getEntityId( );
tvLiD.setText(entityId);
float confidence = landmark.getConfidence( );
tvLConfidence.setText(Float.toString(confidence));
// Multiple locations are possible, e.g., the location of the depicted
// landmark and the location the picture was taken.
for(FirebaseVisionLatLng loc : landmark.getLocations( )) {
double latitude = loc.getLatitude( );
tvLlatitude.setText(Double.toString(latitude));
double longitude = loc.getLongitude( );
tvLlongitude.setText(Double.toString(longitude));
}
}
}
})
.addOnFailureListener(new OnFailureListener( ) {
#Override
public void onFailure(#NonNull Exception e) {
// Task failed with an exception
// ...
Log.d(TAG,e.getMessage());
Toast.makeText(RecognizeLandmarks.this, "Recognizing Failed", Toast.LENGTH_SHORT).show( );
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
//if there is any error show it
Exception error = result1.getError( );
Toast.makeText(this, "" + error, Toast.LENGTH_SHORT).show( );
}
}
}
}
Result
D/MyLog: If you haven't set up billing, please go to Firebase console to set up billing: https://firebase.corp.google.com/u/0/project/_/overview?purchaseBillingPlan=true. If you are specifying a debug Api Key override and turned on Api Key restrictions, make sure the restrictions are set up correctly
ML Kit's landmark detection does not run on the device itself, but uses Google Cloud Vision. For this reason your project needs to be on a paid plan, before you can use landmark detection. The first 1000 calls are free, after which you will be charged for additional calls.
I'm having a problem with my application. The application is supposed to send a message using volume key buttons on the phone. The problem is that it keeps stopping and I do not know if it works. Here is the code, I also added some wake lock in order for my app to stay active even when phone is locked.
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
sendMessage.setEnabled(true);
return true;
} else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) {
sendMessage.setEnabled(true);
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
Right now your code is not sending any messages when you press the volume key nor when you release it. You need to add this to your code:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
...
}
Also, you're missing n opening bracket on the final else of your onKeyDown()
I have followed the official documentation from here to display the location dialog to the user as our app doesn't work without location. The problem is that even when I press the OK button on the dialog, sometimes the onFailure of the task listener gets called, more importantly, even when onSuccess(LocationSettingsResponse locationSettingsResponse) does get called, I'm unable to immediately get the location details, the workaround I made is to create a separate thread to get the details in a loop. I need to know a simpler method to do this.
This took me over 2 days time and I still can't figure what's wrong in my code.
FusedLocationProviderClient client;
TextView textView;
boolean started = false;
double lat = 0;
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
client = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Log.e(tag, "no perm");
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else
work();
}
void work() {
if (!isLocationEnabled()) createLocationRequest();
else locationDetails();
}
int t = 0;
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e(tag, "activity result");
work();
}
void locationDetails() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
client.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
if(lat!=0)return;
lat = location.getLatitude();
textView.setText("location: lat" + lat + " lng" + location.getLongitude());
Log.e(tag, "happy");
} else {
repeatedRequests();
Log.e(tag, "null location");
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
} else work();
}
void createLocationRequest() {
final LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
final SettingsClient settingsclient = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = settingsclient.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
repeatedRequests();
Log.e(tag, "success");
}
});
task.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
Log.e(tag, "failure" + e.getLocalizedMessage());
// repeatedRequests();
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(MainActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
Log.e(tag, "erorr " + sendEx.getLocalizedMessage());
// Ignore the error.
}
}
}
});
}
void repeatedRequests() {
if (!started) {
started = true;
Log.e(tag, "Thread started");
new Thread(new Runnable() {
#Override
public void run() {
while (lat == 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
t++;
if (t > 50) break;
Log.e(tag, "repeat");
runOnUiThread(new Runnable() {
#Override
public void run() {
locationDetails();
}
});
}
}
}).start();
}
}
boolean isLocationEnabled() {
int locationMode = 0;
try {
locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
}
Try to set mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
just for yours samsung, in my case it works but keep in the mind that locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) will return false in this case.
getLastLocation()
it works when there is at least one subscriber to the google service..
You need to subscribe, and if you do not need to constantly update the coordinates, you can immediately unsubscribe...
val client = LocationServices.getFusedLocationProviderClient(this)
client.requestLocationUpdates(locationRequest, object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult?) {
val location = locationResult?.lastLocation
//job.invoke()
client.removeLocationUpdates(this)
}
}, Looper.myLooper())
There is camera codes in my project that another developer who wrote. It takes photo by the device camera but it doesn't save photo in a file of device. It must to save the photo in a file of mobile device. I post here java class and other codes that is related with camera. How can save the photo in device?
SendMessagePage.java
public class SendMessagePage extends BaseActivity {
private static final int CAMERA_RQ = 6969;
private static final int PERMISSION_RQ = 84;
File saveDir = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
}
final MaterialCamera materialCamera =
new MaterialCamera(this)
.saveDir(saveDir)
.showPortraitWarning(true)
.allowRetry(true)
.defaultToFrontFacing(true)
.allowRetry(true)
.autoSubmit(false)
.labelConfirm(R.string.mcam_use_video);
LinearLayout takePhoto = (LinearLayout) findViewById(R.id.take_photo);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(SendMessagePage.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
} else {
if (1 == 2) {
}
ActivityCompat.requestPermissions(SendMessagePage.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 23
);
}
}
saveDir = new File(Environment.getExternalStorageDirectory(), "MaterialCamera");
saveDir.mkdirs();
materialCamera
.stillShot() // launches the Camera in stillshot mode
.labelConfirm(R.string.mcam_use_stillshot);
materialCamera.start(CAMERA_RQ);
}
});
}
private String readableFileSize(long size) {
if (size <= 0) return size + " B";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.##").format(size / Math.pow(1024, digitGroups))
+ " "
+ units[digitGroups];
}
private String fileSize(File file) {
return readableFileSize(file.length());
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Received recording or error from MaterialCamera
if (requestCode == CAMERA_RQ) {
if (resultCode == RESULT_OK) {
final File file = new File(data.getData().getPath());
Toast.makeText(
this,
String.format("Saved to: %s, size: %s", file.getAbsolutePath(), fileSize(file)),
Toast.LENGTH_LONG)
.show();
} else if (data != null) {
Exception e = (Exception) data.getSerializableExtra(MaterialCamera.ERROR_EXTRA);
if (e != null) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onRequestPermissionsResult(
int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(
this,
"Videos will be saved in a cache directory instead of an external storage directory since permission was denied.",
Toast.LENGTH_LONG)
.show();
}
}
Define this in your class
private static final int CAMERA_REQUEST = 1888;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
Uri picUri;
File imagefile;
Use the below code for capturing picture. The picture is saved in DCIM folder
takePicture.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
} else {
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
String pictureName = getPictureName();
imagefile = new File(pictureDirectory, pictureName);
picUri = Uri.fromFile(imagefile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
imageView.setImageURI(picUri);
}
}
private String getPictureName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
nameOfFile=timestamp + ".jpg";
return timestamp + ".jpg";
}
NOTE: This code is working and has no errors as i have used this code in one of my projects. It has been extracted from code of mine.
I am trying to use this code snippets to upload file to the server and is giving me failed to create directory. please help
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;
private static int SELECT_FILE = 3;
private static final int MEDIA_TYPE_IMAGE = 1;
private static final int MEDIA_TYPE_VIDEO = 2;
private Uri fileUri; // file url to store image/video
private void OperationType() {
final CharSequence[] items = { "Video", "Gallery","Photo",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(AdvertiserDashBoard.this);
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Video")) {
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support video camera\nplease choose Ads from your gallery",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
}else{
recordVideo();
}
} else if (items[item].equals("Gallery")) {
chooseImageFile();
}else if (items[item].equals("Photo")) {
if (!isDeviceSupportCamera()) {
Toast.makeText(getApplicationContext(),
"Sorry! Your device doesn't support camera\nplease choose Ads from your gallery",
Toast.LENGTH_LONG).show();
// will close the app if the device does't have camera
}else{
captureImage();
}
}
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
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);
}
private void chooseImageFile() {
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
fileUri = getOutputMediaFileUri(SELECT_FILE);
intent.setType("*/*");
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(Intent.createChooser(intent, "Select File"),
SELECT_FILE);
}
/**
* Launching camera app to record video
*/
private void recordVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// name
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"images");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("TAG", "Oops! Failed create "
+ "images" + " 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 if (type == SELECT_FILE) {
// mediaFile = new File(mediaStorageDir.getPath() + File.separator
// + "VID_" + timeStamp + ".mp4");
// }
else {
return null;
}
return mediaFile;
}
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;
}
}
#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
// launching upload activity
launchUploadActivity(true);
} 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();
}
} else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// video successfully recorded
// launching upload activity
launchUploadActivity(false);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"User cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(AdvertiserDashBoard.this, UploadLiveActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle("newBundy", newBundy);
outState.putParcelable("file_uri", fileUri);
// Save the state of the WebView
m_webview.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
savedInstanceState.getBundle("newBundy");
fileUri = savedInstanceState.getParcelable("file_uri");
// Restore the state of the WebView
m_webview.restoreState(savedInstanceState);
}
Button that trigger file choose type
case R.id.btnAdsSubmit:
OperationType();
break;
default:
Please correct me i do not know what am doing wrong with code snippet
The Goal of this snippet is to choose file from Main activity and send the url to second activity for preview. from second activity user can trigger upload button to upload the file to the server.