I do apologize for the noobish question, but I am building a music player in android studio and I am having problems with the songs playing one after the other like a playlist. The songs can only be picked by hand and after the song finishes it just stops until the user clicks another song. I've written two pieces of code that I suspect will solve this issue but I'm not really sure how to implement them or if they eventually will be of any use at all. I would really appreciate some help with this, could really really use it. Any advice or constructive criticism is always welcome, thanks in advance. here are the snippets:
//------------> to get the next song <---------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
//--------------> to play the song on list item click <-------------------
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
And just for reference here is my main java file:
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ListView list = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private ImageButton btNext = null;
private ImageButton btPrev = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
btNext = (ImageButton) findViewById(R.id.btNxt);
btPrev = (ImageButton) findViewById(R.id.btPrev);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list_item, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
btNext.setOnClickListener(onButtonClick);
btPrev.setOnClickListener(onButtonClick);
}
}
//----------- ??? ----------------------------------------------------------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
// --------------------------------------------------------------------------------
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) durationInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_item, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.btNxt: {
//TO DO
}
case R.id.btPrev: {
//TO DO
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
}
}
};
}
You can look at my methods below to play the next song. Hope it helps.
public static void nextSong() {
int numOfSong = songList.size();
if (!isShuffle) { // Shuffle mode is off
if (currentPosition < numOfSong - 1) {
currentPosition++;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
} else {
currentPosition = 0;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
} else { // Shuffle mode is on
Random rand = new Random();
currentPosition = rand.nextInt(numOfSong);
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
}
And this is playBackMusic() method to play the song:
public static void playBackMusic() {
try {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(currentSong.getPath());
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
endOfTheSong();
}
});
isPlaying = true;
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Method endOfTheSong() to handle what to do after playing current song.
public static void endOfTheSong() {
if (isRepeat == 1) { // currently repeat one song
mediaPlayer.seekTo(0);
mediaPlayer.start();
} else if (isRepeat == 2) { // currently repeat all songs
nextSong();
} else { // currently no repeat
if (currentPosition != songList.size() - 1) nextSong();
}
}
Related
i made a googlemap app where my markers are displyed.
the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem.
also i want to refresh the map or markers each second on the map.
if you have any ideas please i am here to learn from all of you.
here is my MapActivity code :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
private static final String TAG = "MapActivity";
#Bind(R.id.back)
View back;
#Bind(R.id.zoom_in)
View zoom_in;
#Bind(R.id.zoom_out)
View zoom_out;
#Bind(R.id.updatetimer)
TextView updatetimer;
#Bind(R.id.autozoom)
ImageView autozoom;
#Bind(R.id.showtails)
ImageView showtails;
#Bind(R.id.geofences)
ImageView showGeofences;
#Bind(R.id.map_layer)
ImageView map_layer_icon;
private GoogleMap map;
#Bind(R.id.content_layout)
View content_layout;
#Bind(R.id.loading_layout)
View loading_layout;
#Bind(R.id.nodata_layout)
View nodata_layout;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
private AsyncTask downloadingAsync;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
// deviceIdSmallMarkerInfo = new HashMap<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onResume()
{
super.onResume();
timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
if (timeleft < 0)
timeleft = 0;
updatetimer.setText(String.format("%.0f", timeleft));
if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
if (map != null)
refresh();
}
});
}
}, 0, 1000);
}
#Override
protected void onPause()
{
super.onPause();
try
{
timer.cancel();
timer.purge();
downloadingAsync.cancel(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void refresh()
{
if (isRefreshLoced)
return;
isRefreshLoced = true;
lastRefreshTime = System.currentTimeMillis();
final String api_key = (String) DataSaver.getInstance(this).load("api_key");
API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
{
#Override
public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
{
Log.d(TAG, "success: loaded devices array");
final ArrayList<Device> allDevices = new ArrayList<>();
if (getDevicesItems != null)
for (ApiInterface.GetDevicesItem item : getDevicesItems)
allDevices.addAll(item.items);
API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
{
#Override
public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
{
Log.d(TAG, "success: loaded icons");
downloadingAsync = new AsyncTask<Void, Void, Void>()
{
ArrayList<MarkerOptions> markers;
ArrayList<Integer> deviceIds;
#Override
protected Void doInBackground(Void... params)
{
// add markers
int dp100 = Utils.dpToPx(MapActivity.this, 50);
markers = new ArrayList<>();
deviceIds = new ArrayList<>();
if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
return null;
for (Device item : allDevices)
{
if (isCancelled())
break;
if (item.device_data.active == 1)
{
// ieškom ikonos masyve
DeviceIcon mapIcon = null;
for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
if (item.device_data.icon_id == icon.id)
mapIcon = icon;
String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");
try
{
Log.d("MapActivity", "DOWNLOADING BITMAP: " + server_base + mapIcon.path);
Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base + mapIcon.path).openConnection().getInputStream());
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);
float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
int dstWidth = (int) (srcWidth * ratio);
int dstHeight = (int) (srcHeight * ratio);
bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);
// marker
MarkerOptions m = new MarkerOptions();
m.position(new LatLng(item.lat, item.lng));
// marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
// marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
// info window
// MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
// marker.setInfoWindow(infoWindow);
markers.add(m);
deviceIds.add(item.id);
} catch (OutOfMemoryError outOfMemoryError)
{
Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
ArrayList<GeoPoint> points = new ArrayList<>();
if (autoZoomedTimes < 1)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
});
}
}, 50);
} else if (isAutoZoomEnabled)
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + markers.size());
loading_layout.setVisibility(View.GONE);
if (markers.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
for (int i = 0; i < markers.size(); i++)
{
MarkerOptions options = markers.get(i);
int deviceId = deviceIds.get(i);
Marker m;
Polyline polyline;
if (deviceIdMarkers.containsKey(deviceId))
{
Log.d("aa", "moving to" + options.getPosition());
deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
m = deviceIdMarkers.get(deviceId);
polyline = deviceIdPolyline.get(deviceId);
} else
{
Log.d("aa", "putting new");
m = map.addMarker(options);
deviceIdMarkers.put(deviceId, m);
polyline = map.addPolyline(new PolylineOptions());
deviceIdPolyline.put(deviceId, polyline);
}
Device thatonedevice = null;
for (Device device : allDevices)
if (device.id == deviceId)
thatonedevice = device;
markerIdDevices.put(m.getId(), thatonedevice);
// update marker rotation based on driving direction
if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
{
double dirLat = thatonedevice.lat - deviceIdLastLatLng.get(deviceId).latitude;
double dirLng = thatonedevice.lng - deviceIdLastLatLng.get(deviceId).longitude;
m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
}
deviceIdLastLatLng.put(deviceId, new LatLng(thatonedevice.lat, thatonedevice.lng));
List<LatLng> polylinePoints = new ArrayList<>();
for (TailItem item : thatonedevice.tail)
polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
polyline.setPoints(polylinePoints);
polyline.setWidth(Utils.dpToPx(MapActivity.this, 2));
polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
}
// else
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#Override
public View getInfoContents(final Marker marker)
{
synchronized (this)
{
}
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
view.bringToFront();
view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
marker.hideInfoWindow();
}
});
TextView device_name = (TextView) view.findViewById(R.id.device_name);
device_name.setText(device.name);
TextView altitude = (TextView) view.findViewById(R.id.altitude);
altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(device.time);
TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
stopTimeView.setText(stopTime);
TextView speed = (TextView) view.findViewById(R.id.speed);
speed.setText(device.speed + " " + device.distance_unit_hour);
TextView address = (TextView) view.findViewById(R.id.address);
address.setText(device.address);
final ArrayList<Sensor> showableSensors = new ArrayList<>();
for (Sensor item : device.sensors)
if (item.show_in_popup > 0)
showableSensors.add(item);
ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
sensors_list.setAdapter(new AwesomeAdapter<Sensor>(MapActivity.this)
{
#Override
public int getCount()
{
return showableSensors.size();
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);
Sensor item = showableSensors.get(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(item.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(item.value);
return convertView;
}
});
List<Address> addresses;
try
{
addresses = new Geocoder(MapActivity.this).getFromLocation(device.lat, device.lng, 1);
if (addresses.size() > 0)
address.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e)
{
e.printStackTrace();
}
return view;
}
return null;
}
});
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker)
{
int px = Utils.dpToPx(MapActivity.this, 300);
map.setPadding(0, px, 0, 0);
stopTime = "...";
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
{
#Override
public void success(ApiInterface.DeviceStopTimeResult result, Response response)
{
stopTime = result.time;
marker.showInfoWindow();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
marker.hideInfoWindow();
}
});
map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
{
#Override
public void onInfoWindowClose(Marker marker)
{
map.setPadding(0, 0, 0, 0);
}
});
// updateSmallMarkerData(allDevices);
isRefreshLoced = false;
}
}.execute();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
refresh();
}
this MapActivity is slow to load, could you teach me a way to make it goes faster?
Best regard :)
waiting for your propositions.
PS: i have removed some functions to make the code look short but i kept the most important in is case.
For the crashing issue
create a class
public class NetWorkChecker {
static NetworkInfo wifi, mobile;
public static Boolean check(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
} catch (Exception e) {
e.printStackTrace();
}
if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
return true;
} else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
return true;
} else {
//Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
// ((Activity) c).finish();
displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
return false;
}
}
public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
context.startActivity(intent);
}
});
builder.show();
return builder.create();
}
}
to check if the devise have an active internet connection
call
if (!NetWorkChecker.check(this)){
////do your refres
}
I'm new to Android app developing, and I've tried to program a very simple app: each time the headphone cable is inserted it will play a random song from the collection, and stop whenever the headphone cable is disconnected.
However, I now face a very strange problem: no matter what I do, the app plays always two songs at the same time.
It's very strange because I tried to synchronize everything but it didn't solve the issue...
Here follows my code. Thanks in advance for any help!
public class MainActivity extends AppCompatActivity {
private int countMusic;
private boolean headphones= false;
private HeadphonePlugReceiver receiver;
private HashMap<Integer, String> playing_title;
private RandomPlayer player;
Object lock = new Object();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playing_title = new HashMap<>();
scanAgain();
Button scanButton = (Button)findViewById(R.id.scan_again);
scanButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanAgain();
}
});
updateStatus();
receiver = new HeadphonePlugReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
}
private void updateStatus() {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView statusTextView = (TextView)findViewById(R.id.status);
TextView titleTextView = (TextView)findViewById(R.id.title);
if (headphones) {
statusTextView.setText("Headphones connected!");
String txt = "";
for (Integer cd: playing_title.keySet()) {
txt += String.format("%d: %s ### ", cd, playing_title.get(cd).replace("_", " "));
}
titleTextView.setText(txt);
} else {
statusTextView.setText("Headphones not connected.");
titleTextView.setText("Music not playing");
}
}
});
}
private void addDebug(final String code) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView debugTextView = (TextView)findViewById(R.id.debug);
String dbg = String.format("%s \n %s", debugTextView.getText(), code);
debugTextView.setText(dbg);
}
});
}
private void addError(final String msg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView errorTextView = (TextView)findViewById(R.id.error);
errorTextView.setText(msg);
}
});
}
private void startPlayer() {
if (player == null) {
player = new RandomPlayer(this);
player.start();
}
}
private void stopPlayer() {
if (player != null) {
player.interr();
player = null;
}
}
private void scanAgain() {
try {
TextView countTextView = (TextView)findViewById(R.id.count);
countTextView.setText("Scanning... ");
countMusic = scanMusic().getCount();
countTextView.setText(String.format("Music file found: %d", countMusic));
}
catch(Exception e) {
Log.e("problem", e.getMessage());
}
}
public Cursor scanMusic() {
ContentResolver cr = this.getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
String[] projection = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.TITLE_KEY
};
Cursor cur = cr.query(uri, projection, selection, null, sortOrder);
return cur;
}
private class HeadphonePlugReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
synchronized (lock) {
int state = intent.getIntExtra("state", 0);
managePlayer(state);
// Log.e("state", String.format("state: %d", state));
}
}
private void managePlayer(int state) {
boolean n_headphones = (state != 0);
if (n_headphones == headphones)
return;
headphones = n_headphones;
if (headphones)
startPlayer();
else
stopPlayer();
}
}
private class RandomPlayer extends Thread implements MediaPlayer.OnCompletionListener {
private final MainActivity act;
private final Random r;
private final int code;
private MediaPlayer mp;
private boolean keep_going = true;
Object lock2 = new Object();
public RandomPlayer(MainActivity mainActivity) {
r = new Random(System.currentTimeMillis());
act = mainActivity;
code = r.nextInt(10000);
}
public void onCompletion(MediaPlayer arg0) {
playNext();
}
#Override
public void run() {
playNext();
while (keep_going) {
try {
sleep(100);
} catch (InterruptedException e) {
keep_going = false;
}
}
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
playing_title.remove(code);
updateStatus();
}
public void interr() {
keep_going = false;
}
private void playNext() {
synchronized (lock2) {
if (mp != null) {
mp.stop();
mp.release();
mp = null;
}
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
//mp.setVolume(0.9f , 0.9f);
mp.setOnCompletionListener(this);
int chosen = r.nextInt(countMusic);
Cursor cur = scanMusic();
for (int i = 0; i < chosen; i++)
cur.moveToNext();
playing_title.put(code, cur.getString(cur.getColumnIndex(MediaStore.Audio.Media.TITLE)));
try {
int a1 = cur.getColumnIndex(MediaStore.Audio.Media.DATA);
String a2 = cur.getString(a1);
mp.setDataSource(a2);
mp.prepare();
mp.start();
addDebug(a2);
} catch (Exception e) {
Log.e("Randomplayer", "exception", e);
addError(e.getMessage());
}
updateStatus();
}
}
}
}
I have a code to read the contacts from the inbuilt phone contacts and it displays all the contacts in a list view in my app.The user can select multiple contacts and display them in another activity.
This code works fine in Android API level 18 and above,but gives an error in the versions below API 18.
I'm attaching the code of the contact picker activity and its adapter.
Error Logcat
private void getSelectedContacts() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
for (ContactObject bean : ContactsListClass.phoneList) {
if (bean.isSelected()) {
sb.append(bean.getName());
sb.append(bean.getNumber());
sb.append("1");
values.put(DbHelper.KEY_FNAME,bean.getName());
values.put(DbHelper.KEY_LNAME,bean.getNumber() );
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
}
}
dataBase.close();
String s = sb.toString().trim();
if (TextUtils.isEmpty(s)) {
Toast.makeText(context, "Select atleast one Contact",
Toast.LENGTH_SHORT).show();
} else {
s = s.substring(0, s.length() - 1);
/**
Toast.makeText(context, "Selected Contacts : " + s,
Toast.LENGTH_SHORT).show();
**/
Intent i = new Intent(Contacts_main.this, MainActivity.class);
i.putExtra("NAME", name);
i.putExtra("EVT_Name", event_name);
i.putExtra("EVT_Date", event_date);
startActivity(i);
}
}
private void addContactsInList() {
// TODO Auto-generated method stub
Thread thread = new Thread() {
#Override
public void run() {
showPB();
try {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
try {
ContactsListClass.phoneList.clear();
} catch (Exception e) {
}
while (phones.moveToNext()) {
String phoneName = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String phoneImage = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
//String pImage =
ContactObject cp = new ContactObject();
cp.setName(phoneName);
cp.setNumber(phoneNumber);
cp.setImage(phoneImage);
//cp.setImage(getResources(R.drawable.prof_active));
ContactsListClass.phoneList.add(cp);
}
phones.close();
lv = new ListView(context);
lv.setDividerHeight(0);
lv.setDivider(null);
lv.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
llContainer.addView(lv);
}
});
Collections.sort(ContactsListClass.phoneList,
new Comparator<ContactObject>() {
#Override
public int compare(ContactObject lhs,
ContactObject rhs) {
return lhs.getName().compareTo(
rhs.getName());
}
});
objAdapter = new ContactsAdapter(Contacts_main.this,
ContactsListClass.phoneList);
lv.setAdapter(objAdapter); //ERROR SHOWING HERE
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
CheckBox chk = (CheckBox) view
.findViewById(R.id.contactcheck);
ContactObject bean = ContactsListClass.phoneList
.get(position);
if (bean.isSelected()) {
bean.setSelected(false);
chk.setChecked(false);
} else {
bean.setSelected(true);
chk.setChecked(true);
}
}
});
} catch (Exception e) {
// e.printStackTrace();
//Toast.makeText(context, "Crash",Toast.LENGTH_SHORT).show();
}
hidePB();
}
};
thread.start();
}
Adapter Class:
Context mContext;
LayoutInflater inflater;
private List<ContactObject> mainDataList = null;
private List<ContactObject> mainInviteesList = null;
private ArrayList<ContactObject> arraylist;
private DbHelper mHelper;
private SQLiteDatabase dataBase;
public ContactsAdapter(Context context, List<ContactObject> mainDataList) {
mContext = context;
this.mainDataList = mainDataList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ContactObject>();
this.arraylist.addAll(mainDataList);
mHelper=new DbHelper(context);
}
static class ViewHolder {
protected TextView name;
protected TextView number;
protected CheckBox check;
protected ImageView image;
protected EditText invitees;
}
#Override
public int getCount() {
return mainDataList.size();
}
#Override
public ContactObject getItem(int position) {
return mainDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_row, null);
holder.name = (TextView) view.findViewById(R.id.contactname);
holder.number = (TextView) view.findViewById(R.id.contactno);
holder.check = (CheckBox) view.findViewById(R.id.contactcheck);
holder.image = (ImageView) view.findViewById(R.id.contactimage);
holder.invitees = (EditText) view.findViewById(R.id.editInvites);
view.setTag(holder);
view.setTag(R.id.contactname, holder.name);
view.setTag(R.id.contactno, holder.number);
view.setTag(R.id.contactcheck, holder.check);
view.setTag(R.id.editInvites, holder.invitees);
holder.check
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton vw,
boolean isChecked) {
int getPosition = (Integer) vw.getTag();
mainDataList.get(getPosition).setSelected(
vw.isChecked());
/**
dataBase=mHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(DbHelper.KEY_FNAME,mainDataList.get(getPosition).getName());
values.put(DbHelper.KEY_LNAME,mainDataList.get(getPosition).getNumber());
values.put(DbHelper.KEY_INVITE,"1" );
dataBase.insert(DbHelper.TABLE_NAME, null, values);
dataBase.close();
**/
}
});
// holder.invitees.addTextChangedListener(watcher);
} else {
holder = (ViewHolder) view.getTag();
}
holder.check.setTag(position);
//holder.invitees.setTag(position);
holder.name.setText(mainDataList.get(position).getName());
holder.number.setText(mainDataList.get(position).getNumber());
if(getByteContactPhoto(mainDataList.get(position).getImage())==null){
holder.image.setImageResource(R.drawable.prof_active);
}else{
holder.image.setImageBitmap(getByteContactPhoto(mainDataList.get(position).getImage()));
}
holder.check.setChecked(mainDataList.get(position).isSelected());
return view;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
mainDataList.clear();
if (charText.length() == 0) {
mainDataList.addAll(arraylist);
} else {
for (ContactObject wp : arraylist) {
if (wp.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
mainDataList.add(wp);
}
}
}
notifyDataSetChanged();
}
public Bitmap getByteContactPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, Long.parseLong(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, Contacts.Photo.CONTENT_DIRECTORY);
Cursor cursor = mContext.getContentResolver().query(photoUri,
new String[] {Contacts.Photo.DATA15}, null, null, null);
if (cursor == null) {
return null;
}
try {
if (cursor.moveToFirst()) {
byte[] data = cursor.getBlob(0);
if (data != null) {
return BitmapFactory.decodeStream( new ByteArrayInputStream(data));
}
}
} finally {
cursor.close();
}
return null;
}
}
The use case is this, in Android (above Kit Kat): open a stream from an audio file, get its properties, modify the memory buffer and play the result.
I would like to know how to 1) properly create the stream from the audio file; 2) get its properties (channels, encoding, length) like for the javax.sound.sampled.AudioFormat, but using methods from the android.media framework.
I know how to build a stream from binary, add audio properties to it then playing it. I would like to do the other way and extract these properties (channels, encoding) from the existing sound file header, using latest classes of the Android framework.
Thanks!
Here is full streaming class use this :
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private Button btn_play, btn_pause, btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://songspkcompilations.com/indian/soulfularijit/%5BSongs.PK%5D%2012%20-%20Mickey%20Virus%20-%20Tose%20Naina.mp3";
private static final int MINUTES_IN_AN_HOUR = 60;
private static final int SECONDS_IN_A_MINUTE = 60;
private final Handler handler = new Handler();
private boolean is_loading = true;
private boolean is_stopped = false;
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
private TextView txtTime;
private ProgressBar musicProgress;
private ImageView artistImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize_Controls();
}
private void initialize_Controls() {
btn_play = (Button) findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button) findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
musicProgress = (ProgressBar) findViewById(R.id.progress);
artistImg = (ImageView) findViewById(R.id.artistImg);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
txtTime = (TextView) findViewById(R.id.time);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar) v;
mediaPlayer
.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress());
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
if (is_stopped) {
is_stopped = false;
mediaPlayer.seekTo(0);
}
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
if (is_loading) {
is_loading = false;
musicProgress.setVisibility(View.GONE);
artistImg.setVisibility(View.VISIBLE);
}
int progress = (int) (((float) mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100);
int remainSec = (lengthOfAudio - mediaPlayer.getCurrentPosition()) / 1000;
seekBar.setProgress(progress);
txtTime.setText("" + timeConversion(remainSec));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
is_stopped = true;
}
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
txtTime.setText("" + timeConversion(lengthOfAudio / 1000));
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
private void pauseAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
private static String timeConversion(int totalSeconds) {
int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
int minutes = (totalSeconds - (hoursToSeconds(hours)))
/ SECONDS_IN_A_MINUTE;
int seconds = totalSeconds
- ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));
return hours + ":" + minutes + ":" + seconds;
}
private static int hoursToSeconds(int hours) {
return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
}
private static int minutesToSeconds(int minutes) {
return minutes * SECONDS_IN_A_MINUTE;
}
class PlayTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
playAudio();
updateSeekProgress();
}
}
#Override
protected void onResume() {
super.onResume();
new PlayTask().execute();
}
#Override
public void onBackPressed() {
super.onBackPressed();
pauseAudio();
finish();
}
}
the problem is simple, the media player is blocking the UI when implementing the source from remote server. i used a sync prepare for the initialize the media-player, but its block the UI when reset the media player.
here i written a code using thread, it helps a lot but need a clean solution.
public class QuranPlayerAct extends Activity implements DownloadMusicLstn,SeekBar.OnSeekBarChangeListener, OnClickListener,
MediaPlayer.OnPreparedListener, OnCompletionListener,
PlayerBtnClickedLstn, Runnable {
private static final int PLAY_FROM_LOCAL = 234;
private static final int PLAY_FROM_SERVER = 321;
private static final String TAG = "SongsListAct";
private static final int PAUSED = 756;
private static final int STARTED = 554;
private static final int STOPED = 386;
private static final int CLOSED = 453;
private TextView downloadEsplasedTV;
private RelativeLayout playerRetLay;
private ListView musicLst;
private ProgressBar dwnPrgV;
private ImageView playImgV;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private MediaPlayer mp;
private Utilities utils;
private Handler handler;
private boolean stopDownload;
private RelativeLayout downloadRetLay;
private ArrayList<String> musicFiles;
private ImageButton closeImgV;
private TextView downloadTitle;
private long currentDuration;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (mPrepared) {
long totalDuration = mp.getDuration();
currentDuration = mp.getCurrentPosition();
songTotalDurationLabel.setText(""
+ utils.milliSecondsToTimer(totalDuration));
songCurrentDurationLabel.setText(""
+ utils.milliSecondsToTimer(currentDuration));
int progress = (int) (utils.getProgressPercentage(
currentDuration, totalDuration));
songProgressBar.setProgress(progress);
}
handler.postDelayed(this, 100);
}
};
private TextView downloadTotalTV;
private TextView downloadPercentageTV;
private ImageView stopImgV;
private ImageButton closeDownloadImgV;
private int fileSize;
private boolean mPrepared;
private ProgressBar songsLoadingPB;
private String url;
private String fName;
private boolean stopped;
private int plLoc;
private int track_no;
private int state;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_quran_player);
// setActionBar();
setActionBar2();
getRefs();
handler = new Handler();
initMediaPlayer();
playerRetLay.setVisibility(View.GONE);
// updateList();
createAppDirectory();
Thread t = new Thread(this);
t.start();
}
private void setActionBar2() {
final ActionBar bar = getActionBar();
bar.setDisplayShowHomeEnabled(false);
bar.setDisplayShowCustomEnabled(true);
bar.setDisplayShowTitleEnabled(false);
bar.setCustomView(R.layout.player_actionbar_lay);
}
/*
* private void setActionBar() { final ActionBar bar = getActionBar();
*
* bar.setDisplayShowHomeEnabled(false);
* bar.setDisplayShowCustomEnabled(true);
* bar.setDisplayShowTitleEnabled(false);
* bar.setCustomView(R.layout.player_actionbar_lay);
*
* TextView tv = (TextView) bar.getCustomView().findViewById(
* R.id.action_bar_title);
*
* try { tv.setTypeface(Typeface .createFromAsset(getAssets(),
* "DANUBE__.TTF")); } catch (Exception e) { e.printStackTrace(); } }
*/
#Override
public void onResume() {
super.onResume();
setVisiblilityToPlayerAndUI(false);
updateProgressBar();
if(state==CLOSED)playerRetLay.setVisibility(View.GONE);
}
#Override
public void onPause() {
super.onPause();
l("Activity paused");
stopDownload = true;
setVisiblilityToPlayerAndUI(false);
handler.removeCallbacks(mUpdateTimeTask);
if (mp != null)
switch (state) {
case STARTED:
mp.pause();
playImgV.setImageResource(R.drawable.play_img);
break;
}
}
private void getRefs() {
musicLst = (ListView) findViewById(R.id.musLst_lstV);
playerRetLay = (RelativeLayout) findViewById(R.id.musLst_player_retLay);
dwnPrgV = (ProgressBar) findViewById(R.id.musLst_down_progbarV);
downloadRetLay = (RelativeLayout) findViewById(R.id.musLst_dwn_retLay);
playImgV = (ImageView) findViewById(R.id.musLst_ply_btn);
songProgressBar = (SeekBar) findViewById(R.id.musLst_seek_bar);
songTitleLabel = (TextView) findViewById(R.id.musLst_mus_det_txt);
songCurrentDurationLabel = (TextView) findViewById(R.id.time_esplased_TV);
songTotalDurationLabel = (TextView) findViewById(R.id.total_time_TV);
closeImgV = (ImageButton) findViewById(R.id.musLst_close_btn);
downloadTitle = (TextView) findViewById(R.id.musLst_down_title_TV);
downloadEsplasedTV = (TextView) findViewById(R.id.time_esplased_TV22);
downloadTotalTV = (TextView) findViewById(R.id.total_time_TV2);
downloadPercentageTV = (TextView) findViewById(R.id.total_percentage);
stopImgV = (ImageView) findViewById(R.id.musLst_stop_btn);
closeDownloadImgV = (ImageButton) findViewById(R.id.close_down_btn);
songsLoadingPB = (ProgressBar) findViewById(R.id.songs_load_progressbar);
}
#Override
public void run() {
if (!isNetworkAvailable()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(QuranPlayerAct.this,
"No Internet Connection Available",
Toast.LENGTH_LONG).show();
}
});
return;
}
MusicAppUtils appUtils = new MusicAppUtils();
String jsn = appUtils
.getDataFromUrl(MusicAppCommons.HTTP_AIMANSANGAM_COM_LISTFILES_PHP);
if (jsn == null)
return;
jsn = jsn.replace(",]", "]");
musicFiles = appUtils.parseMusicFilesJson(jsn);
updateList();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void createAppDirectory() {
if (MusicAppCommons
.checkFileExist(MusicAppCommons.AIMANSANGAM_MUSIC_DIR)) {
Log.i(TAG, "app directory already exist");
return;
}
File dir = new File(MusicAppCommons.AIMANSANGAM_MUSIC_DIR);
if (dir.mkdirs())
Log.i(TAG, "app directory created");
}
private void setVisiblilityToPlayerAndUI(boolean b) {
if (b) {
songsLoadingPB.setVisibility(View.VISIBLE);
downloadRetLay.setVisibility(View.VISIBLE);
// playerRetLay.setVisibility(View.VISIBLE);
} else {
songsLoadingPB.setVisibility(View.GONE);
downloadRetLay.setVisibility(View.GONE);
// playerRetLay.setVisibility(View.GONE);
}
}
private void initMediaPlayer() {
utils = new Utilities();
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
songProgressBar.setOnSeekBarChangeListener(this);
playImgV.setOnClickListener(this);
closeDownloadImgV.setOnClickListener(this);
closeImgV.setOnClickListener(this);
stopImgV.setOnClickListener(this);
}
private void resetTimeLabel() {
runOnUiThread(new Runnable() {
#Override
public void run() {
songTotalDurationLabel.setText("..");
songCurrentDurationLabel.setText("..");
}
});
}
public void updateProgressBar() {
handler.removeCallbacks(mUpdateTimeTask);
handler.postDelayed(mUpdateTimeTask, 100);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(mUpdateTimeTask);
if (mp != null)
mp.release();
}
public void updateList() {
l("called update list");
if (musicFiles == null)
return;
updateMusicListView(MusicLstAdapter.MUSIC_NOT_DOWNLOADING);
}
private void updateMusicListView(int state) {
final MusicLstAdapter lstAdapter = new MusicLstAdapter(this,
musicFiles, this, state, this);
runOnUiThread(new Runnable() {
#Override
public void run() {
musicLst.setAdapter(lstAdapter);
lstAdapter.notifyDataSetChanged();
}
});
}
#Override
public void onClick(View v) {
if (v == closeDownloadImgV) {
downloadRetLay.setVisibility(View.GONE);
stopDownload = true;
Toast.makeText(this, "Download canceled", Toast.LENGTH_SHORT)
.show();
} else if (v == playImgV) {
if (stopped)
new PlayerThread();
if (mp.isPlaying()) {
if (mp != null) {
state = PAUSED;
mp.pause();
l("pause");
playImgV.setImageResource(R.drawable.play_img);
}
} else {
if (mp != null) {
state = STARTED;
mp.start();
l("start");
playImgV.setImageResource(R.drawable.pause_img);
}
}
} else if (v == closeImgV) {
l("close clicked");
state = CLOSED;
playerRetLay.setVisibility(View.GONE);
handler.removeCallbacks(mUpdateTimeTask);
mp.stop();
mPrepared = false;
new Thread(new Runnable() {
#Override
public void run() {
mp.reset();
}
}).start();
} else if (v == stopImgV) {
l("stop clicked");
state = STOPED;
handler.removeCallbacks(mUpdateTimeTask);
mp.stop();
resetTimeLabel();
playImgV.setImageResource(R.drawable.play_img);
stopped = true;
mPrepared = false;
}
}
// --------************************************************************************
#Override
public void setSize(final int fileSize) {
handler.post(new Runnable() {
#Override
public void run() {
dwnPrgV.setMax(fileSize);
QuranPlayerAct.this.fileSize = fileSize;
float size = (float) fileSize / 1048576;
DecimalFormat format = new DecimalFormat("#.##");
downloadTotalTV.setText(format.format(size) + " MB");
downloadPercentageTV.setText("0 %");
}
});
}
#Override
public void onProgressUpdate(final long total) {
handler.post(new Runnable() {
#Override
public void run() {
dwnPrgV.setProgress((int) total);
float size = (float) total / 1048576;
DecimalFormat format = new DecimalFormat("#.##");
downloadEsplasedTV.setText(format.format(size) + " MB");
float l = total / (float) fileSize * 100;
int round = Math.round(l);
downloadPercentageTV.setText(round + " %");
}
});
}
#Override
public void finished() {
handler.post(new Runnable() {
#Override
public void run() {
downloadRetLay.setVisibility(View.GONE);
}
});
updateMusicListView(MusicLstAdapter.MUSIC_NOT_DOWNLOADING);
}
#Override
public void onDownloadSuccess(boolean success) {
if (success) {
} else {
}
}
#Override
public boolean isStopDownload() {
return stopDownload;
}
#Override
public void downloadStarted(final String fName) {
stopDownload = false;
handler.post(new Runnable() {
#Override
public void run() {
downloadTitle.setText(fName);
downloadRetLay.setVisibility(View.VISIBLE);
}
});
updateMusicListView(MusicLstAdapter.MUSIC_DOWNLOADING);
}
// ----------------*****************************************************************************
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
handler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mp.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(),
totalDuration);
mp.seekTo(currentPosition);
updateProgressBar();
}
#Override
public void onPrepared(MediaPlayer mp) {
l("onprepared");
mPrepared = true;
mp.start();
state = STARTED;
playImgV.setImageResource(R.drawable.pause_img);
}
private void l(String str) {
Log.i(TAG, str);
}
// ---------------------***************************************************************************
private class PlayerThread extends Thread {
public PlayerThread() {
start();
}
#Override
public void run() {
try {
stopped = false;
mPrepared = false;
resetTimeLabel();
mp.reset();
mp.setDataSource(url);
if (plLoc == PLAY_FROM_SERVER) {
mp.prepareAsync();
mp.setOnPreparedListener(QuranPlayerAct.this);
updatePlayerImg(R.drawable.play_img);
} else {
mp.prepare();
mp.start();
mPrepared = true;
state = STARTED;
updatePlayerImg(R.drawable.pause_img);
}
updatePlayerUI();
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void updatePlayerUI() {
runOnUiThread(new Runnable() {
#Override
public void run() {
songTitleLabel.setText(fName);
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
}
});
}
}
private void updatePlayerImg(final int playImg) {
runOnUiThread(new Runnable() {
#Override
public void run() {
playImgV.setImageResource(playImg);
}
});
}
// ------------------------------
#Override
public void onCompletion(MediaPlayer mp) {
track_no++;
if (track_no > musicFiles.size() - 1) {
track_no = 0;
}
playerRetLay.setVisibility(View.VISIBLE);
fName = musicFiles.get(track_no);
String filePath = MusicAppCommons.AIMANSANGAM_MUSIC_DIR + "/" + fName;
if (MusicAppCommons.checkFileExist(filePath)) {
url = filePath;
plLoc = PLAY_FROM_LOCAL;
} else {
url = MusicAppCommons.HTTP_AIMANSANGAM_COM_QURAN_FILES + fName;
url = url.replace(" ", "%20");
plLoc = PLAY_FROM_SERVER;
}
new PlayerThread();
}
#Override
public void clickedOnPlayBtn(int val) {
this.track_no = val;
l("song clicked");
playerRetLay.setVisibility(View.VISIBLE);
fName = musicFiles.get(val);
String filePath = MusicAppCommons.AIMANSANGAM_MUSIC_DIR + "/" + fName;
if (MusicAppCommons.checkFileExist(filePath)) {
url = filePath;
plLoc = PLAY_FROM_LOCAL;
} else {
url = MusicAppCommons.HTTP_AIMANSANGAM_COM_QURAN_FILES + fName;
url = url.replace(" ", "%20");
plLoc = PLAY_FROM_SERVER;
}
new PlayerThread();
}
}