Android mediaplayer volume change issues after phone call - android

I am using a service in my mp3 player to play media. I use mediaplayer object to play music. Normally the volume keys work when the music is playing. I also used Telephony Manager in my service to check phone calls. And I start and stop the music when the call is disconnected and is in progress respectively. But after the disconnection of phone call, the volume keys stopped working. I can see the dialog of volume change. But the sound volume don't change. Any idea? It is even happening in native player.
My player service:
public class PPlayService extends Service {
public static final int NOTIFICATION_NUMBER = 0;
Context conte;
MediaPlayer playHandler;
BroadcastReceiver broadcaster;
IncomingHandler mServiceHandler;
String online = "", link = "", name = "";
boolean playing = false;
boolean currentFlag = true;
Runnable runnable;
String[] uris, names;
int send;
SharedPreferences pre;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
AudioManager am;
// ........
PhoneStateListener phoneStateListener;
TelephonyManager mgr;
boolean notFromTelephone = false;
RemoteViews contentView;
BroadcastReceiver stopFromNoti, forwardFromNoti, backwardFromNoti;
Thread th;
public void handleMessage(Message msg) {
try {
playing = false;
if (playHandler != null) {
playHandler.setOnPreparedListener(null);
playHandler.setOnCompletionListener(null);
}
currentFlag = true;
System.gc();
if (online.equals("0")) {
contentView = new RemoteViews(getPackageName(),
R.layout.offline_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
PendingIntent backSong = PendingIntent.getBroadcast(conte, 0,
new Intent("backwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.backward_noti,
backSong);
PendingIntent frontSong = PendingIntent.getBroadcast(conte, 0,
new Intent("forwardFromNoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.forward_noti,
frontSong);
} else {
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0,
new Intent("stopfromnoti"),
PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti,
pit);
}
Intent intt = new Intent(getBaseContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(getBaseContext(), 0,
intt, 0);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setContentIntent(pi).setAutoCancel(false);
notificationManager.notify(
Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.LOADING);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
if (playHandler != null) {
playing = false;
playHandler.reset();
} else {
playHandler = new MediaPlayer();
}
if (online.equals("1")) {
// Online Stream
playHandler.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
playHandler.setDataSource(link);
playHandler.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
if (playHandler != null) {
if (!playHandler.isPlaying()) {
playSongNow();
}
}
}
});
playHandler.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
} else {
// Offline Stream
playHandler = MediaPlayer.create(conte, Uri.parse(link));
playSongNow();
}
} catch (Exception e) {
}
}
#Override
public void onCreate() {
conte = this;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
am.requestAudioFocus(new OnAudioFocusChangeListener() {
#Override
public void onAudioFocusChange(int focusChange) {
}
}, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT,
AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
forwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i >= send - 1) {
if (send > 0) {
name = names[0];
link = uris[0];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i + 1];
link = uris[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
backwardFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
getSD();
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
}
};
stopFromNoti = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (playHandler != null) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime", playHandler.getDuration() / 1000);
conte.sendBroadcast(in);
playHandler.reset();
stopSelf();
}
stopSelf();
}
};
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
if (!notFromTelephone) {
notFromTelephone = false;
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
}
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
if (playHandler.isPlaying()) {
playing = false;
playHandler.pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
pre = getSharedPreferences("download", 0);
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
contentView = new RemoteViews(getPackageName(),
R.layout.online_notification_layout);
PendingIntent pit = PendingIntent.getBroadcast(conte, 0, new Intent(
"stopfromnoti"), PendingIntent.FLAG_UPDATE_CURRENT);
contentView.setOnClickPendingIntent(R.id.play_or_pause_noti, pit);
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon).setContent(contentView)
.setAutoCancel(false).setContentIntent(pit);
startForeground(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.build());
broadcaster = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getExtras().getInt("action") == Mp3Constants.PAUSE) {
if (playHandler != null)
if (playHandler.isPlaying()) {
playing = false;
notFromTelephone = true;
playHandler.pause();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.PLAY) {
if (playHandler != null)
if (!playHandler.isPlaying()) {
playSongNow();
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.STOP) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
stopSelf();
} else if (arg1.getExtras().getInt("action") == Mp3Constants.SEEK) {
if (playHandler != null) {
{
playHandler.seekTo(arg1.getExtras()
.getInt("seekto") * 1000);
}
}
} else if (arg1.getExtras().getInt("action") == Mp3Constants.FORWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i >= send - 1) {
// if (send > 0) {
// name = names[0];
// link = uris[0];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i + 1];
// link = uris[i + 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
} else if (arg1.getExtras().getInt("action") == Mp3Constants.BACKWARD) {
if (playHandler != null) {
playHandler.reset();
playing = false;
}
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
int i = 0;
for (i = 0; i < send; i++) {
if (link.equalsIgnoreCase(uris[i])) {
break;
}
}
if (i == send || i == 0) {
if (send > 0) {
name = names[send - 1];
link = uris[send - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
} else {
name = names[i - 1];
link = uris[i - 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
}
// for (int i = 0; i < send - 1; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// link = uris[i - 1];
// name = names[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler
// .obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// break;
// }
// }
}
}
// getSD();
// int i = 0;
// for (i = 0; i < send; i++) {
// if (link.equalsIgnoreCase(uris[i])) {
// break;
// }
// }
// if (i == send || i == 0) {
// if (send > 0) {
// name = names[send - 1];
// link = uris[send - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
// } else {
// name = names[i - 1];
// link = uris[i - 1];
// pre.edit().putString("name", name);
// pre.edit().putString("online", online);
// pre.edit().putString("link", link);
// Message msg = mServiceHandler.obtainMessage();
// msg.arg1 = 1;
// mServiceHandler.sendMessage(msg);
// }
}
}
};
registerReceiver(broadcaster, new IntentFilter(
"com.codebrew.bestmp3downloader.PPlayService"));
registerReceiver(stopFromNoti, new IntentFilter("stopfromnoti"));
registerReceiver(forwardFromNoti, new IntentFilter("forwardFromNoti"));
registerReceiver(backwardFromNoti, new IntentFilter("backwardFromNoti"));
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceHandler = new IncomingHandler(PPlayService.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
online = pre.getString("online", "0");
link = pre.getString("link", "");
name = pre.getString("name", "");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
unregisterReceiver(broadcaster);
unregisterReceiver(stopFromNoti);
unregisterReceiver(forwardFromNoti);
unregisterReceiver(backwardFromNoti);
if (playHandler != null) {
if (playHandler.isPlaying()) {
playHandler.stop();
}
playHandler = null;
}
if (mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
super.onDestroy();
notificationManager.cancel(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER);
}
public void playSongNow() {
try {
playing = true;
playHandler.start();
runnable = new Runnable() {
public void run() {
while (playing) {
if (playing) {
try {
Intent in = new Intent(
Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.PLAYING);
if (playHandler.getCurrentPosition() / 1000 == playHandler
.getDuration() / 1000)
th.stop();
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
if (currentFlag) {
currentFlag = false;
contentView.setTextViewText(
R.id.name_of_the_song, name);
notificationManager
.notify(Mp3Constants.NOTIFICATION_NUMBER_FOR_PLAYER,
mBuilder.setContent(
contentView)
.build());
}
conte.sendBroadcast(in);
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
};
th = new Thread(runnable);
th.start();
playHandler.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playing = false;
pre.edit().putBoolean("stopped", true).commit();
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("status", Mp3Constants.COMPLETED);
in.putExtra("name", name);
try {
in.putExtra("currentTime",
playHandler.getCurrentPosition() / 1000);
in.putExtra("totalTime",
playHandler.getDuration() / 1000);
} catch (Exception e) {
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
}
conte.sendBroadcast(in);
if (online.equals("0")) {
if (pre.getBoolean("repeat", false)) {
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
getSD();
if (pre.getBoolean("shuffle", false)) {
Random r = new Random();
int x = r.nextInt(send);
link = uris[x];
name = names[x];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
} else {
for (int i = 0; i < send - 1; i++) {
if (link.equalsIgnoreCase(uris[i])) {
link = uris[i + 1];
name = names[i + 1];
pre.edit().putString("name", name);
pre.edit().putString("online", online);
pre.edit().putString("link", link);
Message msg = mServiceHandler
.obtainMessage();
msg.arg1 = 1;
mServiceHandler.sendMessage(msg);
break;
}
}
}
}
}
if (online.equals("1")) {
// stopSelf();
}
}
});
} catch (Exception e) {
playing = false;
Intent in = new Intent(Mp3Constants.NOTIFICATION);
in.putExtra("download", "0");
in.putExtra("online", online);
in.putExtra("name", name);
in.putExtra("status", Mp3Constants.FAILED);
in.putExtra("currentTime", 0);
in.putExtra("totalTime", 0);
conte.sendBroadcast(in);
Toast.makeText(
getBaseContext(),
"Error playing: "
+ name
+ "\nFile broken or deleted! Please try another song",
Toast.LENGTH_SHORT).show();
stopSelf();
}
}
private void getSD() {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return;
}
Arrays.sort(files, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return +1;
} else if (((File) o1).lastModified() < ((File) o2)
.lastModified()) {
return -1;
} else {
return 0;
}
}
});
send = files.length;
uris = new String[send];
names = new String[send];
for (int i = 0; i < send; i++) {
File file = files[i];
// take the file name only
double size = file.length();
size = size / (1024 * 1024);
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
uris[send - 1 - i] = file.getPath();
names[send - 1 - i] = myfile;
}
}
static class IncomingHandler extends Handler {
private final WeakReference<PPlayService> mService;
IncomingHandler(PPlayService service) {
mService = new WeakReference<PPlayService>(service);
}
#Override
public void handleMessage(Message msg) {
PPlayService service = mService.get();
if (service != null) {
service.handleMessage(msg);
}
}
}
}

