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()
Related
before i'm so sorry if my post maybe duplicated, but i have another case in this problem, i wanna show an image that i capture from camera in ImageView and after that i save it or upload it into my json file, but after i take the picture, it's stopped in Log.i ("Error", "Maybe Here");
no error in my code but the image cant saved into thumbnail ImageView
Here is my code, i'm using Asyntask
public class StoreTodoDisplayActivity extends AppCompatActivity {
public Context ctx;
Uri imgUri;
ActionBar actionBar;
public static CategoryData category_data_ar[];
public static CategoryData category_data_ar2[];
String targetUrl;
String path = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/img11.jpg";
public static final String PREFS_NAME = "MyPrefsFile";
SharedPreferences settings;
RestData restData;
ImageData imgData;
public Uri mCapturedImageURI;
public String image_path = "";
Toolbar toolbar;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.camera_display);
targetUrl = Config.getEndPointUrl();
ctx = this.getApplicationContext();
System.gc();
set_Spinner();
set_Spinner2();
// Toolbar show
toolbar = (Toolbar) findViewById(R.id.actionbarCameraDisplay);
setSupportActionBar(toolbar);
final android.support.v7.app.ActionBar abar = getSupportActionBar();
abar.setDisplayShowCustomEnabled(true);
abar.setDisplayShowTitleEnabled(false);
abar.setDisplayHomeAsUpEnabled(true);
abar.setHomeButtonEnabled(true);
// Back button pressed
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
settings = getSharedPreferences(PREFS_NAME, 0);
}
#Override
public void onResume() {
if (!UserInfo.loginstatus) {
finish();
}
super.onResume();
}
public void get_pic(View view) {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, 12345);
}
public void save_img(View view) {
EditText te = (EditText) findViewById(R.id.camera_display_txt);
String msg = te.getText().toString();
Spinner sp = (Spinner) findViewById(R.id.spinner1);
int catid = (int) sp.getSelectedItemId();
String cat = category_data_ar[catid].catid;
Spinner sp2 = (Spinner) findViewById(R.id.spinner2);
int catid2 = (int) sp2.getSelectedItemId();
String cat2 = category_data_ar2[catid2].catid;
ImageUploader uploader = new ImageUploader("display", msg, cat, cat2);
uploader.execute(Config.getEndPointUrl() + "/uploadimage.json");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 12345) {
if (resultCode == RESULT_OK) {
getimage getm = new getimage();
getm.execute();
}
}
}
public void set_Spinner2() {
Spinner sp = (Spinner) findViewById(R.id.spinner2);
sp.setVisibility(View.VISIBLE);
CatProductHelper helper = new CatProductHelper(ctx);
category_data_ar2 = helper.getCategories();
String[] isidesc = new String[category_data_ar2.length];
for (int k = 0; k < category_data_ar2.length; k++) {
isidesc[k] = category_data_ar2[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + category_data_ar2[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
public void set_Spinner() {
// set list activity
Spinner sp = (Spinner) findViewById(R.id.spinner1);
category_data_ar = StoreInfo.storeDisplayCat;
try {
String[] isidesc = new String[category_data_ar.length];
Log.i("toTry", "Normal");
for (int k = 0; k < category_data_ar.length; k++) {
isidesc[k] = category_data_ar[k].catdesc;
Log.i("AndroidRuntime", "Desc -- "
+ category_data_ar[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(
StoreTodoDisplayActivity.this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
} catch (Exception e) {
Log.i("toCatch", "NULL EXCEPTION");
DisplayCatHelper helperDisplayCat = new DisplayCatHelper(ctx);
CategoryData[] displayCat = helperDisplayCat.getCategories();
String[] isidesc = new String[displayCat.length];
for (int k = 0; k < displayCat.length; k++) {
isidesc[k] = displayCat[k].catdesc;
Log.i("AndroidRuntime", "Desc -- " + displayCat[k].catdesc);
}
ArrayAdapter spinnerArrayAdapter = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, isidesc);
spinnerArrayAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(spinnerArrayAdapter);
}
}
private class ImageUploader extends AsyncTask<String, String, String> {
ProgressDialog dialog;
private String url;
private String cameraType;
private String cameraMsg;
private String cameraCat;
private String catproduct;
public ImageUploader(String type, String msg, String cat, String cat2) {
cameraType = type;
cameraMsg = msg;
cameraCat = cat;
catproduct = cat2;
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(StoreTodoDisplayActivity.this, "",
"Uploading...", false);
// none
}
#Override
protected String doInBackground(String... params) {
url = params[0];
Log.i("ncdebug", "upload image to: " + url);
try {
if (image_path.equals("")) {
Log.i("ncdebug", "bmp kosong!!!!");
} else {
Log.i("ncdebug", "Ok bmp gak kosong, mari kirim");
restData = new RestData();
imgData = new ImageData();
restData.setTitle("Display : " + StoreInfo.storename);
restData.setRequestMethod(RequestMethod.POST);
restData.setUrl(url);
imgData.setImageData(url, image_path, cameraMsg, cameraCat
+ "-" + catproduct, UserInfo.username,
StoreInfo.storeid, cameraType, UserInfo.checkinid);
saveToDb();
return "Success";
}
} catch (Exception e) {
//saveToDb();
}
return "Penyimpanan gagal, ulangi tahap pengambilan gambar";
}
#Override
protected void onPostExecute(String Result) {
dialog.dismiss();
if (Result.equals("Success")) {
Toast.makeText(ctx, "Data tersimpan", Toast.LENGTH_SHORT)
.show();
// checked todo
String vVar = StoreInfo.storeid + "-" + UserInfo.username
+ "-displaycam";
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(vVar, true);
editor.commit();
Intent intent = new Intent(ctx, StoreTodoActivity.class);
startActivity(intent);
finish();
} else {
Toast.makeText(ctx, Result, Toast.LENGTH_LONG)
.show();
}
}
}
public void saveToDb() {
Log.i("eris", "connection failed so save to db");
RestHelper helper = new RestHelper(ctx);
helper.insertRest(restData);
imgData.setRestId(helper.getRestId());
Log.i("REST ID", helper.getRestId());
ImageHelper imgHelper = new ImageHelper(ctx);
imgHelper.insertRest(imgData);
}
public class getimage extends AsyncTask<String, String, String> {
String orientation = "";
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// Log.i("INI BACKGROUND", "LIHAT");
try {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(mCapturedImageURI, projection,
null, null, null);
int column_index_data = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor
.getString(column_index_data);
String parentPath = Environment.getExternalStorageDirectory()
+ "/Nestle Confect";
String filename = System.currentTimeMillis() + ".jpg";
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inSampleSize = 4;
Bitmap bmp = BitmapFactory.decodeFile(capturedImageFilePath,
opts);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File file = new File(parentPath);
file.mkdir();
try {
file.createNewFile();
Log.i("absoulute path", file.getAbsolutePath());
FileOutputStream fo = new FileOutputStream(file + "/"
+ filename, true);
// 5
fo.write(bytes.toByteArray());
fo.close();
image_path = parentPath + "/" + filename;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
image_path = capturedImageFilePath;
}
byte[] thumb = null;
try {
ExifInterface exif = new ExifInterface(
capturedImageFilePath);
orientation = exif
.getAttribute(ExifInterface.TAG_ORIENTATION);
thumb = exif.getThumbnail();
} catch (IOException e) {
}
if (thumb != null) {
Log.i("IMAGEVIEW", "THUMBNAIL");
bitmap = BitmapFactory.decodeByteArray(thumb, 0,
thumb.length);
} else {
Log.i("IMAGEVIEW", "REALFILE");
return "not fine";
}
return "fine";
} catch (Exception e) {
return "not fine";
}
}
#Override
public void onPostExecute(String result) {
// PROBLEM HERE
Log.i("ERROR", "HERE MAYBE");
if (result.equals("fine")) {
ImageView gambarHasil = (ImageView) findViewById(R.id.camera_display_img);
gambarHasil.setImageBitmap(bitmap);
if (!orientation.equals("1")) {
Log.i("ORIENTATION", orientation);
float angel = 0f;
if (orientation.equals("6")) {
angel = 90f;
} else if (orientation.equals("8")) {
angel = -90f;
}
Matrix matrix = new Matrix();
gambarHasil.setScaleType(ScaleType.MATRIX); // required
matrix.postRotate((float) angel, gambarHasil.getDrawable()
.getBounds().width() / 2, gambarHasil.getDrawable()
.getBounds().height() / 2);
gambarHasil.setImageMatrix(matrix);
}
} else {
Toast.makeText(
ctx,
"Error, Try To Take Picture Again",
Toast.LENGTH_LONG).show();
}
}
}
}
I think your activity just got restarted you need to put below code in manifest where you declare. and save your uri on saveInstanceState and restore it on onrestoreinstancestate. it will be resolve your issue
android:configChanges="orientation|keyboardHidden|screenSize"
Use this lib,Provides support above API 14
https://github.com/google/cameraview
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.
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!
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
In this question,actually i want to change the notification sound.For this i create a custom sound dialog box through which i can change and set the different ringtones.But the problem is that this sound dialog box is present in different activity i.e. SoundActivity while i write the notification code in different activity.Can you please tell me how can i use this sound activity in notification code so that by changing the ringtones,notification sound alos get changed. I have this sound activity in which i set the ringtones according to my demand.But i want these ringtones to be beep when notifications come.I write the code for notifictaion in another activity.Can you please tell me how can i use this sound activity,so that changes made in this activity changes the notification sound???
protected void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sound);
setTitle("Sounds");
initUpdateView();
isSystemRingtone=PreferencesClass.getSystemRingtoneStatus(getApplicationContext());
textviewRingtone = (TextView)findViewById(R.id.textview_ringtone_settings);
if(PreferencesClass.getRingtone(getApplicationContext()).substring(0, 1).equalsIgnoreCase("/")){
String[] son=PreferencesClass.getRingtone(getApplicationContext()).split("/");
String[] s=son[son.length-1].split("\\.ogg");
String rep=s[0].replace("_", " ");
if(rep.startsWith("S ")){
rep=rep.substring(2);
}
textviewRingtone.setText(UppercaseFirstLetters(rep));
mysong=son[son.length-1];
mysongPath=PreferencesClass.getRingtone(getApplicationContext());
if(mysongPath.contains("system")){
SelectedTone="Sounds";
}
else{
SelectedTone="My Music";
}
}
songURI=PreferencesClass.getUri(getApplicationContext());
LinearLayout layoutRingtone = (LinearLayout)findViewById(R.id.linearlayout_ringtone_settings);
layoutRingtone.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(RINGTONE_DIALOG_ID);
}
});
}catch(Exception ex)
{
Log.e("ERROR",ex.toString());
}
}
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case RINGTONE_DIALOG_ID:
{
int selectedIndex = 1;
//if(SelectedTone.equalsIgnoreCase("My Music"))
//if(SelectedTone.equalsIgnoreCase(""))
// selectedIndex=0;
Dialog dialog=null;
//final String[] ringArray=new String[]{"My Music","Sounds"};
final String[] ringArray=new String[]{"Sounds"};
if(ringArray.length>0){
AlertDialog.Builder builder = new AlertDialog.Builder(SoundActivity.this);
builder.setSingleChoiceItems(ringArray, selectedIndex, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if(which==0){
isSystemRingtone=1;
SelectedTone="Sounds";
PreferencesClass.setSystemRingtoneStatus(1, getApplicationContext());
Intent intent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Sounds");
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, false);
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,RingtoneManager.TYPE_RINGTONE);
String uri = songURI;
Log.d("uri", uri);
//chooses and keeps the selected item as a uri
if ( uri != null ) {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, Uri.parse( uri ));
} else {
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, (Uri)null);
}
startActivityForResult(intent,999);
}
dialog.dismiss();
}
});
builder.setTitle("Ringtone");
//dialog=new Dialog(SettingsGroup.group, R.style.Theme_D1dialog);
dialog=builder.create();
dialog.setCanceledOnTouchOutside(true);
return dialog;
}
else
Toast.makeText(getApplicationContext(), "No Data is available", Toast.LENGTH_LONG).show();
}
}
return super.onCreateDialog(id);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d("req", requestCode+"");
if (resultCode == RESULT_OK) {
if (requestCode == RQS_OPEN_AUDIO_MP3) {
audioFileUri = data.getData();
Log.d("uri", audioFileUri.toString());
String son[]=audioFileUri.toString().split("/");
int k=0;
int id=1;
try{
id=Integer.parseInt(son[son.length-1]);
}
catch(Exception e){
k=1;
mysong=son[son.length-1];
mysongPath=audioFileUri.getPath();
}
//Log.d("id", son[son.length-1]);
if(k==0){
Uri allaudiosong = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String audioID = data.getDataString();
Uri MyUri = Uri.parse(audioID);
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " !=0 ";
Cursor cursor;
cursor = managedQuery(MyUri, STAR, null, null, null);
int i=0;
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
// mysong[i]=song_name;
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
if(id==song_id){
mysong=song_name;
if(SelectedTone.equalsIgnoreCase("My Music")){
textviewRingtone.setText(mysong);
}
}
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
if(id==song_id){
mysongPath=fullpath;
Log.d("path", fullpath);
if(SelectedTone.equalsIgnoreCase("My Music"))
PreferencesClass.setRingtone(mysongPath, SoundActivity.this);
}
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
Log.d("Audio Album Id= ",""+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
i++;
} while (cursor.moveToNext());
}
}
}
Log.d("audio",audioFileUri.getPath());
}
if(requestCode==999){
Log.d("req", requestCode+"");
Uri uri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
try
{
Uri audioFileUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
Log.d("uri", audioFileUri.toString());
String son[]=audioFileUri.toString().split("/");
int k=0;
int id=1;
try{
id=Integer.parseInt(son[son.length-1]);
Log.d("id", id+"");
}
catch(Exception e){
k=1;
}
Log.d("K", k+"");
if(k==0){
Uri allaudiosong = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Uri MyUri = uri;
PreferencesClass.setUri(MyUri.toString(), getApplicationContext());
songURI=MyUri.toString();
String audioselection = MediaStore.Audio.Media.IS_MUSIC + " !=0 ";
Cursor cursor;
cursor = managedQuery(MyUri, STAR,null, null, null);
int i=0;
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
String song_name = cursor
.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
System.out.println("Audio Song Name= "+song_name);
// mysong[i]=song_name;
int song_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media._ID));
System.out.println("Audio Song ID= "+song_id);
if(id==song_id){
mysong=song_name;
if(SelectedTone.equalsIgnoreCase("Sounds")){
String[] s=mysong.split("\\.");
String rep=s[0].replace("_", " ");
if(rep.startsWith("S ")){
rep=rep.substring(2);
}
textviewRingtone.setText(UppercaseFirstLetters(rep));
}
}
String fullpath = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
System.out.println("Audio Song FullPath= "+fullpath);
if(id==song_id){
Log.d("Done", "Done");
//mysongPath=fullpath.substring(4, fullpath.length());
mysongPath=fullpath;
Log.d("path", fullpath);
if(SelectedTone.equalsIgnoreCase("Sounds"))
PreferencesClass.setRingtone(mysongPath, SoundActivity.this);
}
String album_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM));
System.out.println("Audio Album Name= "+album_name);
int album_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
System.out.println("Audio Album Id= "+album_id);
Log.d("Audio Album Id= ",""+album_id);
String artist_name = cursor.getString(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST));
System.out.println("Audio Artist Name= "+artist_name);
int artist_id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
System.out.println("Audio Artist ID= "+artist_id);
i++;
} while (cursor.moveToNext());
}
}
}
}
catch (Exception localException)
{
}
}
}
}
public void playSample(String s){
AssetFileDescriptor afd = null;
Log.d("RingtoneSelected",PreferencesClass.getRingtone(getApplicationContext()));
if(!(s.substring(0,1).equalsIgnoreCase("/"))){
try {
if(s==null){
afd = getAssets().openFd(PreferencesClass.getRingtone(getApplicationContext())+".mp3");
}else{
afd = getAssets().openFd(s+".mp3");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
player = new MediaPlayer();
try {
if(s.substring(0, 1).equalsIgnoreCase("/")){
player.setDataSource(s);
}
else
player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
player.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
float volume=(float)Float.valueOf(PreferencesClass.getVolume(getApplicationContext()));
player.setVolume(volume,volume);
if(!(s.substring(0, 1).equalsIgnoreCase("/"))){
player.setLooping(true);
}
else
player.setLooping(false);
player.start();
playing=true;
if(!(s.substring(0, 1).equalsIgnoreCase("/"))){
Thread thread=new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try{
Thread.sleep(10000);
}catch(Exception e){
}
player.stop();
}
});
thread.start();
}
}
public static String UppercaseFirstLetters(String str)
{
char[] chars = str.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i]=='.' || chars[i]=='\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
I have this sound activity in which i set the ringtones according to my demand.But i want these ringtones to be beep when notifications come.I write the code for notifictaion in another activity.Can you please tell me how can i use this sound activity,so that changes made in this activity changes the notification sound??
This is my notifcation code in which code for changing the sound has to be included.Actually in this code in notification code,i have used the mobile ringtone.But i want to use the sound from custom dialog box:
Intent notificationIntent = new Intent(context, HomeTabActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, Utils.notiMsg, pendingIntent);
notification.flags|=notification.FLAG_INSISTENT|notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_LIGHTS;
//notification.vibrate=new long[] {100L, 100L, 200L, 500L};
notificationManager.notify(1, notification);
Utils.notificationReceived=true;
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(this, uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final AudioManager audioManager = (AudioManager)getSystemService(AUDIO_SERVICE);
if(audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION)!=0){
mediaPlayer.setLooping(false);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
This is the following code which contains notification class as well as sound activity.
When do you launch your notifications from that class? On some event or...?
You can make a Service class that is used to dispatch the notifications, and whenever the user changes the notification sound you alert your Service to change the sound that will be used next time..