Play a success sound ONLY when Activity is complete - java

I have created an app that you could share images with them. I have set a notification sound when the sharing process is done. However, if I hit Cancel/Back buttons, the sound still plays.
In my code below, I have set a share button, once you click on it, you can share a bitmap of the image through the basic sharing app of android.
How can I set the sound to ONLY play when the sharing is complete.
Thanks,
Safi
Here's my code:
shareBtn = findViewById(R.id.shareButton);
shareBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.startAnimation(animTranslate);
shareDigitalCard();
}
});
private void shareDigitalCard() {
if (ActivityCompat.checkSelfPermission(MyMenu.this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
try {
makeStorageRequest();
} catch (Exception e) {
e.printStackTrace();
}
}else {
Bitmap viewBmp = Bitmap.createBitmap(mPager.getWidth(),
mPager.getHeight(), Bitmap.Config.ARGB_8888);
viewBmp.setDensity(mPager.getResources().getDisplayMetrics().densityDpi);
Canvas canvas = new Canvas(viewBmp);
//mPager.layout(0, 0 , mPager.getLayoutParams().width, mPager.getLayoutParams().height);
mPager.draw(canvas);
path = String.valueOf(saveTempBitmap(viewBmp));
shareImage(path);
}
}
private void shareImage(String file) {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
File imageFileToShare = new File(file);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
try {
startActivityForResult(Intent.createChooser(share, "Share Image!"),123);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 123){
if (isSoundEnable) {
MediaPlayer player = null;
if (player == null) {
player = MediaPlayer.create(this, R.raw.success);
final MediaPlayer finalPlayer = player;
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer(finalPlayer);
}
});
}
player.start();
}
} else {
Toast.makeText(this, "An Error Has Occured !", Toast.LENGTH_SHORT).show();
}
}

You cannot get this event. The sharing procedure depends on the other App and you haven't any control or result from it. What you know is just you have send an Intent to a specific App, but what it does it's all up to it.

Related

Repeat method with OnActivityResult every X seconds

I have a method that takes a picture and then in the onActivityResult passes to another activity for subsequent analysis of the picture. So far so good.
My problem is that when I use a handler to repeat the process every 10 sec, the method is called but it will only take photos automatically without passing to the other activity. My guess is that when the method is called again automatically the onActivityResult is never called. Does anybody have a clue of which could may be be the problem?
takePhotoBtn.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
TakePhoto();
}
});
private void TakePhoto() {
Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagepath = new File(getFilesDir(), "images");
File newFile = new File(imagepath, ".jpg");
if (newFile.exists()) {
newFile.delete();
}else {
newFile.getParentFile().mkdir();
}
selectedPhotoPath = getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", newFile);
startActivityForResult(captureIntent, TAKE_PHOTO_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_REQUEST_CODE && resultCode == RESULT_OK) {
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(selectedPhotoPath);
bundle = new Bundle();
bundle.putParcelable(KEY_BITMAP, selectedPhotoPath);
}catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(this, "Unable to open image", Toast.LENGTH_LONG).show();
}
}
Intent intent = new Intent(this, Activity.class);
intent.putExtras(bundle);
startActivity(intent);
handler.postDelayed(new Runnable() {
#Override
public void run() {
TakePhoto();
handler.postDelayed(this, 10000);
}
},10000);
}
Any kind of help will be highly appreciated!!! Thanks

android - Google places opens the map on closes after 1 sec