Related

Android saving audio/mp3 file to external storage

I have question about saving audio/mp3
file to external storage
after saving the file it show in external storage
but when I open any android music player the file not showing there
I try to change the folder to "/storage/emulated/0/Music/" still not showing
even on download folder nothing.
the app is for download music from YouTube using API
public class DownloadedActivity extends AppCompatActivity implements AdapterMusicDownloaded.ClickCallBack, View.OnClickListener {
private RecyclerView lvManager;
private AdapterMusicDownloaded adapterMusicSearch;
private ArrayList<ItemMusicDownloaded> arrayList = new ArrayList<>();
private LinearLayout llEmptyFile;
private static final String AUTHORITY = "com.free.music.downloader" + ".fileprovider";
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
public static final String UPDATE_MUSIC = "update_music";
private ImageView imgBackSearch;
private InterstitialAd mInterstitialAd;
private AdView adView;
private ProgressBar loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_downloaded_songs);
initViews();
}
private void initViews() {
loading = findViewById(R.id.loading);
adView = findViewById(R.id.adView);
initAdsFull();
MobileAds.initialize(this, getResources().getString(R.string.mobile_id));
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
llEmptyFile = findViewById(R.id.ll_empty_file);
imgBackSearch = findViewById(R.id.img_back_downloaded);
imgBackSearch.setOnClickListener(this);
lvManager = findViewById(R.id.lv_main);
LinearLayoutManager manager = new LinearLayoutManager(this);
manager.setOrientation(LinearLayoutManager.VERTICAL);
adapterMusicSearch = new AdapterMusicDownloaded(arrayList, this);
adapterMusicSearch.setCallBack(this);
lvManager.setLayoutManager(manager);
lvManager.setAdapter(adapterMusicSearch);
LoadAsync loadAsync = new LoadAsync();
loadAsync.execute();
}
#Override
public void clickItemMusic(int position) {
Intent playIntent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
final File photoFile = new File(arrayList.get(position).getLink());
Uri photoURI = FileProvider.getUriForFile(this, AUTHORITY, photoFile);
playIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
playIntent.setDataAndType(photoURI, "audio/*");
} else {
playIntent.setDataAndType(Uri.parse(arrayList.get(position).getLink()), "audio/*");
}
startActivity(playIntent);
}
#Override
public void clickOptionItemMusic(final int postion, View view) {
PopupMenu popupMenu = new PopupMenu(this, view);
popupMenu.inflate(R.menu.menu_option_main);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
File file = new File(arrayList.get(postion).getLink());
boolean deleted = file.delete();
if (deleted) {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_finish), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(DownloadedActivity.this, getResources().getString(R.string.delete_error), Toast.LENGTH_SHORT).show();
}
arrayList.remove(postion);
adapterMusicSearch.notifyDataSetChanged();
break;
case R.id.menu_share_main:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
final File photoFile = new File(arrayList.get(postion).getLink());
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri photoURI = FileProvider.getUriForFile(DownloadedActivity.this, AUTHORITY, photoFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, photoURI);
} else {
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(photoFile));
}
shareIntent.setType("audio/*");
startActivity(Intent.createChooser(shareIntent, "Share music"));
break;
default:
break;
}
return false;
}
});
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.img_back_downloaded) {
onBackPressed();
}
}
#Override
public void onBackPressed() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
finish();
}
}
private class LoadAsync extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
llEmptyFile.setVisibility(View.GONE);
loading.setVisibility(View.VISIBLE);
}
#SuppressLint("WrongThread")
#Override
protected String doInBackground(Void... voids) {
arrayList.clear();
File f = new File(PATH);
File[] files = f.listFiles();
if (f.exists()) {
if (files.length <= 0) {
Log.d("sizearrList", "0");
return "OK";
} else {
Log.d("sizearrList", "2");
arrayList.clear();
Arrays.sort(files, new Comparator() {
public int compare(Object o1, Object o2) {
if (((File) o1).lastModified() > ((File) o2).lastModified()) {
return -1;
} else if (((File) o1).lastModified() < ((File) o2).lastModified()) {
return +1;
} else {
return 0;
}
}
});
for (File aFile : files) {
if (!aFile.isDirectory()) {
String name = aFile.getName();
String path = aFile.getPath();
getTimeVideo(aFile.getAbsolutePath());
Date lastModified = getFileLastModified(path);
arrayList.add(new ItemMusicDownloaded(name, path, lastModified, getTimeVideo(aFile.getAbsolutePath())))
;
} else {
Log.d("myLog", "Do not add");
}
}
Log.d("sizeArrsss", arrayList.size() + "");
for (int i = 0; i < arrayList.size(); i++) {
Log.d("sizeArr", arrayList.get(i).getTitle());
}
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (arrayList.size() == 0) {
llEmptyFile.setVisibility(View.VISIBLE);
} else {
llEmptyFile.setVisibility(View.GONE);
}
loading.setVisibility(View.GONE);
adapterMusicSearch.notifyDataSetChanged();
}
}
public static Date getFileLastModified(String pathFile) {
File file = new File(pathFile);
return new Date(file.lastModified());
}
private void initAdsFull() {
mInterstitialAd = new InterstitialAd(this);
MobileAds.initialize(this,
getResources().getString(R.string.mobile_id));
mInterstitialAd.setAdUnitId(getResources().getString(R.string.ads_full));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
finish();
}
});
}
public long getTimeVideo(String pathFile) {
try {
MediaPlayer mp = MediaPlayer.create(this, Uri.parse(pathFile));
int duration = mp.getDuration();
mp.release();
return duration;
} catch (Exception e) {
return 0;
}
}
}
public class DownloadVideoAsyn extends AsyncTask<String, Integer, String> {
private String title;
private int check;
private NotificationCompat.Builder builder;
private NotificationManager manager;
private String CHANNEL_ID = "download_video_tiktok_auto";
private String pathVideo = title + ".mp3";
private int id = 1232;
private Context mContext;
private NotificationChannel mChannel;
Notification noti;
public DownloadVideoAsyn(String title, int check, Context context) {
this.title = title;
this.check = check;
this.mContext = context;
}
public static final String PATH = Environment.getExternalStorageDirectory().toString() + "/FreeMusic/";
private EventDownloadVideoCallBack callBack;
public void setCallBack(EventDownloadVideoCallBack callBack) {
this.callBack = callBack;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (check == 2) {
manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
builder = new NotificationCompat.Builder(mContext, CHANNEL_ID);
Intent iCancel = new Intent();
id = id + 1;
iCancel.putExtra("id", id);
iCancel.putExtra("pathVideo", pathVideo);
iCancel.setAction("CANCEL_ACTION");
PendingIntent PICancel = PendingIntent.getBroadcast(mContext, 0, iCancel, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setSmallIcon(R.drawable.ic_download)
.setContentTitle(title.replace("'", "") + ".mp3")
.setContentText(mContext.getString(R.string.download))
.setChannelId(CHANNEL_ID)
.setPriority(Notification.PRIORITY_MAX)
.addAction(R.drawable.ic_cancel, "Cancel", PICancel)
.setAutoCancel(true);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
mChannel = new NotificationChannel(CHANNEL_ID, "channel-name", importance);
mChannel.setSound(null, null);
manager.createNotificationChannel(mChannel);
}
}
}
#Override
protected String doInBackground(String... strings) {
String link = strings[0];
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
String path = PATH + title.replace("'", "") + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
try {
URL url = new URL(link);
// check folder exist
File folder = new File(PATH);
if (!folder.exists()) {
folder.mkdir();
}
Date currentTime = Calendar.getInstance().getTime();
title = currentTime.getTime() + "";
String path = PATH + title + ".mp3";
File file = new File(path);
long total = 0;
FileOutputStream fileOutputStream = new FileOutputStream(file);
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
int fileLength = connection.getContentLength();
//=============================
byte[] b = new byte[1024];
int count = inputStream.read(b);
while (count != -1) {
total += count;
fileOutputStream.write(b, 0, count);
count = inputStream.read(b);
int progress = (int) (total * 100 / fileLength);
publishProgress(progress);
if (check == 2) {
builder.setProgress(100, progress, false);
builder.setContentText(mContext.getString(R.string.download) + " " + progress + "%");
noti = builder.build();
noti.flags = Notification.FLAG_ONLY_ALERT_ONCE;
manager.notify(id, noti);
if (progress == 100) {
manager.cancel(id);
}
}
}
inputStream.close();
fileOutputStream.close();
} catch (Exception ex) {
return null;
}
}
return PATH + title + ".mp3";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
Uri uri = Uri.parse("file://" + "/storage/emulated/0/FreeMusic/" + s);
Intent scanFileIntent = new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri);
mContext.sendBroadcast(scanFileIntent);
callBack.downloadVideoFinish(s);
}
else {
callBack.downloadVideoFail("Error");
}
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (check == 1) {
if (callBack != null) {
callBack.updateProgress(values[0]);
}
}
}
public interface EventDownloadVideoCallBack {
void downloadVideoFinish(String s);
void updateProgress(int pro);
void downloadVideoFail(String fail);
}
}

How to fix Runtime Exception Unable to start Activity

