I've made a music player usim MediaPlayer. When I close the app the song keeps playing but when I resume, onCreate is called everything starts again and previous song also keeps playing. So if now I start new song, both the songs play even though there's only one MediaPlayer variable. Why is onCreate called when app is reopened. What is the way to prevent it?
EDIT: Note that xml file also gets reset. PLus I loose control over song playing before leaving the app.
public class MainActivity extends AppCompatActivity {
SeekBar seekBar;
MediaPlayer mediaPlayer;
ImageView imageView;
Handler handler = new Handler();
private String[] mAudioPath;
private String[] mMusicList;
static int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button ctrl = (Button) findViewById(R.id.play);
Button stop = (Button) findViewById(R.id.stop);
imageView = (ImageView) findViewById(R.id.imageView);
ListView listView = (ListView) findViewById(R.id.listView);
seekBar = (SeekBar) findViewById(R.id.seekBar);
mediaPlayer = MediaPlayer.create(MainActivity.this,R.raw.song);
seekBar.setMax(mediaPlayer.getDuration());
//get tracks list
mMusicList = getAudioList();
mAudioPath = getmAudioPath();
ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mMusicList);
listView.setAdapter(mAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(MainActivity.this,mAudioPath[position],Toast.LENGTH_SHORT).show();
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(mAudioPath[position]);
mediaPlayer.prepare();
mediaPlayer.seekTo(0);
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setProgress(0);
ctrl.setText("║");
try {
byte[] art;
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(mAudioPath[position]);
art = mediaMetadataRetriever.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
imageView.setImageBitmap(songImage);
}
catch (Exception e){
byte[] art;
Bitmap songImage = BitmapFactory.decodeResource(getResources(), R.drawable.default_artwork);
imageView.getLayoutParams().width= ViewGroup.LayoutParams.MATCH_PARENT;
imageView.setImageBitmap(songImage);
}
mediaPlayer.start();
handler.postDelayed(runnable,1);
} catch (IOException e) {
e.printStackTrace();
}
}
});
//Get track data
MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(MainActivity.this, Uri.parse("android.resource://in.swapsha96.playtime/"+R.raw.song));
String artist;
artist = mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
if (artist == null)
artist = "Unknown Artist";
try {
byte[] art;
art = mediaMetadataRetriever.getEmbeddedPicture();
Bitmap songImage = BitmapFactory.decodeByteArray(art, 0, art.length);
imageView.setImageBitmap(songImage);
}
catch (Exception e){
imageView.setBackgroundColor(Color.BLACK);
}
Toast.makeText(MainActivity.this,artist,Toast.LENGTH_SHORT).show();
//Controls
ctrl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
ctrl.setText("║");
}
else {
mediaPlayer.pause();
ctrl.setText("►");
}
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(runnable,1);
}
});
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.pause();
mediaPlayer.seekTo(0);
ctrl.setText("►");
}
});
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(runnable);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(runnable);
mediaPlayer.seekTo(seekBar.getProgress());
handler.postDelayed(runnable,1);
}
});
}
//update seekBar
Runnable runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,1);
}
};
private String[] getAudioList() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
String[] mAudioPath = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
mAudioPath[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return songs;
}private String[] getmAudioPath() {
final Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.DISPLAY_NAME, MediaStore.Audio.Media.DATA }, null, null,
"LOWER(" + MediaStore.Audio.Media.TITLE + ") ASC");
int count = mCursor.getCount();
String[] songs = new String[count];
String[] path = new String[count];
int i = 0;
if (mCursor.moveToFirst()) {
do {
songs[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
path[i] = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
i++;
} while (mCursor.moveToNext());
}
mCursor.close();
return path;
}
}
As you know : onCreate(), onStart() and onResume() will be called when you start an Activity.So to avoid onCreate recall, you can use a boolean in your onCreate method for example isActivityReopened that is set to false, then set to true in the first use of onCreate. Here an example you can inspire from it :
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
// Other stuff
if (!isActivityReopened) {
// Run what do you want to do only once.
// To avoid onCreate() if it will be called a second time,
// so put the boolean to true
isActivityReopened = true;
}
}
In your code you are not checking whether the mediaplayer was playing or not every time you choose a new song.
if(mediaPlayer.isPlaying())
{mediaplyer.stop()}
you need to stop it and then reset it again.
try as well to set the launch mode in the Manifest file of the activitg tag to be singleTask.
<activity
android:name=".MainActivity"
android:launchMode="singleTask">
My advice for you if you want yourself to get out of all this is to use a bound service. It will help you managing the mediaplayer states and will keep running in the background. This great tutorial might help.
Related
I am using a GridView and universalimageloader (1.8.6) and seem to be encountering a memory leak - though maybe I am misinterpreting DDMS and MAT results? This is code I did not write, but it is pretty basic - we are showing a number of photos and allowing the user to select as many as they want and then storing those for future reference. The code seems to work fine, but in MAT "Leak Suspect" the GridView from below keeps on showing up, chewing upwards of 5 mb each time, even when I have called finish() on the Activity. From what I have read Android can keep the Activity in memory until it wants to release it (and have seen this with other Activities) but it never seems to want to release this one - even when I force GC. The "new thread" allocation looks a bit suspicious, but wouldn't that get dellocated with the calling Activity?
Probably just missing something obvious, but here is the code:
public class PhotoGalleryPickerActivity extends MyActivity {
private Boolean mMultiple = false;
GridView gridGallery;
Handler handler;
GalleryAdapter adapter;
ImageView imgNoMedia;
Button btnGalleryOk;
String action;
private ImageLoader imageLoader;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photo_gallery_picker);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("Photo Gallery Capture");
Bundle extras = getIntent().getExtras();
mMultiple = extras.getBoolean("multiple");
initImageLoader();
init();
}
private void initImageLoader() {
try {
String CACHE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/.temp_tmp";
new File(CACHE_DIR).mkdirs();
File cacheDir = StorageUtils.getOwnCacheDirectory(getBaseContext(), CACHE_DIR);
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.discCache(new UnlimitedDiscCache(cacheDir))
.memoryCache(new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
} catch (Exception e) {
Utilities.logException(e);
}
}
private void init() {
handler = new Handler();
gridGallery = (GridView) findViewById(R.id.gridGallery);
gridGallery.setFastScrollEnabled(true);
adapter = new GalleryAdapter(getApplicationContext(), imageLoader);
PauseOnScrollListener listener = new PauseOnScrollListener(imageLoader, true, true);
gridGallery.setOnScrollListener(listener);
if (mMultiple == true){
findViewById(R.id.llBottomContainer).setVisibility(View.VISIBLE);
gridGallery.setOnItemClickListener(mItemMulClickListener);
adapter.setMultiplePick(true);
}
else {
findViewById(R.id.llBottomContainer).setVisibility(View.GONE);
gridGallery.setOnItemClickListener(mItemSingleClickListener);
adapter.setMultiplePick(false);
}
gridGallery.setAdapter(adapter);
imgNoMedia = (ImageView) findViewById(R.id.imgNoMedia);
btnGalleryOk = (Button) findViewById(R.id.btnGalleryOk);
btnGalleryOk.setOnClickListener(mOkClickListener);
new Thread() {
#Override
public void run() {
Looper.prepare();
handler.post(new Runnable() {
#Override
public void run() {
adapter.addAll(getGalleryPhotos());
checkImageStatus();
}
});
Looper.loop();
};
}.start();
}
private void checkImageStatus() {
if (adapter.isEmpty()) {
imgNoMedia.setVisibility(View.VISIBLE);
} else {
imgNoMedia.setVisibility(View.GONE);
}
}
View.OnClickListener mOkClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<CustomGallery> selected = adapter.getSelected();
String[] photos = new String[selected.size()];
for (int i = 0; i < photos.length; i++) {
photos[i] = selected.get(i).sdcardPath;
}
Intent data = new Intent().putExtra("photos", photos);
if(photos.length == 0) {
data = null;
}
setResult(RESULT_OK, data);
finish();
}
};
AdapterView.OnItemClickListener mItemMulClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
adapter.changeSelection(v, position);
}
};
AdapterView.OnItemClickListener mItemSingleClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> l, View v, int position, long id) {
CustomGallery item = adapter.getItem(position);
String[] photos = new String[1];
photos[0] = item.sdcardPath;
Intent data = new Intent().putExtra("photos", photos);
setResult(RESULT_OK, data);
finish();
}
};
private ArrayList<CustomGallery> getGalleryPhotos() {
ArrayList<CustomGallery> galleryList = new ArrayList<CustomGallery>();
try {
String[] dirs = new String[1];
final String where = MediaStore.Images.Media.DATA + " not like ? ";
String mediaDir = GlobalState.getInstance().currentForm.mediaDirectory();
if (mediaDir != null) {
int slash = mediaDir.lastIndexOf("/");
dirs[0] = mediaDir.substring(0, slash) + "%";
}
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = null;
try {
if (mediaDir != null && mediaDir.trim().length() > 0) {
imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, where, dirs, orderBy);
}
else {
imagecursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
}
if (imagecursor != null && imagecursor.getCount() > 0) {
while (imagecursor.moveToNext()) {
CustomGallery item = new CustomGallery();
int dataColumnIndex = imagecursor
.getColumnIndex(MediaStore.Images.Media.DATA);
item.sdcardPath = imagecursor.getString(dataColumnIndex);
galleryList.add(item);
}
}
}
catch (Exception ex) {
Utilities.logException(ex);
Utilities.logError("PhotoGalleryPickerActivity", "getGalleryPhotos : " + ex.getMessage());
}
finally {
if (imagecursor != null) {
imagecursor.close();
}
}
} catch (Exception e) {
Utilities.logException(e);
e.printStackTrace();
}
// show newest photo at beginning of the list
Collections.reverse(galleryList);
return galleryList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
PhotoGalleryPickerActivity.this.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The MAT results, run from Eclipse, look like this. It shows all the various calls I have made to this Activity, as though none of them have been actually released:
The normal memory for the application hangs around 11-15mb, but as you can see it is now at ~50mb, and grows each time I call the activity. If all the memory for the suspects was reclaimed I think I would be right where I should be:
Finally, could this be a result of running from Eclipse remotely to the device? I saw something similar with another control and was not able to replicate. Whereas I am definitely able to replicate this.
Thanks!
Just to wrap this one up, the issue was the new Thread(), which was holding onto the resources and specifically the GridView (at +4mb per hit). My final solution was to just get rid of the thread and looper, and just call the two methods directly in the init() of the Activity. I have no idea why it was coded into a looping thread to begin with, though I suspect it may have been to update the list of images on the fly (or cut and pasted code that was not really understood). Anyway seems to be working and the memory is being successfully garage collected. Thanks to #dharms you the help!
Hi i'm still trying to make my wavPlayer. My apps has listitem that contain wav file. When I click a file, it should be played but it didn't. I've tried some way on OnListItemClick() to make it work (I marked it with double slash), but it still error. Most of error are nullpointer. Anybody can help me?
here's my code and log cat
public class PlayercobaActivity extends ListActivity implements View.OnClickListener {
private MediaCursorAdapter mediaAdapter = null;
PlayAudio playTask;
Button startRecordingButton, stopRecordingButton, startPlaybackButton,
stopPlaybackButton;
boolean isPlaying = false;
int frequency = 11025;
int channelConfiguration = AudioFormat.CHANNEL_CONFIGURATION_MONO;
int audioEncoding = AudioFormat.ENCODING_PCM_16BIT;
//File item ;
String item;
// File path = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Datarekaman/recording5.wav");
//Cursor acursor;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playercoba);
startPlaybackButton = (Button) this .findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
ContentResolver cr = getContentResolver();
Uri uri = MediaStore.Files.getContentUri("external");
String[] projection = null;
String sortOrder = null; // unordered
String selectionMimeType = MediaStore.Files.FileColumns.MIME_TYPE + "=?";
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension("wav");
String[] selectionArgsPdf = new String[]{ mimeType };
Cursor cursor = cr.query(uri, projection , selectionMimeType, selectionArgsPdf, sortOrder );
if(null != cursor)
{
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.listitem, cursor);
setListAdapter(mediaAdapter);
}
}
//#Override
public void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
//String name = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DISPLAY_NAME));
//item =(String) list.getItemAtPosition(position);
//File item = new File(name);
//item = new File();
//item = (String) view.getTag();
//item = (String) getListAdapter().getItem(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
//playTask = new PlayAudio();
//playTask.execute();
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
}
public void onClick(View v) {
if (v == startPlaybackButton) {
play();
} else if (v == stopPlaybackButton) {
stopPlaying();
}
}
public void play() {
startPlaybackButton.setEnabled(false);
playTask = new PlayAudio();
playTask.execute();
stopPlaybackButton.setEnabled(true);
}
public void stopPlaying() {
isPlaying = false;
stopPlaybackButton.setEnabled(false);
startPlaybackButton.setEnabled(true);
}
private class PlayAudio extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
isPlaying = true;
int bufferSize = AudioTrack.getMinBufferSize(frequency,
channelConfiguration, audioEncoding);
short[] audiodata = new short[bufferSize/4];
try {
DataInputStream dis = new DataInputStream(
new BufferedInputStream(new FileInputStream(item)));
AudioTrack audioTrack = new AudioTrack(
AudioManager.STREAM_MUSIC, frequency,
channelConfiguration, audioEncoding, bufferSize,
AudioTrack.MODE_STREAM);
audioTrack.play();
while (isPlaying && dis.available() > 0) {
int i = 0;
while (dis.available() > 0 && i < audiodata.length) {
audiodata[i] = dis.readShort();
i++;
}
audioTrack.write(audiodata, 0, audiodata.length);
}
dis.close();
startPlaybackButton.setEnabled(false);
stopPlaybackButton.setEnabled(true);
} catch (Throwable t) {
Log.e("AudioTrack", "Playback Failed");
}
return null;
}
protected void onPostExecute(Void result) {
startPlaybackButton.setEnabled(true);
stopPlaybackButton.setEnabled(false);
}
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[] { MediaStore.MediaColumns.DISPLAY_NAME},
new int[] { R.id.displayname});
}
}
}
LogCat
05-19 23:01:17.015 13752-13752/com.example.agita.playercoba E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.agita.playercoba.PlayercobaActivity.onListItemClick(PlayercobaActivity.java:93)
at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
at android.widget.AdapterView.performItemClick(AdapterView.java:301)
at android.widget.AbsListView.performItemClick(AbsListView.java:1287)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3078)
at android.widget.AbsListView$1.run(AbsListView.java:4159)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4947)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
at dalvik.system.NativeStart.main(Native Method)
if you are extending CursorAdapter, you can get the Cursor at position through the first argument of onListItemClick
Cursor cursor = (Cursor) list.getItemAtPosition(position);
item = cursor.getString(cursor. getColumnIndex(MediaStore. MediaColumns.DATA));
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
I am sending images and audio files to my php server. I am using Asynctask for this. I have two activities in my program. The problem is if I launch my second activity (AudioActivity) from MainActivity like this
upload_audio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AudioActivity.class);
startActivity(intent);
}
});
then when i click the button upload_audio the screen goes black but the process still running successfully . so if i make this audio activity my mainActivity then everything works perfect.so how can i make my app still visible during processing files while launching activity from MainActivity.hope you understand my question
here is my code of AudioActivity
public class AudioActivity extends Activity {
private static final int SELECT_AUDIO = 2;
String selectedPath = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
upload();
}
public void upload() {
ArrayList<Uri> fileName = getFileList(this);
for ( int i = 0 ; i < fileName.size() ; i++ )
{
try {
selectedPath = getPath(fileName.get(i)).toString();
System.out.println(getPath(fileName.get(i)));
new AudioSync(selectedPath).execute(getPath(fileName.get(i))).get();
// AudioSync sync = new AudioSync(getPath(fileName.get(i))).get;
//new AudioSync().execute("").get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Audio.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private ArrayList<Uri> getFileList(Context context) {
Cursor actualimagecursor = null;
ArrayList<Uri> fileList = new ArrayList<Uri>();
try
{
String[] proj = { MediaStore.Audio.Media.DATA, MediaStore.Audio.Media._ID };
actualimagecursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, proj,
null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
int actual_image_column_index = actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
for ( int i = 0 ; i < actualimagecursor.getCount() ; i++ )
{
actualimagecursor.moveToPosition(i);
String fileName = actualimagecursor.getString(actual_image_column_index);
fileList.add(( Uri.withAppendedPath( MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, fileName )));
}
return fileList;
}
catch ( Exception e )
{
return null;
}
}
}
You don't want to create an Activity for uploading or playing Audio. Activities are always linked with views and are use to interact with the user.
http://developer.android.com/guide/components/activities.html
You want to use a service to do that: http://developer.android.com/guide/components/services.html
i've got this Activity and as soon as i hit the home button during the playback of the sounds
the sounds keep playing and when the sound is finished it brings back the app.
public class View5 extends MasterView implements OnCompletionListener {
int[] tracks = new int[4];
int[] times = new int[4];
int currentTrack = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
InputStream stream = null;
try {
stream = getAssets().open("herzdruck_animiert2.gif");
} catch (IOException e) {
e.printStackTrace();
}
SharedPreferences settings = getSharedPreferences("settings", 0);
String lang = settings.getString("lang", "");
if (lang.equals("de")) {
tracks[0] = getResources().getIdentifier("raw/view5_1_de",
null, this.getPackageName());
tracks[1] = getResources().getIdentifier("raw/view5_2_de", null,
this.getPackageName());
tracks[2] = getResources().getIdentifier("raw/view5_3_de", null,
this.getPackageName());
tracks[3] = getResources().getIdentifier("raw/view5_4_de", null,
this.getPackageName());
} else if (lang.equals("tr")) {
tracks[0] = getResources().getIdentifier("raw/view5_1_tr",
null, this.getPackageName());
tracks[1] = getResources().getIdentifier("raw/view5_2_tr", null,
this.getPackageName());
tracks[2] = getResources().getIdentifier("raw/view5_3_tr", null,
this.getPackageName());
tracks[3] = getResources().getIdentifier("raw/view5_4_tr", null,
this.getPackageName());
} else if (lang.equals("en")) {
tracks[0] = getResources().getIdentifier("raw/view5_1_en",
null, this.getPackageName());
tracks[1] = getResources().getIdentifier("raw/view5_2_en", null,
this.getPackageName());
tracks[2] = getResources().getIdentifier("raw/view5_3_en", null,
this.getPackageName());
tracks[3] = getResources().getIdentifier("raw/view5_4_en", null,
this.getPackageName());
}
times[0] = 5000;
times[1] = 2000;
times[2] = 2000;
times[3] = 1000;
GifMovieView view = new GifMovieView(this, stream);
mPlayer = MediaPlayer.create(getApplicationContext(), tracks[currentTrack]);
mPlayer.setOnCompletionListener(this);
mPlayer.start();
setContentView(view);
}
#Override
public void onCompletion(MediaPlayer arg0) {
arg0.release();
arg0 = MediaPlayer.create(getApplicationContext(),
tracks[currentTrack]);
if (currentTrack < tracks.length-1) {
currentTrack++;
arg0 = MediaPlayer.create(getApplicationContext(),
tracks[currentTrack]);
arg0.setOnCompletionListener(this);
try {
Thread.sleep(times[currentTrack]);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
arg0.start();
}else if(currentTrack==tracks.length-1) {
Intent i = new Intent(getApplicationContext(), ViewBeat1.class);
startActivity(i);
}
}
}
How can i get rid of this behaviour?
The MasterView holds the mPlayer and also closes it onRestart, onDestroy and onPause.
Here is the state diagram of the MediaPlayer that will help you to understand at what point in the Activity's life cycle should you call the various methods on your MediaPlayer object.
Just like Jesse J said, try calling stop() in onPause()
I have been making ringtone application and I have a problem. I can play sounds in listitem and I can set ringtone but when I check from telephone settings, it doesn't play. Where is the problem, thanks.
public class AndroidListViewActivity extends ListActivity {
int [] sesdosya;
MediaPlayer mediaPlayer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
// storing string resources into Array
String[] sesler = getResources().getStringArray(R.array.sesler);
// Binding Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, sesler));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent intent = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
intent.putExtra("position", position);
startActivity(intent);
}
private String getItemAtPosition(int position) {
// TODO Auto-generated method stub
return null;
}
});
}
}
Other class; (Play and set ringtone)
public class SingleListItem extends Activity{
int [] sesdosya;
String[] sesisim;
MediaPlayer mediaPlayer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sesisim = new String[] {"aramabeni","azsonra","baglama","crank","haha","hippopchicken","nokiaturkish","nuri","policemix",
"polistelsiz","ramiz","veryfunnybaby","wahwah","walawalabingbang","windowsmusic"};
sesdosya= new int[] {R.raw.aramabeni,R.raw.azsonra,R.raw.baglama,R.raw.crank,R.raw.haha,R.raw.hippopchicken,R.raw.nokiaturkish,R.raw.nuri,
R.raw.policemix,R.raw.polistelsiz,R.raw.ramiz,R.raw.veryfunnybaby,R.raw.wahwah,R.raw.walawalabingbang,R.raw.windowsmusic};
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
mediaPlayer = MediaPlayer.create(this, sesdosya[position]);
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
mediaPlayer.start();
//start the progress dialog
}
});
Button zil = (Button) findViewById(R.id.btnzilsesi);
zil.setOnClickListener(new View.OnClickListener(){
public void onClick(View arg0) {
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
setRingtone(sesdosya[position]);
//start the progress dialog
}
});
}
#SuppressLint("SdCardPath")
public boolean setRingtone(int p){
byte[] buffer=null;
InputStream fIn = getBaseContext().getResources().openRawResource(p);
int size=0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
// TODO Auto-generated catch block
return false;
}
String path=Environment.getExternalStorageDirectory().getPath()+"/sdcard/media/audio/ringtones/";
String filename=sesisim+".mp3";
boolean exists = (new File(path)).exists();
if (!exists){new File(path).mkdirs();}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+path+filename)));
File k = new File(path);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE,filename);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.Audio.Media.ARTIST, "test1");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION,false);
values.put(MediaStore.Audio.Media.IS_ALARM, false);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//Insert it into the database
Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());
getContentResolver().delete(uri, MediaStore.MediaColumns.DATA + "=\"" + k.getAbsolutePath() + "\"", null);
Uri newUri = getContentResolver().insert(uri, values);
RingtoneManager.setActualDefaultRingtoneUri(
SingleListItem.this,
RingtoneManager.TYPE_RINGTONE,
newUri
);
return true;
}
}