Im creating an intent to an activity by clicking on a button which should open google places, but it closes again really fast and says no location selected, and returns to the main activity, and then nothing happens if i click again.
My api should be fine, I have checked that it's the correct SHA1-fingerprint thats connected to the api key.
The result code is 2
It worked earlier in the activity before this one, but I needed it to open when i click on a button instead, and now when I try to open this new activity as an intent it wont work.
public class MapActivity extends AppCompatActivity {
int PLACE_PICKER_REQUEST = 1;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events);
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (status != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
GooglePlayServicesUtil.getErrorDialog(status, this,
100).show();
}
}
if (status == ConnectionResult.SUCCESS) {
int PLACE_PICKER_REQUEST = 199;
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Context context = this;
try {
startActivityForResult(builder.build(context), PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
System.out.println("Result code: " + resultCode);
System.out.println("Request code: " + requestCode);
if (requestCode == 100) {
status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
}
if (requestCode == 199) {
//process Intent......
if (data != null) {
Place place = PlacePicker.getPlace(data, this);
String toastMsg = String.format("Place: %s", place.getName());
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
} else {
String toastMsg = ("No location selected.");
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();
}
}
}
}
This is from the intent which create the new intent to maps
public void onClick(View view) {
Intent i = new Intent(this, MapActivity.class);
startActivity(i);
}
I think its happening because of you are using old method of getPlace
try to swap the arguments, by changing it from:
Place place = PlacePicker.getPlace(data, this);
to
Place place = PlacePicker.getPlace(getContext(), data);
Update #2
Enable Google places API in the developer console and add these lines to AndroidManifest
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="ADD_YOUR_API_KEY_HERE" />
Update #3
after some search, it looks like there is others having same issue. Look at these links:
https://github.com/zhangtaii/react-native-google-place-picker/issues/21
https://stackoverflow.com/a/32751164/
https://github.com/googlesamples/android-play-places/issues/13

Error when trying to play audio file from URI

So I'm completely new to Android programming and I'm starting off by trying to make an app that allows users to edit audio files. Here is my code so far, which makes a user upload an audio file and play it:
public class MainActivity extends Activity {
final int ACTIVITY_CHOOSE_FILE = 1;
public String filePath;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) this.findViewById(R.id.uploadbutton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseFile;
Intent intent;
chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
chooseFile.setType("audio/mpeg");
intent = Intent.createChooser(chooseFile, "Choose a file");
startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);
}
});
Button playButton = (Button)findViewById(R.id.playbutton);
playButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), Uri.parse(filePath));
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
}
});
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVITY_CHOOSE_FILE: {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
filePath = uri.getPath();
getFilePath(filePath);
TextView URI_Text = (TextView)findViewById(R.id.file_URI);
URI_Text.setText(filePath);
}
}
}
}
public String getFilePath (String filePath) {
return filePath;
}
}
However, I'm getting the error code E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab756e00
What am I doing wrong?
That error is not related to any of your code from your question. However, you are going wrong in other places.
getPath() is useless. The Uri should be treated as an opaque handle. Calling getPath() on a Uri, and expecting a file to be at that path, is akin to expecting there to be a /questions/33843271/error-when-trying-to-play-audio-file-from-uri path on your computer's hard drive, just because your browser happens to be showing a URL with that path.
Also, your access to the data represented by that Uri is short-lived. This is reminiscent of Web development, where you might be able to stream data from some URL for a while, but eventually your session times out. Saving the Uri is pointless. Either consume the data now (via a ContentResolver and openInputStream()), or don't bother with the data at all.

How do I set the Camera Intent as the Main Activity

I want to launch the camera once a user opens up my application.
Right now I have this, and it works fine. When the user launches my application, it automatically opens up the camera. However, then the user hits the "back" button after taking an image, it opens up a blank activity.
How do I get it to go back to the camera?
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_TAKE_PHOTO = 0;
// The URI of photo taken with camera
private Uri mUriPhotoTaken;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
takePhoto();
}
// Deal with the result of selection of the photos and faces.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
Uri imageUri;
if (data == null || data.getData() == null) {
imageUri = mUriPhotoTaken;
} else {
imageUri = data.getData();
}
Intent intent = new Intent(MainActivity.this, Result.class);
intent.setData(imageUri);
startActivity(intent);
}
}
// Launch the camera to allow the user to take a photo
public void takePhoto(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(intent.resolveActivity(getPackageManager()) != null) {
// Save the photo taken to a temporary file.
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File file = File.createTempFile("IMG_", ".jpg", storageDir);
mUriPhotoTaken = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mUriPhotoTaken);
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException e) {
Log.d("ERROR", e.getMessage());
}
}
}
}
Try to call takePhoto() method in the onStart() instead of onCreate() and then call the finish() method into the onStop().
Try it.
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(this, ActivityYouWantToOpen.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
}

android Media Player stream more than 1 URL

I'm using mediaPlayer in my Android application to stream an MP3 url from online. Instead of just playing the 1 url, how can I stream 5 urls to play one after the other? here's my code
Uri myUri = Uri.parse("https://db.tt/9nBgouRf");
final MediaPlayer sdrPlayer = new MediaPlayer();
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); //don't use prepareAsync for mp3 playback
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again", Toast.LENGTH_LONG).show();
}
play.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View v) {
sdrPlayer.start();
}
}
);
Just create a List to hold all of your URIs
Set up some class variables:
private int playlistPos = 0;
private List<Uri> myUris = new ArrayList<Uri>();
private MediaPlayer sdrPlayer = new MediaPlayer();
Set up a method for initialising the song:
public initSong(Uri myUri) {
try {
sdrPlayer.setDataSource(this, myUri);
sdrPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
sdrPlayer.prepare(); // don't use prepareAsync for mp3 playback
}
catch (IOException e) {
e.printStackTrace();
Toast.makeText(channelx.this,
"Please turn on WiFi and try again",
Toast.LENGTH_LONG).show();
}
}
Then in the onCreate()
myUris.add(Uri.parse("https://db.tt/9nBgouRf"));
// Add the others as well...
initSong(myUris.get(playlistPos);
sdrPlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
playlistPos++;
initSong(myUris.get(playlistPos));
sdrPlayer.start(); // Start it as well if you wish
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
sdrPlayer.start();
}
});

Categories

Resources