06-28 17:05:23.694 13262-13262/io.hypertrack.sendeta.debug
E/AndroidRuntime: FATAL EXCEPTION: main
Process: io.hypertrack.sendeta.debug, PID: 13262
java.lang.RuntimeException: Unable to start activity ComponentInfo{io.hypertrack.sendeta.debug/io.hypertrack.sendeta.activities.MainActivity}:
android.view.InflateException: Binary XML file line #4: Error
inflating class java.lang.reflect.Constructor
io.hypertrack.sendeta.activities.MainActivity.onCreate(MainActivity.java:109)
public class MainActivity extends AppCompatActivity implements LocationListener {
protected static final int MY_PERMISSIONS_ACCESS_FINE_LOCATION = 1;
// Time in milliseconds; only reload weather if last update is longer ago than this value
private static final int NO_UPDATE_REQUIRED_THRESHOLD = 300000;
private static Map<String, Integer> speedUnits = new HashMap<>(3);
private static Map<String, Integer> pressUnits = new HashMap<>(3);
private static boolean mappingsInitialised = false;
Typeface weatherFont;
Weather todayWeather = new Weather();
TextView todayTemperature;
TextView todayDescription;
TextView todayWind;
TextView todayPressure;
TextView todayHumidity;
TextView todaySunrise;
TextView todaySunset;
TextView lastUpdate;
TextView todayIcon;
ViewPager viewPager;
TabLayout tabLayout;
View appView;
LocationManager locationManager;
ProgressDialog progressDialog;
int theme;
boolean destroyed = false;
private List<Weather> longTermWeather = new ArrayList<>();
private List<Weather> longTermTodayWeather = new ArrayList<>();
private List<Weather> longTermTomorrowWeather = new ArrayList<>();
public String recentCity = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// Initialize the associated SharedPreferences file with default values
PreferenceManager.setDefaultValues(this, R.xml.prefs, false);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
setTheme(theme = getTheme(prefs.getString("theme", "fresh")));
boolean darkTheme = theme == R.style.AppTheme_NoActionBar_Dark ||
theme == R.style.AppTheme_NoActionBar_Classic_Dark;
boolean blackTheme = theme == R.style.AppTheme_NoActionBar_Black ||
theme == R.style.AppTheme_NoActionBar_Classic_Black;
// Initiate activity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scrolling);
appView = findViewById(R.id.viewApp);
progressDialog = new ProgressDialog(MainActivity.this);
// Load toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (darkTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Dark);
} else if (blackTheme) {
toolbar.setPopupTheme(R.style.AppTheme_PopupOverlay_Black);
}
// Initialize textboxes
todayTemperature = (TextView) findViewById(R.id.todayTemperature);
todayDescription = (TextView) findViewById(R.id.todayDescription);
todayWind = (TextView) findViewById(R.id.todayWind);
todayPressure = (TextView) findViewById(R.id.todayPressure);
todayHumidity = (TextView) findViewById(R.id.todayHumidity);
todaySunrise = (TextView) findViewById(R.id.todaySunrise);
todaySunset = (TextView) findViewById(R.id.todaySunset);
lastUpdate = (TextView) findViewById(R.id.lastUpdate);
todayIcon = (TextView) findViewById(R.id.todayIcon);
weatherFont = Typeface.createFromAsset(this.getAssets(), "fonts/weather.ttf");
todayIcon.setTypeface(weatherFont);
// Initialize viewPager
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
destroyed = false;
initMappings();
// Preload data from cache
preloadWeather();
updateLastUpdateTime();
// Set autoupdater
AlarmReceiver.setRecurringAlarm(this);
}
public WeatherRecyclerAdapter getAdapter(int id) {
WeatherRecyclerAdapter weatherRecyclerAdapter;
if (id == 0) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTodayWeather);
} else if (id == 1) {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermTomorrowWeather);
} else {
weatherRecyclerAdapter = new WeatherRecyclerAdapter(this, longTermWeather);
}
return weatherRecyclerAdapter;
}
#Override
public void onStart() {
super.onStart();
updateTodayWeatherUI();
updateLongTermWeatherUI();
}
#Override
public void onResume() {
super.onResume();
if (getTheme(PreferenceManager.getDefaultSharedPreferences(this).getString("theme", "fresh")) != theme) {
// Restart activity to apply theme
overridePendingTransition(0, 0);
finish();
overridePendingTransition(0, 0);
startActivity(getIntent());
} else if (shouldUpdate() && isNetworkAvailable()) {
getTodayWeather();
getLongTermWeather();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
destroyed = true;
if (locationManager != null) {
try {
locationManager.removeUpdates(MainActivity.this);
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
private void preloadWeather() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
String lastToday = sp.getString("lastToday", "");
if (!lastToday.isEmpty()) {
new TodayWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastToday);
}
String lastLongterm = sp.getString("lastLongterm", "");
if (!lastLongterm.isEmpty()) {
new LongTermWeatherTask(this, this, progressDialog).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "cachedResponse", lastLongterm);
}
}
private void getTodayWeather() {
new TodayWeatherTask(this, this, progressDialog).execute();
}
private void getLongTermWeather() {
new LongTermWeatherTask(this, this, progressDialog).execute();
}
private void searchCities() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(this.getString(R.string.search_title));
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
input.setMaxLines(1);
input.setSingleLine(true);
alert.setView(input, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String result = input.getText().toString();
if (!result.isEmpty()) {
saveLocation(result);
}
}
});
alert.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Cancelled
}
});
alert.show();
}
private void saveLocation(String result) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
recentCity = preferences.getString("city", Constants.DEFAULT_CITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("city", result);
editor.commit();
if (!recentCity.equals(result)) {
// New location, update weather
getTodayWeather();
getLongTermWeather();
}
}
private void aboutDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Forecastie");
final WebView webView = new WebView(this);
String about = "<p>1.6.1</p>" +
"<p>A lightweight, opensource weather app.</p>" +
"<p>Developed by <a href='mailto:t.martykan#gmail.com'>Tomas Martykan</a></p>" +
"<p>Data provided by <a href='https://openweathermap.org/'>OpenWeatherMap</a>, under the <a href='http://creativecommons.org/licenses/by-sa/2.0/'>Creative Commons license</a>" +
"<p>Icons are <a href='https://erikflowers.github.io/weather-icons/'>Weather Icons</a>, by <a href='http://www.twitter.com/artill'>Lukas Bischoff</a> and <a href='http://www.twitter.com/Erik_UX'>Erik Flowers</a>, under the <a href='http://scripts.sil.org/OFL'>SIL OFL 1.1</a> licence.";
TypedArray ta = obtainStyledAttributes(new int[]{android.R.attr.textColorPrimary, R.attr.colorAccent});
String textColor = String.format("#%06X", (0xFFFFFF & ta.getColor(0, Color.BLACK)));
String accentColor = String.format("#%06X", (0xFFFFFF & ta.getColor(1, Color.BLUE)));
ta.recycle();
about = "<style media=\"screen\" type=\"text/css\">" +
"body {\n" +
" color:" + textColor + ";\n" +
"}\n" +
"a:link {color:" + accentColor + "}\n" +
"</style>" +
about;
webView.setBackgroundColor(Color.TRANSPARENT);
webView.loadData(about, "text/html", "UTF-8");
alert.setView(webView, 32, 0, 32, 0);
alert.setPositiveButton(R.string.dialog_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
private String setWeatherIcon(int actualId, int hourOfDay) {
int id = actualId / 100;
String icon = "";
if (actualId == 800) {
if (hourOfDay >= 7 && hourOfDay < 20) {
icon = this.getString(R.string.weather_sunny);
} else {
icon = this.getString(R.string.weather_clear_night);
}
} else {
switch (id) {
case 2:
icon = this.getString(R.string.weather_thunder);
break;
case 3:
icon = this.getString(R.string.weather_drizzle);
break;
case 7:
icon = this.getString(R.string.weather_foggy);
break;
case 8:
icon = this.getString(R.string.weather_cloudy);
break;
case 6:
icon = this.getString(R.string.weather_snowy);
break;
case 5:
icon = this.getString(R.string.weather_rainy);
break;
}
}
return icon;
}
public static String getRainString(JSONObject rainObj) {
String rain = "0";
if (rainObj != null) {
rain = rainObj.optString("3h", "fail");
if ("fail".equals(rain)) {
rain = rainObj.optString("1h", "0");
}
}
return rain;
}
private ParseResult parseTodayJson(String result) {
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
return ParseResult.CITY_NOT_FOUND;
}
String city = reader.getString("name");
String country = "";
JSONObject countryObj = reader.optJSONObject("sys");
if (countryObj != null) {
country = countryObj.getString("country");
todayWeather.setSunrise(countryObj.getString("sunrise"));
todayWeather.setSunset(countryObj.getString("sunset"));
}
todayWeather.setCity(city);
todayWeather.setCountry(country);
JSONObject coordinates = reader.getJSONObject("coord");
if (coordinates != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putFloat("latitude", (float) coordinates.getDouble("lon")).putFloat("longitude", (float) coordinates.getDouble("lat")).commit();
}
JSONObject main = reader.getJSONObject("main");
todayWeather.setTemperature(main.getString("temp"));
todayWeather.setDescription(reader.getJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = reader.getJSONObject("wind");
todayWeather.setWind(windObj.getString("speed"));
if (windObj.has("deg")) {
todayWeather.setWindDirectionDegree(windObj.getDouble("deg"));
} else {
Log.e("parseTodayJson", "No wind direction available");
todayWeather.setWindDirectionDegree(null);
}
todayWeather.setPressure(main.getString("pressure"));
todayWeather.setHumidity(main.getString("humidity"));
JSONObject rainObj = reader.optJSONObject("rain");
String rain;
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = reader.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
todayWeather.setRain(rain);
final String idString = reader.getJSONArray("weather").getJSONObject(0).getString("id");
todayWeather.setId(idString);
todayWeather.setIcon(setWeatherIcon(Integer.parseInt(idString), Calendar.getInstance().get(Calendar.HOUR_OF_DAY)));
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastToday", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateTodayWeatherUI() {
try {
if (todayWeather.getCountry().isEmpty()) {
preloadWeather();
return;
}
} catch (Exception e) {
preloadWeather();
return;
}
String city = todayWeather.getCity();
String country = todayWeather.getCountry();
DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(getApplicationContext());
getSupportActionBar().setTitle(city + (country.isEmpty() ? "" : ", " + country));
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
// Temperature
float temperature = UnitConvertor.convertTemperature(Float.parseFloat(todayWeather.getTemperature()), sp);
if (sp.getBoolean("temperatureInteger", false)) {
temperature = Math.round(temperature);
}
// Rain
double rain = Double.parseDouble(todayWeather.getRain());
String rainString = UnitConvertor.getRainString(rain, sp);
// Wind
double wind;
try {
wind = Double.parseDouble(todayWeather.getWind());
} catch (Exception e) {
e.printStackTrace();
wind = 0;
}
wind = UnitConvertor.convertWind(wind, sp);
// Pressure
double pressure = UnitConvertor.convertPressure((float) Double.parseDouble(todayWeather.getPressure()), sp);
todayTemperature.setText(new DecimalFormat("0.#").format(temperature) + " " + sp.getString("unit", "°C"));
todayDescription.setText(todayWeather.getDescription().substring(0, 1).toUpperCase() +
todayWeather.getDescription().substring(1) + rainString);
if (sp.getString("speedUnit", "m/s").equals("bft")) {
todayWind.setText(getString(R.string.wind) + ": " +
UnitConvertor.getBeaufortName((int) wind) +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
} else {
todayWind.setText(getString(R.string.wind) + ": " + new DecimalFormat("0.0").format(wind) + " " +
localize(sp, "speedUnit", "m/s") +
(todayWeather.isWindDirectionAvailable() ? " " + getWindDirectionString(sp, this, todayWeather) : ""));
}
todayPressure.setText(getString(R.string.pressure) + ": " + new DecimalFormat("0.0").format(pressure) + " " +
localize(sp, "pressureUnit", "hPa"));
todayHumidity.setText(getString(R.string.humidity) + ": " + todayWeather.getHumidity() + " %");
todaySunrise.setText(getString(R.string.sunrise) + ": " + timeFormat.format(todayWeather.getSunrise()));
todaySunset.setText(getString(R.string.sunset) + ": " + timeFormat.format(todayWeather.getSunset()));
todayIcon.setText(todayWeather.getIcon());
}
public ParseResult parseLongTermJson(String result) {
int i;
try {
JSONObject reader = new JSONObject(result);
final String code = reader.optString("cod");
if ("404".equals(code)) {
if (longTermWeather == null) {
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
}
return ParseResult.CITY_NOT_FOUND;
}
longTermWeather = new ArrayList<>();
longTermTodayWeather = new ArrayList<>();
longTermTomorrowWeather = new ArrayList<>();
JSONArray list = reader.getJSONArray("list");
for (i = 0; i < list.length(); i++) {
Weather weather = new Weather();
JSONObject listItem = list.getJSONObject(i);
JSONObject main = listItem.getJSONObject("main");
weather.setDate(listItem.getString("dt"));
weather.setTemperature(main.getString("temp"));
weather.setDescription(listItem.optJSONArray("weather").getJSONObject(0).getString("description"));
JSONObject windObj = listItem.optJSONObject("wind");
if (windObj != null) {
weather.setWind(windObj.getString("speed"));
weather.setWindDirectionDegree(windObj.getDouble("deg"));
}
weather.setPressure(main.getString("pressure"));
weather.setHumidity(main.getString("humidity"));
JSONObject rainObj = listItem.optJSONObject("rain");
String rain = "";
if (rainObj != null) {
rain = getRainString(rainObj);
} else {
JSONObject snowObj = listItem.optJSONObject("snow");
if (snowObj != null) {
rain = getRainString(snowObj);
} else {
rain = "0";
}
}
weather.setRain(rain);
final String idString = listItem.optJSONArray("weather").getJSONObject(0).getString("id");
weather.setId(idString);
final String dateMsString = listItem.getString("dt") + "000";
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(Long.parseLong(dateMsString));
weather.setIcon(setWeatherIcon(Integer.parseInt(idString), cal.get(Calendar.HOUR_OF_DAY)));
Calendar today = Calendar.getInstance();
if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) {
longTermTodayWeather.add(weather);
} else if (cal.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR) + 1) {
longTermTomorrowWeather.add(weather);
} else {
longTermWeather.add(weather);
}
}
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(MainActivity.this).edit();
editor.putString("lastLongterm", result);
editor.commit();
} catch (JSONException e) {
Log.e("JSONException Data", result);
e.printStackTrace();
return ParseResult.JSON_EXCEPTION;
}
return ParseResult.OK;
}
private void updateLongTermWeatherUI() {
if (destroyed) {
return;
}
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
Bundle bundleToday = new Bundle();
bundleToday.putInt("day", 0);
RecyclerViewFragment recyclerViewFragmentToday = new RecyclerViewFragment();
recyclerViewFragmentToday.setArguments(bundleToday);
viewPagerAdapter.addFragment(recyclerViewFragmentToday, getString(R.string.today));
Bundle bundleTomorrow = new Bundle();
bundleTomorrow.putInt("day", 1);
RecyclerViewFragment recyclerViewFragmentTomorrow = new RecyclerViewFragment();
recyclerViewFragmentTomorrow.setArguments(bundleTomorrow);
viewPagerAdapter.addFragment(recyclerViewFragmentTomorrow, getString(R.string.tomorrow));
Bundle bundle = new Bundle();
bundle.putInt("day", 2);
RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
recyclerViewFragment.setArguments(bundle);
viewPagerAdapter.addFragment(recyclerViewFragment, getString(R.string.later));
int currentPage = viewPager.getCurrentItem();
viewPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
if (currentPage == 0 && longTermTodayWeather.isEmpty()) {
currentPage = 1;
}
viewPager.setCurrentItem(currentPage, false);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private boolean shouldUpdate() {
long lastUpdate = PreferenceManager.getDefaultSharedPreferences(this).getLong("lastUpdate", -1);
boolean cityChanged = PreferenceManager.getDefaultSharedPreferences(this).getBoolean("cityChanged", false);
// Update if never checked or last update is longer ago than specified threshold
return cityChanged || lastUpdate < 0 || (Calendar.getInstance().getTimeInMillis() - lastUpdate) > NO_UPDATE_REQUIRED_THRESHOLD;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}

Notification created from Service disappears from status bar

I have a webservice and I am using ksoap2 to connect to it and upload some pictures.
The process is:
Open the gallery
Select a few pictures
Share to my app
Start a foreground service
send the basic information to this service, like an array with all the picture's path
handle the intent and take the bundles
and start the foreground notification with the proper flag and with startForeground(id,noty)
The problem:
Everything goes right. Uploading and showing the items uploaded ...until...suddenly the notification just disappear from the bar.
After a while it shows by itself again and continues the upload, I tried to set some stuff to get the last item uploaded and start from there, I don't know if I am doing right and I would like to have an advice about this.
This is the Activity from where I call the Service:
Intent mServiceIntent = new Intent(this, UploadService.class);
Bundle bund = new Bundle();
bund.putStringArray("pathList", pictureList);
bund.putString("tags", tag);
boolean hasGeotag = UserManagerClass.UserLogged.isActiveLocation();
bund.putBoolean("hasGeotag", hasGeotag);
if (hasGeotag) {
GeoTag gtag = UserManagerClass.UserLocation;
bund.putDouble("latitude", gtag.getLatitude());
bund.putDouble("longitude", gtag.getLongitude());
bund.putString("city", gtag.getCity());
bund.putString("country", gtag.getCountry());
bund.putString("address", gtag.getAddress());
}
bund.putInt("idOwner", IDOWNER);
bund.putInt("idUser", UserManagerClass.UserLogged.getID());
bund.putInt("albumindex", albumIndex);
bund.putInt("privacyindex", privacyIndex);
bund.putString("comment", comment);
mServiceIntent.putExtras(bund);
startService(mServiceIntent);
and this is the code of the Service:
public class UploadService extends Service {
private static final int myID = 1433;
private static final String PREF_NAME = "SERVICEUPLOAD";
private static final String UPLOADED_PATH = "UPLOADED_";
private static int position;
private int albumIndex;
private String comment;
private boolean hasGeotag;
private int idOwner;
private int idUser;
private GeoTag location;
private String[] pathList;
private int privacyIndex;
private SoapPost sp;
private String tags;
private NotificationManager nManager;
private PendingIntent pi;
#Override
public void onCreate() {
Log.e("step 1", "entered to create");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
private void exit() {
Log.e("step 10", "ending...");
deletePosition();
Log.e("step 12", "ended");
this.stopForeground(true);
updateNotification(true);
}
void createNotification() {
Log.e("step 4", "entered to create notification");
// In this sample, we'll use the same text for the ticker and the
// expanded notification
CharSequence text = getText(R.string.upload_waiting);
//
pi = PendingIntent.getActivity(this, 0, new Intent(), Notification.FLAG_FOREGROUND_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.add_comment_icon);
builder.setTicker(text);
builder.setContentIntent(pi);
builder.setContentText(text);
builder.setContentTitle(text);
startForeground(myID, builder.build());
}
private void updateNotification(boolean completed) {
Log.e("step 8", "updating notification");
String ticker = String.format(getResources().getString(R.string.upload_uploading_tick), position);
String message = String.format(getResources().getString(R.string.upload_uploading_message_progress), position, pathList.length);
String title = String.format(getResources().getString(R.string.upload_uploading_title), position);
String title_completed = getResources().getString(R.string.upload_uploading_title_completed);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setSmallIcon(R.drawable.add_comment_icon);
builder.setContentText(message);
builder.setTicker(ticker);
if (!completed)
builder.setContentTitle(title);
else {
builder.setContentTitle(title_completed);
pi = PendingIntent.getActivity(this, 0, new Intent(), 0);
}
builder.setContentIntent(pi);
if (completed)
nManager.notify(myID, builder.build());
else
startForeground(myID, builder.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("step 2", "entered to onstart");
handleIntent(intent);
return START_STICKY;
}
void handleIntent(Intent data) {
Log.e("step 3", "entered to handle");
// GETS THE POSITIONS IF THE SERVICE WAS STOPPED BEFORE
// RETURN 0 IF IT WASNT
getPosition();
//
if (data == null)
this.stopForeground(true);
Bundle dt = data.getExtras();
tags = dt.getString("tags");
pathList = dt.getStringArray("pathList");
hasGeotag = dt.getBoolean("hasGeotag");
if (hasGeotag) {
location = new GeoTag();
location.setLatitude(dt.getDouble("latitude"));
location.setLongitude(dt.getDouble("longitude"));
location.setAddress(dt.getString("address"));
location.setCity(dt.getString("city"));
location.setCountry(dt.getString("country"));
}
idOwner = dt.getInt("idOwner");
idUser = dt.getInt("idUser");
albumIndex = dt.getInt("albumindex");
privacyIndex = dt.getInt("privacyindex");
comment = dt.getString("comment");
// isCover = dt.getBoolean("isCover");
sp = new SoapPost();
// CREATES THE NOTFICATION
createNotification();
// FINALLY SEND THE DATA TO THE WEB SERVICE
sendData();
}
private void sendData() {
Log.e("step 4", "entered to send data");
for (String fl : pathList) {
Log.e("step 5", "sending... " + fl);
if (fl != null && !fl.equals(UPLOADED_PATH)) {
try {
String[] dataup = new String[10];
if (hasGeotag) {
dataup = new String[15];
dataup[10] = String.valueOf(location.getLatitude());
dataup[11] = String.valueOf(location.getLongitude());
dataup[12] = location.getAddress();
dataup[13] = location.getCity();
dataup[14] = location.getCountry();
}
if (comment.length() > 0)
dataup[0] = URLEncoder.encode(comment, "UTF-8");
else
dataup[0] = "";
dataup[1] = String.valueOf(idOwner);
dataup[2] = String.valueOf(idUser);
dataup[3] = "2";
dataup[4] = "";
dataup[5] = String.valueOf(albumIndex);
dataup[6] = String.valueOf(privacyIndex);
dataup[7] = "";
dataup[8] = "";
dataup[9] = "";
File file = new File(fl);
// CONTINUE ONLY IF THE FILE EXISTS
if (file.exists()) {
Log.e("step 6", "file exists true");
// SETTING WIDTH AND HEIGHT
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fl, options);
int wth = options.outWidth;
int hth = options.outHeight;
long lenght = file.length();
// END W AND H
String b64 = null;
b64 = Base64.encodeToString(PictureManagerClass.getBytesFromFile(file), Base64.DEFAULT);
file = null;
// SETTING
// 4 BASE64
// 7 W
// 8 H
// 9 L
dataup[4] = b64;
dataup[7] = String.valueOf(wth);
dataup[8] = String.valueOf(hth);
dataup[9] = String.valueOf(lenght);
Log.e("step 7", "uploading... " + fl);
// SET THE CURRENT ITEM AS UPLOADED
pathList[position] = null;
// SAVE THE ACTUAL POSITION
savePosition();
sp.uploadPicture(dataup, tags, SoapPost.UPLOAD_PICTURE);
position++;
updateNotification(false);
}// END FILE EXISTS
}
catch (Exception ex) {
// SAVE THE ACTUAL POSITION
savePosition();
//
StackTraceElement[] stack = ex.getStackTrace();
String Trace = " ";
for (StackTraceElement line : stack) {
Trace += line.toString();
}
Log.e("SERVICE: ", Trace);
}
}// END FL NULL
}// END FOR
exit();
}
#Override
public void onDestroy() {
// SAVE THE ACTUAL POSITION
savePosition();
super.onDestroy();
}
#Override
public void onLowMemory() {
// SAVE THE ACTUAL POSITION
savePosition();
super.onLowMemory();
}
void savePosition() {
Log.e("step 9", "saving position");
// SET THE VALUES FROM PATHS TO SET TO SAVE IT INTO PREFERENCES
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("position", position);
Set<String> set = new HashSet<String>();
if (pathList != null) {
for (int i = 0; i < position; i++)
pathList[i] = null;
for (int i = position; i < pathList.length; i++)
if (pathList[i] != null)
set.add(pathList[i]);
}
if (pathList != null)
editor.putStringSet("pathList", set);
editor.commit();
}
void getPosition() {
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
position = prefs.getInt("position", 0);
Log.e("step 3.1", position + "");
Set<String> set = new HashSet<String>();
set = prefs.getStringSet("pathList", set);
int pos = 0;
for (String path : set) {
pathList = new String[set.size()];
pathList[pos] = path;
pos++;
}
}
void deletePosition() {
Log.e("step 11", "clear...");
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.commit();
}
/* (non-Javadoc)
* #see android.app.Service#onBind(android.content.Intent)
*/
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
FIXED
i fixed it...this is the new method sendData():
private void sendData() {
new Thread(new Runnable() {
#Override
public void run() {
for (String fl : pathList) {
if (fl != null && !fl.equals(UPLOADED_PATH)) {
try {
String[] dataup = new String[10];
if (hasGeotag) {
dataup = new String[15];
dataup[10] = String.valueOf(location.getLatitude());
dataup[11] = String.valueOf(location.getLongitude());
dataup[12] = location.getAddress();
dataup[13] = location.getCity();
dataup[14] = location.getCountry();
}
if (comment.length() > 0)
dataup[0] = URLEncoder.encode(comment, "UTF-8");
else
dataup[0] = "";
dataup[1] = String.valueOf(idOwner);
dataup[2] = String.valueOf(idUser);
dataup[3] = "2";
dataup[4] = "";
dataup[5] = String.valueOf(albumIndex);
dataup[6] = String.valueOf(privacyIndex);
dataup[7] = "";
dataup[8] = "";
dataup[9] = "";
File file = new File(fl);
// CONTINUE ONLY IF THE FILE EXISTS
if (file.exists()) {
// SETTING WIDTH AND HEIGHT
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fl, options);
int wth = options.outWidth;
int hth = options.outHeight;
long lenght = file.length();
// END W AND H
byte[] pic = PictureManagerClass.getBytesFromFile(file);
Log.e("picLength", pic.length + "");
file = null;
// SETTING
// 4 BASE64
// 7 W
// 8 H
// 9 L
dataup[4] = "";
dataup[7] = String.valueOf(wth);
dataup[8] = String.valueOf(hth);
dataup[9] = String.valueOf(lenght);
Log.e("step 7", "uploading... " + fl);
// SET THE CURRENT ITEM AS UPLOADED
pathList[position] = null;
// SAVE THE ACTUAL POSITION
savePosition();
String mes = sp.uploadPicture(dataup, tags, SoapPost.UPLOAD_PICTURE, pic);
Log.e("picID", mes);
pic = null;
dataup = null;
position++;
updateNotification(false);
Thread.sleep(1 * 1000);
}// END FILE EXISTS
}
catch (Exception ex) {
// SAVE THE ACTUAL POSITION
savePosition();
//
StackTraceElement[] stack = ex.getStackTrace();
String Trace = " ";
for (StackTraceElement line : stack) {
Trace += line.toString();
}
Log.e("SERVICE: ", Trace);
}
}// END FL NULL
}// END FOR
exit();
}
}).start();;
}
and now the notification doesnt hide until all files were uploaded ... thanks.

Download Manager failed the download

I am using DownloadManager to download the following url:
http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
But the downloading is failed. I even hit the url on browser and it works properly. Is it the problem of url parsing?
Code: DDownloadService.java
public class DDownloadService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
Context conte;
// NotificationManager notificationManager;
// NotificationCompat.Builder mBuilder;
boolean playing = false;
Runnable runnable;
SharedPreferences pre;
static int countOfCurrent = 0;
String downloadName, downloadUrl;
NotificationManager notificationManager;
NotificationCompat.Builder mBuilder;
// ..
static int downloadNumber = 0;
DownloadManager mgr[] = new DownloadManager[100];
long downloadIds[] = new long[100];
BroadcastReceiver cancelDownload;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
downloadNumber++;
downloadName = pre.getString("downloadname", "");
downloadName = viewSD(downloadName);
downloadUrl = pre.getString("downloadurl", "");
downloadName = downloadName.toLowerCase();
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "") + "|"
+ downloadName).commit();
pre.edit().putInt(downloadName + "no", +downloadNumber).commit();
mgr[downloadNumber] = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
try {
countOfCurrent++;
downloadIds[downloadNumber] = mgr[downloadNumber]
.enqueue(new DownloadManager.Request(Uri
.parse(downloadUrl))
.setAllowedNetworkTypes(
DownloadManager.Request.NETWORK_WIFI
| DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle("Downloading")
.setDescription(downloadName)
.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_HIDDEN)
.setDestinationInExternalPublicDir(
Environment.DIRECTORY_MUSIC,
downloadName)
.setVisibleInDownloadsUi(false));
pre.edit()
.putLong(downloadName + "id",
downloadIds[downloadNumber]).commit();
Timer myTimer = new Timer();
myTimer.schedule(new RegrowCornAnimate(downloadNumber,
downloadName), 0, 10);
} catch (IllegalStateException e) {
Toast.makeText(getBaseContext(), "No storage found!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (Exception e) {
Toast.makeText(getBaseContext(), " Something wrong happened!",
Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
#Override
public void onCreate() {
conte = this;
pre = getSharedPreferences("download", 0);
downloadName = pre.getString("downloadname", "");
downloadUrl = pre.getString("downloadurl", "");
cancelDownload = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
try {
mgr[pre.getInt(arg1.getExtras().getString("name") + "no", 0)]
.remove(pre.getLong(
arg1.getExtras().getString("name") + "id",
0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
registerReceiver(cancelDownload, new IntentFilter("cancelIt"));
notificationManager = (NotificationManager) conte
.getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(conte)
.setSmallIcon(R.drawable.icon)
.setContentTitle("Downloading in progress").setContentText("");
startForeground(55, mBuilder.build());
notificationManager.cancel(55);
HandlerThread thread = new HandlerThread("ServiceStartArguments", 0);
// //..................
// notificationManager = (NotificationManager) conte
// .getSystemService(Context.NOTIFICATION_SERVICE);
// mBuilder = new NotificationCompat.Builder(conte);
// RemoteViews remoteViews = new RemoteViews(getPackageName(),
// R.layout.notification_layout);
// try {
// mBuilder.setSmallIcon(R.drawable.icon);
// mBuilder.setAutoCancel(false).setOngoing(true)
// .setContent(remoteViews);
// Uri uri = RingtoneManager
// .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mBuilder.setSound(uri);
// notificationManager.notify(Mp3Constants.NOTIFICATION_NUMBER,
// mBuilder.build());
// } catch (Exception e) {
// e.printStackTrace();
// }
// //...................
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// online = intent.getExtras().getString("online");
// link = intent.getExtras().getString("link");
// name = intent.getExtras().getString("name");
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(cancelDownload);
}
class RegrowCornAnimate extends TimerTask {
private final int serial;
private final String name_of_da;
boolean startFlag = true, errorFlag = true;
RegrowCornAnimate(int serial, String name) {
this.serial = serial;
this.name_of_da = name;
}
public void run() {
// Do stuff
int dl_progress = 0;
try {
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(downloadIds[serial]);
Cursor c = mgr[serial].query(q);
c.moveToFirst();
long bytes_downloaded = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
long bytes_total = c
.getInt(c
.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
dl_progress = (int) ((bytes_downloaded * 100) / bytes_total);
pre.edit().putInt(name_of_da, dl_progress).commit();
switch (c.getInt(c
.getColumnIndex(DownloadManager.COLUMN_STATUS))) {
case DownloadManager.STATUS_FAILED:
// msg = "Download failed!";
// Toast.makeText(getBaseContext(), "Url Broken!",
// Toast.LENGTH_SHORT).show();
sendNotification(1, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
case DownloadManager.STATUS_PAUSED:
// msg = "Download paused!";
if (errorFlag) {
errorFlag = false;
sendNotification(7, serial, name_of_da, dl_progress);
}
break;
case DownloadManager.STATUS_PENDING:
// msg = "Download pending!";
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_RUNNING:
// msg = "Download in progress!";
errorFlag = true;
if (startFlag) {
if (verifyFromSD(name_of_da)) {
startFlag = false;
sendBroadcast(new Intent("start"));
}
}
sendNotification(0, serial, name_of_da, dl_progress);
break;
case DownloadManager.STATUS_SUCCESSFUL:
// msg = "Download complete!";
pre.edit()
.putString(
"songsInDownload",
pre.getString("songsInDownload", "")
.replace("|" + name_of_da, ""))
.commit();
pre.edit().putInt(name_of_da, 100);
sendNotification(0, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
default:
// msg = "Download is nowhere in sight";
sendNotification(10, serial, name_of_da, dl_progress);
this.cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
break;
}
c.close();
} catch (Exception e) {
e.printStackTrace();
sendNotification(7, serial, name_of_da, dl_progress);
cancel();
countOfCurrent--;
if (countOfCurrent == 0)
stopSelf();
}
}
}
public void sendNotification(int tmout, int nin, String name, int progress) {
if (tmout == 0) {
// notificationManager.notify(nin, mBuilder.build());
if (progress >= 100) {
// notificationManager.cancel(nin);
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Completed").setContentText(name)
.setAutoCancel(true).setOngoing(false)
.setProgress(100, 100, false);
Uri ttt = Uri.parse(Environment.getExternalStorageDirectory()
.toString() + "/Music/" + name);
pre.edit().putInt("retry", 1).commit();
Intent inten = new Intent(Intent.ACTION_VIEW, ttt);
String arr[] = name.split("\\.");
inten.setDataAndType(ttt, "audio/" + arr[arr.length - 1]);
PendingIntent i = PendingIntent.getActivity(getBaseContext(),
0, inten, 0);
mBuilder.setContentIntent(i);
notificationManager.notify(nin, mBuilder.build());
} else {
mBuilder.setContentTitle("Downloading: " + name)
.setContentText(progress + " %")
.setSmallIcon(R.drawable.icon).setAutoCancel(false)
.setOngoing(true);
mBuilder.setProgress(100, progress, false);
notificationManager.notify(nin, mBuilder.build());
}
} else {
if (tmout == 1) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Failed: " + name)
.setContentText(progress + " %").setAutoCancel(true)
.setProgress(100, progress, false).setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else if (tmout == 7) {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Cancelled: " + name)
.setAutoCancel(true).setProgress(100, progress, false)
.setOngoing(false);
// Intent intnt = new Intent(Mp3Constants.NOTIFICATION);
// intnt.putExtra("resume", "1");
// intnt.putExtra("url", urlD);
// intnt.putExtra("name", name);
// intnt.putExtra("nin", nin);
// PendingIntent i = PendingIntent
// .getBroadcast(conte, 0, intnt, 0);
// mBuilder.setContentIntent(i);
} else {
mBuilder.setSmallIcon(R.drawable.icon)
.setContentTitle("Interrupted: " + name)
.setContentText("No storage found").setAutoCancel(true)
.setOngoing(false);
}
notificationManager.notify(nin, mBuilder.build());
}
}
private String viewSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return naame;
}
while (true) {
String newName = naame;
naame = relooper(files, newName);
if (newName.equals(naame))
break;
}
return naame;
}
public String relooper(File[] files, String name) {
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (name.equalsIgnoreCase(myfile))
return "copy_of_" + name;
}
return name;
}
private boolean verifyFromSD(String naame) {
File f = new File(Environment.getExternalStorageDirectory().toString()
+ "/Music");
File[] files = f.listFiles();
if (files == null) {
return false;
}
int send = files.length;
for (int i = 0; i < send; i++) {
File file = files[i];
String myfile = file
.getPath()
.substring(file.getPath().lastIndexOf("/") + 1,
file.getPath().length()).toLowerCase();
if (naame.equalsIgnoreCase(myfile))
return true;
}
return false;
}
}
EDIT: I found the problem from logcat:
01-07 11:47:37.313: W/DownloadManager(18893): Exception for id 285: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): java.lang.IllegalArgumentException: Illegal character in path at index 115: http://dj-videos.us/Music/XclusiveSinGleTrack/320%20Kbps/November%202013/Yo%20Yo%20Honey%20Singh%20-%20Blue%20Eyes-[DJKANG.Com].mp3
01-07 11:47:37.313: W/DownloadManager(18893): at java.net.URI.create(URI.java:727)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getProxy(Proxy.java:113)
01-07 11:47:37.313: W/DownloadManager(18893): at android.net.Proxy.getPreferredHttpHost(Proxy.java:218)
01-07 11:47:37.313: W/DownloadManager(18893): at com.android.providers.downloads.DownloadThread.run(DownloadThread.java:174)
But I still need to know which format to use to parse url for DownloadManager.
The IllegalArgumentException occurs when the URL contains illegal characters such as [ ]. As mentioned in the comments, you need to encode such characters using URLEncoder.
I implemented it this way in my code -
private String checkUrl(String url) {
if(url.contains("[")) {
String[] a = url.split("\\[");
String b = "[" + a[1]; //contains text after [ e.g. [DJKANG.Com].mp3
url = a[0] + URLEncoder.encode(b, "UTF-8"); // encodes illegal characters
}
return url;
}

Android : To shift the common code of all activities to a base class.. the application crashes

I have the following BaseClass:
public class BaseClass extends Activity implements MusicUtils.Defs,
View.OnTouchListener, View.OnLongClickListener {
private static final int USE_AS_RINGTONE = CHILD_MENU_BASE;
private boolean mOneShot = false;
private boolean mSeeking = false;
private boolean mDeviceHasDpad;
private long mStartSeekenter code herePos = 0;
private long mLastSeekEventTime;
private IMediaPlaybackService mService = null;
private RepeatingImageButton mPrevButton;
private ImageButton mPauseButton;
private RepeatingImageButton mNextButton;
private Worker mAlbumArtWorker;
private AlbumArtHandler mAlbumArtHandler;
private Toast mToast;
private int mTouchSlop;
private ServiceToken mToken;
public BaseClass() {
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
mAlbumArtWorker = new Worker("album art worker");
mAlbumArtHandler = new AlbumArtHandler(mAlbumArtWorker.getLooper());
mCurrentTime = (TextView) findViewById(R.id.currenttime);
mTotalTime = (TextView) findViewById(R.id.totaltime);
mPrevButton = (RepeatingImageButton) findViewById(R.id.prev);
mPrevButton.setOnClickListener(mPrevListener);
mPrevButton.setRepeatListener(mRewListener, 260);
mPauseButton = (ImageButton) findViewById(R.id.pause);
mPauseButton.requestFocus();
mPauseButton.setOnClickListener(mPauseListener);
mNextButton = (RepeatingImageButton) findViewById(R.id.next);
mNextButton.setOnClickListener(mNextListener);
mNextButton.setRepeatListener(mFfwdListener, 260);
seekmethod = 1;
mDeviceHasDpad = (getResources().getConfiguration().navigation ==
Configuration.NAVIGATION_DPAD);
if (icicle != null) {
mOneShot = icicle.getBoolean("oneshot");
} else {
mOneShot = getIntent().getBooleanExtra("oneshot", false);
}
mTouchSlop = ViewConfiguration.get(BaseClass.this).getScaledTouchSlop();
}
Handler mLabelScroller = new Handler() {
#Override
public void handleMessage(Message msg) {
TextView tv = (TextView) msg.obj;
int x = tv.getScrollX();
x = x * 3 / 4;
tv.scrollTo(x, 0);
if (x == 0) {
tv.setEllipsize(TruncateAt.END);
} else {
Message newmsg = obtainMessage(0, tv);
mLabelScroller.sendMessageDelayed(newmsg, 15);
}
}
};
Cursor c = MusicUtils.query(this, ContentUris.withAppendedId(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, audioid),
new String[] { MediaStore.Audio.Media.IS_MUSIC }, null,
null,
null);
boolean ismusic = true;
if (c != null) {
if (c.moveToFirst()) {
ismusic = c.getInt(0) != 0;
}
c.close();
}
if (!ismusic) {
return false;
}
boolean knownartist = (artist != null)
&& !MediaStore.UNKNOWN_STRING.equals(artist);
boolean knownalbum = (album != null)
&& !MediaStore.UNKNOWN_STRING.equals(album);
title = getString(R.string.mediasearch, title);
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(MediaStore.INTENT_ACTION_MEDIA_SEARCH);
i.putExtra(SearchManager.QUERY, query);
if (knownartist) {
i.putExtra(MediaStore.EXTRA_MEDIA_ARTIST, artist);
}
if (knownalbum) {
i.putExtra(MediaStore.EXTRA_MEDIA_ALBUM, album);
}
i.putExtra(MediaStore.EXTRA_MEDIA_TITLE, song);
i.putExtra(MediaStore.EXTRA_MEDIA_FOCUS, mime);
startActivity(Intent.createChooser(i, title));
return true;
}
private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
public void onStartTrackingTouch(SeekBar bar) {
mLastSeekEventTime = 0;
mFromTouch = true;
}
public void onProgressChanged(SeekBar bar, int progress,
boolean fromuser) {
if (!fromuser || (mService == null))
return;
long now = SystemClock.elapsedRealtime();
if ((now - mLastSeekEventTime) > 250) {
mLastSeekEventTime = now;
updateTrackInfo();
mPosOverride = mDuration * progress / 1000;
try {
mService.seek(mPosOverride);
} catch (RemoteException ex) {
}
// trackball event, allow progress updates
if (!mFromTouch) {
refreshNow();
mPosOverride = -1;
}
}
}
private View.OnClickListener mPauseListener = new View.OnClickListener() {
public void onClick(View v) {
doPauseResume();
}
};
private View.OnClickListener mPrevListener = new View.OnClickListener() {
public void onClick(View v) {
if (mService == null)
return;
try {
if (mService.position() < 2000) {
mService.prev();
} else {
mService.seek(0);
mService.play();
}
} catch (RemoteException ex) {
}
}
};
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
try {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
if (mStartSeekPos < 1000) {
mService.prev();
} else {
mService.seek(0);
}
} else {
scanBackward(-1,
event.getEventTime() -
event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (mService != null) {
if (!mSeeking && mStartSeekPos >= 0) {
mPauseButton.requestFocus();
mService.next();
} else {
scanForward(-1,
event.getEventTime() -
event.getDownTime());
mPauseButton.requestFocus();
mStartSeekPos = -1;
}
}
mSeeking = false;
mPosOverride = -1;
return true;
}
} catch (RemoteException ex) {
}
return super.onKeyUp(keyCode, event);
}
private boolean useDpadMusicControl() {
if (mDeviceHasDpad
&& (mPrevButton.isFocused() || mNextButton.isFocused()
|| mPauseButton
.isFocused())) {
return true;
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
int repcnt = event.getRepeatCount();
if ((seekmethod == 0) ? seekMethod1(keyCode) : seekMethod2(keyCode))
return true;
switch (keyCode) {
/*
* // image scale case KeyEvent.KEYCODE_Q: av.adjustParams(-0.05, 0.0,
* 0.0, 0.0, 0.0,-1.0); break; case KeyEvent.KEYCODE_E: av.adjustParams(
* 0.05, 0.0, 0.0, 0.0, 0.0, 1.0); break; // image translate case
* KeyEvent.KEYCODE_W: av.adjustParams( 0.0, 0.0,-1.0, 0.0, 0.0, 0.0);
* break; case KeyEvent.KEYCODE_X: av.adjustParams( 0.0, 0.0, 1.0, 0.0,
* 0.0, 0.0); break; case KeyEvent.KEYCODE_A: av.adjustParams( 0.0,-1.0,
* 0.0, 0.0, 0.0, 0.0); break; case KeyEvent.KEYCODE_D: av.adjustParams(
* 0.0, 1.0, 0.0, 0.0, 0.0, 0.0); break; // camera rotation case
* KeyEvent.KEYCODE_R: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 0.0,-1.0);
* break; case KeyEvent.KEYCODE_U: av.adjustParams( 0.0, 0.0, 0.0, 0.0,
* 0.0, 1.0); break; // camera translate case KeyEvent.KEYCODE_Y:
* av.adjustParams( 0.0, 0.0, 0.0, 0.0,-1.0, 0.0); break; case
* KeyEvent.KEYCODE_N: av.adjustParams( 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
* break; case KeyEvent.KEYCODE_G: av.adjustParams( 0.0, 0.0, 0.0,-1.0,
* 0.0, 0.0); break; case KeyEvent.KEYCODE_J: av.adjustParams( 0.0, 0.0,
* 0.0, 1.0, 0.0, 0.0); break;
*/
case KeyEvent.KEYCODE_SLASH:
seekmethod = 1 - seekmethod;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (!useDpadMusicControl()) {
break;
}
if (!mPrevButton.hasFocus()) {
mPrevButton.requestFocus();
}
scanBackward(repcnt, event.getEventTime() -
event.getDownTime());
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (!useDpadMusicControl()) {
break;
}
if (!mNextButton.hasFocus()) {
mNextButton.requestFocus();
}
scanForward(repcnt, event.getEventTime() - event.getDownTime());
return true;
case KeyEvent.KEYCODE_S:
toggleShuffle();
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_SPACE:
doPauseResume();
return true;
}
return super.onKeyDown(keyCode, event);
}
private void scanBackward(int repcnt, long delta) {
if (mService == null)
return;
try {
if (repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos - delta;
if (newpos < 0) {
// move to previous track
mService.prev();
long duration = mService.duration();
mStartSeekPos += duration;
newpos += duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0)
{
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void scanForward(int repcnt, long delta) {
if (mService == null)
return;
try {
if (repcnt == 0) {
mStartSeekPos = mService.position();
mLastSeekEventTime = 0;
mSeeking = false;
} else {
mSeeking = true;
if (delta < 5000) {
// seek at 10x speed for the first 5 seconds
delta = delta * 10;
} else {
// seek at 40x after that
delta = 50000 + (delta - 5000) * 40;
}
long newpos = mStartSeekPos + delta;
long duration = mService.duration();
if (newpos >= duration) {
// move to next track
mService.next();
mStartSeekPos -= duration; // is OK to go
negative
newpos -= duration;
}
if (((delta - mLastSeekEventTime) > 250) || repcnt < 0) {
mService.seek(newpos);
mLastSeekEventTime = delta;
}
if (repcnt >= 0) {
mPosOverride = newpos;
} else {
mPosOverride = -1;
}
refreshNow();
}
} catch (RemoteException ex) {
}
}
private void doPauseResume() {
try {
if (mService != null) {
if (mService.isPlaying()) {
mService.pause();
} else {
mService.play();
}
updateTrackInfo();
refreshNow();
setPauseButtonImage();
}
} catch (RemoteException ex) {
}
}
private void toggleShuffle() {
if (mService == null) {
return;
}
try {
int shuffle = mService.getShuffleMode();
if (shuffle == MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NORMAL);
if (mService.getRepeatMode() ==
MediaPlaybackService.REPEAT_CURRENT) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
}
showToast(R.string.shuffle_on_notif);
} else if (shuffle == MediaPlaybackService.SHUFFLE_NORMAL
|| shuffle == MediaPlaybackService.SHUFFLE_AUTO) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
showToast(R.string.shuffle_off_notif);
} else {
Log.e("MediaPlaybackActivity", "Invalid shuffle mode: "
+ shuffle);
}
} catch (RemoteException ex) {
}
}
private void cycleRepeat() {
if (mService == null) {
return;
}
try {
int mode = mService.getRepeatMode();
if (mode == MediaPlaybackService.REPEAT_NONE) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_ALL);
showToast(R.string.repeat_all_notif);
} else if (mode == MediaPlaybackService.REPEAT_ALL) {
mService.setRepeatMode(MediaPlaybackService.REPEAT_CURRENT);
if (mService.getShuffleMode() != MediaPlaybackService.SHUFFLE_NONE) {
mService.setShuffleMode(MediaPlaybackService.SHUFFLE_NONE);
}
showToast(R.string.repeat_current_notif);
} else {
mService.setRepeatMode(MediaPlaybackService.REPEAT_NONE);
showToast(R.string.repeat_off_notif);
}
} catch (RemoteException ex) {
}
}
private void showToast(int resid) {
if (mToast == null) {
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
}
mToast.setText(resid);
mToast.show();
}
private void startPlayback() {
if (mService == null)
return;
Intent intent = getIntent();
String filename = "";
Uri uri = intent.getData();
if (uri != null && uri.toString().length() > 0) {
// If this is a file:// URI, just use the path directly instead
// of going through the open-from-filedescriptor codepath.
String scheme = uri.getScheme();
if ("file".equals(scheme)) {
filename = uri.getPath();
} else {
filename = uri.toString();
}
try {
if (!ContentResolver.SCHEME_CONTENT.equals(scheme)
|| !MediaStore.AUTHORITY.equals(uri.getAuthority())) {
mOneShot = true;
}
mService.stop();
mService.openFile(filename, mOneShot);
mService.play();
setIntent(new Intent());
} catch (Exception ex) {
Log.d("MediaPlaybackActivity", "couldn't start playback: " + ex);
}
}
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
}
private ServiceConnection osc = new ServiceConnection() {
public void onServiceConnected(ComponentName classname, IBinder obj) {
mService = IMediaPlaybackService.Stub.asInterface(obj);
startPlayback();
try {
// Assume something is playing when the service says it is,
// but also if the audio ID is valid but the service is paused.
if (mService.getAudioId() >= 0 || mService.isPlaying()
|| mService.getPath() != null) {
// something is playing now, we're done
setPauseButtonImage();
return;
}
} catch (RemoteException ex) {
}
// Service is dead or not playing anything. If we got here as part
// of a "play this file" Intent, exit. Otherwise go to the Music
// app start screen.
if (getIntent().getData() == null) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(BaseClass.this, MusicBrowserActivity.class);
startActivity(intent);
}
finish();
}
public void onServiceDisconnected(ComponentName classname) {
mService = null;
}
};
private void setPauseButtonImage() {
try {
if (mService != null && mService.isPlaying()) {
mPauseButton
.setImageResource(android.R.drawable.ic_media_pause);
} else {
mPauseButton.setImageResource(android.R.drawable.ic_media_play);
}
} catch (RemoteException ex) {
}
}
private TextView mCurrentTime;
private TextView mTotalTime;
private long mPosOverride = -1;
private boolean mFromTouch = false;
private long mDuration;
private int seekmethod;
private boolean paused;
private static final int REFRESH = 1;
private static final int QUIT = 2;
private static final int GET_ALBUM_ART = 3;
private static final int ALBUM_ART_DECODED = 4;
private void queueNextRefresh(long delay) {
if (!paused) {
Message msg = mHandler.obtainMessage(REFRESH);
mHandler.removeMessages(REFRESH);
mHandler.sendMessageDelayed(msg, delay);
}
}
private long refreshNow() {
if (mService == null)
return 500;
try {
long pos = mPosOverride < 0 ? mService.position() : mPosOverride;
long remaining = 1000 - (pos % 1000);
if ((pos >= 0) && (mService.duration() > 0)) {
mCurrentTime.setText(MusicUtils
.makeTimeString(this, pos / 1000));
if (mService.isPlaying()) {
mCurrentTime.setVisibility(View.VISIBLE);
} else {
// blink the counter
int vis = mCurrentTime.getVisibility();
mCurrentTime
.setVisibility(vis == View.INVISIBLE ? View.VISIBLE
: View.INVISIBLE);
remaining = 500;
}
} else {
mCurrentTime.setText("--:--");
}
// return the number of milliseconds until the next full second, so
// the counter can be updated at just the right time
return remaining;
} catch (RemoteException ex) {
}
return 500;
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
updateTrackInfo();
long next = refreshNow();
queueNextRefresh(next);
break;
case QUIT:
// This can be moved back to onCreate once the bug that prevents
// Dialogs from being started from onCreate/onResume is fixed.
new AlertDialog.Builder(BaseClass.this)
.setTitle(R.string.service_start_error_title)
.setMessage(R.string.service_start_error_msg)
.setPositiveButton(R.string.service_start_error_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
finish();
}
}).setCancelable(false).show();
break;
default:
break;
}
}
};
private BroadcastReceiver mStatusListener = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(MediaPlaybackService.META_CHANGED)) {
// redraw the artist/title info and
// set new max for progress bar
updateTrackInfo();
setPauseButtonImage();
queueNextRefresh(1);
} else if (action.equals(MediaPlaybackService.PLAYBACK_COMPLETE)) {
if (mOneShot) {
finish();
} else {
setPauseButtonImage();
}
} else if (action.equals(MediaPlaybackService.PLAYSTATE_CHANGED)) {
setPauseButtonImage();
}
}
};
private static class AlbumSongIdWrapper {
public long albumid;
public long songid;
AlbumSongIdWrapper(long aid, long sid) {
albumid = aid;
songid = sid;
}
}
private void updateTrackInfo() {
if (mService == null) {
return;
}
try {
String path = mService.getPath();
if (path == null) {
finish();
return;
}
long songid = mService.getAudioId();
if (songid < 0 && path.toLowerCase().startsWith("http://")) {
// Once we can get album art and meta data from MediaPlayer, we
// can show that info again when streaming.
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART,
new AlbumSongIdWrapper(-1, -1)).sendToTarget();
} else {
String artistName = mService.getArtistName();
if (MediaStore.UNKNOWN_STRING.equals(artistName)) {
artistName = getString(R.string.unknown_artist_name);
}
String albumName = mService.getAlbumName();
long albumid = mService.getAlbumId();
if (MediaStore.UNKNOWN_STRING.equals(albumName)) {
albumName = getString(R.string.unknown_album_name);
albumid = -1;
}
mAlbumArtHandler.removeMessages(GET_ALBUM_ART);
mAlbumArtHandler.obtainMessage(GET_ALBUM_ART,
new AlbumSongIdWrapper(albumid, songid)).sendToTarget();
}
mDuration = mService.duration();
mTotalTime.setText(MusicUtils
.makeTimeString(this, mDuration / 1000));
} catch (RemoteException ex) {
finish();
}
}
public class AlbumArtHandler extends Handler {
private long mAlbumId = -1;
public AlbumArtHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
long albumid = ((AlbumSongIdWrapper) msg.obj).albumid;
long songid = ((AlbumSongIdWrapper) msg.obj).songid;
if (msg.what == GET_ALBUM_ART
&& (mAlbumId != albumid || albumid < 0)) {
// while decoding the new image, show the default album art
Message numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, null);
mHandler.removeMessages(ALBUM_ART_DECODED);
mHandler.sendMessageDelayed(numsg, 300);
Bitmap bm = MusicUtils.getArtwork(BaseClass.this, songid,
albumid);
if (bm == null) {
bm = MusicUtils.getArtwork(BaseClass.this, songid, -1);
albumid = -1;
}
if (bm != null) {
numsg = mHandler.obtainMessage(ALBUM_ART_DECODED, bm);
mHandler.removeMessages(ALBUM_ART_DECODED);
mHandler.sendMessage(numsg);
}
mAlbumId = albumid;
}
}
}
public static class Worker implements Runnable {
private final Object mLock = new Object();
private Looper mLooper;
/**
* Creates a worker thread with the given name. The thread then runs a
* {#link android.os.Looper}.
*
* #param name
* A name for the new thread
*/
Worker(String name) {
Thread t = new Thread(null, this, name);
t.setPriority(Thread.MIN_PRIORITY);
t.start();
synchronized (mLock) {
while (mLooper == null) {
try {
mLock.wait();
} catch (InterruptedException ex) {
}
}
}
}
public Looper getLooper() {
return mLooper;
}
public void run() {
synchronized (mLock) {
Looper.prepare();
mLooper = Looper.myLooper();
mLock.notifyAll();
}
Looper.loop();
}
public void quit() {
mLooper.quit();
}
}
}
And I want to extend this Class.. But the program crashes showing null pointer exception at this base class.. The base class doesn't have any content view and it points to the buttons (ex.previous and next button), and shows null pointer.. please guide me to solve this problem.
set contentview in the child class and parent class can access it.

Categories

Resources