I need help, there are osvnonoe Activiti in which history is loaded tracks, when you click on the track opens an alert dialog with loading the page, then the link is redirected, and the output is a link with the track, which I send to the media player in the service, but I get a NullPointerException
Example link
http://s.spynetstation.com/m/8/Loud%20Sound/TAMFREE026/unknown-Blitzkrieg-320kbps.mp3
Error
FATAL EXCEPTION: main
java.lang.NullPointerException
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:783)
at android.media.MediaPlayer.setDataSource(MediaPlayer.java:761)
at com.spynetstation.MediaService.initT(MediaService.java:132)
at com.spynetstation.MainActivity$14.shouldOverrideUrlLoading(MainActivity.java:716)
at android.webkit.CallbackProxy.uiOverrideUrlLoading(CallbackProxy.java:224)
at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:324)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Code Activity
public class MainActivity extends FragmentActivity {
MediaPlayer mediaPlayer;
static AudioManager am;
static CheckBox pdaStream;
Button btnNews;
static TitleAdapter titleAdapter;
static ViewPager mViewPager;
RelativeLayout RelativeLayout1;
static String selectStream;
public String stream_sel;
public static String colors_sel;
public int stream;
public static int colors;
public boolean checker;
public static boolean track;
public boolean searchtrack;
public boolean searchtrackhistory;
static SharedPreferences mSettings;
static TextView titleMusic;
static boolean replay = false;
public MusicIntentReceiver myReceiver;
//History
public LinearLayout history;
public Button btn_up;
public boolean history_view = false;
public static TextView history1;
public static TextView history2;
public static TextView history3;
public static TextView history4;
public static TextView history5;
boolean loadingFinished = true;
boolean redirect = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Create();
}
public void Create(){
setContentView(R.layout.activity_main);
//Settings
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
//Language settings
lang = mSettings.getString("lang", "default");
if (lang.equals("default")) {lang=getResources().getConfiguration().locale.getCountry();}
locale = new Locale(lang);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
Log.i("Lang change", "Locale="+locale);
getBaseContext().getResources().updateConfiguration(config, null);
//End Language
mViewPager = (ViewPager) findViewById(R.id.pager);
RelativeLayout1 = (RelativeLayout) findViewById(R.id.RelativeLayout1);
pdaStream = (CheckBox) findViewById(R.id.pdaStream);
pdaStream.setText(R.string.chkbox);
checker = mSettings.getBoolean("checker", false);
Log.i("Resume: checker=",""+checker);
track = mSettings.getBoolean("track", false);
Log.i("Resume: track=",""+track);
searchtrack = mSettings.getBoolean("searchtrack", false);
Log.i("Resume: searchtrack=",""+searchtrack);
searchtrackhistory = mSettings.getBoolean("searchtrackhistory", false);
Log.i("Resume: searchtrackhistory=",""+searchtrackhistory);
stream_sel = mSettings.getString("stream", "1");
Log.i("Resume: stream_sel=",""+stream_sel);
if (stream_sel.equals("0")) {
stream = 0;}
else if (stream_sel.equals("1")) {
stream = 1;}
else if (stream_sel.equals("2")) {
stream = 2;}
else stream = 1;
Log.i("Default Stream=", " "+stream);
//---
Log.i("MainActivity","onCreate");
titleAdapter = new TitleAdapter(getSupportFragmentManager());
mViewPager.setAdapter(titleAdapter);
mViewPager.setCurrentItem(stream);
mViewPager.setOffscreenPageLimit(3);
stream_buf = stream;
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
SeekBar music = (SeekBar)findViewById(R.id.seekBar1);
initBar(music, AudioManager.STREAM_MUSIC);
if (Free) {pdaStream.setChecked(true);}
else {pdaStream.setChecked(checker);}
titleMusic = (TextView) findViewById(R.id.titleMusic);
titleMusic.setSelected(true);
titleMusic.setVisibility(View.VISIBLE);
CallReceiver.state = true;
StartHistory();
IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
myReceiver = new MusicIntentReceiver();
registerReceiver(myReceiver, filter);
SearchTrack();
startService(new Intent(this, MediaService.class));
}
public void StartHistory() {
history1 = (TextView) findViewById(R.id.history1);
history1.setSelected(true);
history2 = (TextView) findViewById(R.id.history2);
history2.setSelected(true);
history3 = (TextView) findViewById(R.id.history3);
history3.setSelected(true);
history4 = (TextView) findViewById(R.id.history4);
history4.setSelected(true);
history5 = (TextView) findViewById(R.id.history5);
history5.setSelected(true);
history = (LinearLayout) findViewById(R.id.history);
history.setVisibility(View.INVISIBLE);
btn_up = (Button) findViewById(R.id.btn_up);
btn_up.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (history_view){
Log.i("StartHistory","History close");
btn_up.setBackgroundResource(R.drawable.up);
history.setVisibility(View.INVISIBLE);
history_view=false;
MediaService.only_his=false;
if (MediaService.mediaPlayer==null){
titleMusic.setText(" ");
}
} else {
Log.i("StartHistory","History open");
btn_up.setBackgroundResource(R.drawable.up2);
history.setVisibility(View.VISIBLE);
history_view=true;
if (MediaService.mediaPlayer==null){
MediaService.only_his=true;
if (stream_buf==0){
MediaService.InputHistory("http://liquid.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://liquid.spynetstation.com:8000/linkable_current_track.txt");
}
if (stream_buf==1){
MediaService.InputHistory("http://main.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://main.spynetstation.com:8000/linkable_current_track.txt");
}
if (stream_buf==2){
MediaService.InputHistory("http://dub.spynetstation.com:8000/meta.txt");
MediaService.SearchInHistory("http://dub.spynetstation.com:8000/linkable_current_track.txt");
}
}else {MediaService.only_his=false;}
}
}
});
}
public void SearchTrack(){
final String searchurl = "https://www.google.ru/search?q=";
titleMusic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrack){} else {
if (MediaService.currentlyPlaying != null){
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(searchurl + MediaService.currentlyPlaying)));
}
}
}
});
history1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[1] != null){
ShowTrack(MediaService.searchhis[0],MediaService.his[1]);
}
}
}
});
history2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[2] != null){
ShowTrack(MediaService.searchhis[1],MediaService.his[2]);
}
}
}
});
history3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[3] != null){
ShowTrack(MediaService.searchhis[2],MediaService.his[3]);
}
}
}
});
history4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[4] != null){
ShowTrack(MediaService.searchhis[3],MediaService.his[4]);
}
}
}
});
history5.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (searchtrackhistory){} else {
if (MediaService.his[5] != null){
ShowTrack(MediaService.searchhis[4],MediaService.his[5]);
}
}
}
});
}
public void ShowTrack(final String smetaout,String stitleout){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(stitleout);
final WebView wv = new WebView(this);
Log.d("My Webview", "ShowTrack");
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(smetaout);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(url);
Log.d("shouldOverrideUrlLoading", url);
Uri myUri = Uri.parse(url);
MediaService.initT(myUri);
MediaService.startT();
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if(!redirect){
loadingFinished = true;
}
if(loadingFinished && !redirect){
} else{
redirect = false;
}
}
});
alert.setView(wv);
alert.setNegativeButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
alert.show();
}
}
Code Service
public class MediaService extends Service implements OnPreparedListener,OnCompletionListener{
static boolean isPlayingMain = false;
static boolean isPlayingLiquid = false;
static boolean isPlayingDubstep = false;
static MediaPlayer mediaPlayer;
static NotificationManager nm;
private static NotificationCompat.Builder mBuilder;
private static Notification.Builder mNBuilder;
public static Context ctx;
public IBinder onBind(Intent paramIntent) {
return null;
}
public static void initT(Uri urlTrack){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d("initT",""+urlTrack);
mediaPlayer.setDataSource(ctx,urlTrack);
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
Log.i("MediaService", "prepare");
}
public static void startT(){
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
Log.i("MediaService", "start");
}
});
}
public static void releaseMP() {
if (mediaPlayer != null) {
try {
mediaPlayer.release();
Log.i("MediaService", "release");
mediaPlayer = null;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.i("MediaService", "onCompletion");
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.i("MediaService", "onPrepareed");
}
public void onCreate() {
super.onCreate();
ctx = getApplicationContext();
//notif(titleNotif, contentNotif);
//this.nm = ((NotificationManager)getSystemService("notification"));
}
public void onDestroy() {
//this.nm.cancelAll();
stopForeground(true);
if(CallReceiver.telManager != null) {
CallReceiver.telManager.listen(CallReceiver.phoneListener, PhoneStateListener.LISTEN_NONE);
Log.i("CallReceiver", "Destroy");
}
}
public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) {
try {
TimeUnit.SECONDS.sleep(0);
notif(getResources().getString(R.string.title_notif),getResources().getString(R.string.title_notif));
return super.onStartCommand(paramIntent, paramInt1, paramInt2);
}
catch (InterruptedException localInterruptedException) {
for (;;) {
localInterruptedException.printStackTrace();
}
}
}
public void notif(String titleNotif, String contentNotif){
//building the notification
mBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.drawable.spy)
.setContentTitle(titleNotif)
.setTicker(contentNotif)
.setOngoing(true)
//.addAction(R.drawable.media_play, "Play", notificationIntent)
;
Intent notificationIntent = new Intent(ctx, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
//Notification n = mBuilder.build();
//nm.notify(1, n);
startForeground(1, mBuilder.build());
}
}
Thank you all for your answers! Decided as follows:
In the service has changed as follows:
public static void initT(Context context,Uri urlTrack){
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.d("initT",""+urlTrack);
mediaPlayer.setDataSource(context,urlTrack);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}catch (IllegalArgumentException e) {
e.printStackTrace();
}
Log.i("MediaService", "prepare");
}
In Activity changed as follows:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
view.loadUrl(url);
Log.d("shouldOverrideUrlLoading", url);
Uri myUri = Uri.parse(url);
context = getApplicationContext();
MediaService.releaseMP();
MediaService.initT(context, myUri);
MediaService.startT();
return true;
}
Related
When I click music notification and run activity. When music change the content of textview changed, but view not update, but when I run an activity independently, everything works fine and view updated.
In musicService class:
PendingIntent contentPendingIntent = PendingIntent.getActivity
(this, 0, new Intent(this, MusicPlayer.class), 0);
builder.setContentTitle(mMedia.getTitleMedia())
.setContentText(mMedia.getSingerName())
.setContentIntent(contentPendingIntent)
.setSmallIcon(R.drawable.ic_notification)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.addAction(restartAction)
.addAction(playPauseAction)
.addAction(nextMusic)
.setDeleteIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(getApplicationContext(), PlaybackStateCompat.ACTION_STOP));
and my activity class
public class MusicPlayer extends AppCompatActivity implements ServiceConnection, CacheListener, SeekBar.OnSeekBarChangeListener, Player.EventListener {
private SimpleExoPlayerView mPlayerView;
public PlayerService mPlayerService;
private boolean mBound;
//______________________________________________________________________________________________
VolleyRequestHelper volleyRequestHelper;
//______________________________________________________________________________________________
public static MusicPlayer instance;
public ImageView download;
TextView title;
TextView artist;
SeekBar progressBar;
ImageView circleImageView;
ImageView album_art_blurred;
PlayPauseButton mPlayPause;
public AppBarLayout appBarLayout;
private final VideoProgressUpdater updater = new VideoProgressUpdater();
public DownloadProgressView downloadProgressView;
//______________________________________________________________________________________________
TextView songElapsedTime;
TextView songDuration;
int positionOfMusic = 0;
public Media media;
boolean initAlbum = false;
boolean startService = false;
boolean checkChangeMediaDetails = true;
//______________________________________________________________________________________________
RecyclerView recyclerViewArtist;
SimilarSongsAdapter similarSongsAdapter;
public List<Media> similarSongsList = new ArrayList<>();
//______________________________________________________________________________________________
int songElapsed = 0;
int songDurationTime = 0;
int videoProgress = 0;
int mediaServiceRun = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
instance = this;
volleyRequestHelper = VolleyRequestHelper.getInstance(getApplicationContext(), requestCompletedListener);
initView();
initRecyclerview();
Intent intent = getIntent();
mediaServiceRun = intent.getIntExtra("mediaServiceRun", 1);
if (mediaServiceRun == 1) {
Intent i = new Intent(this, PlayerService.class);
bindService(i, this, Context.BIND_AUTO_CREATE);
startService(i);
} else {
media = intent.getParcelableExtra("media");
switch (media.getCustomMediaType()) {
case "آهنگ آلبوم":
setMedia(media);
getAlbumTrack(media.getAlbumId());
break;
case "آلبوم":
initAlbum = true;
getAlbumTrack(media.getId());
break;
default:
setMedia(media);
Serach(media.getSingerName(), "1");
break;
}
selectMedia(media);
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(this);
mBound = false;
}
}
#Override
protected void onResume() {
super.onResume();
updater.start();
}
#Override
public void onPause() {
super.onPause();
updater.stop();
}
//_________________________ServiceConnected_and_ServiceDisconnected_____________________________
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
//______________________________________________________________________________________________
//_______________________________________setMediaInView_________________________________________
public void setMedia(Media mediaL) {
media = mediaL;
bluredImage(mediaL.getCover());
Picasso.with(this).load(mediaL.getCover()).into(circleImageView);
title.setText(mediaL.getTitleMedia());
artist.setText(mediaL.getSingerName());
checkCachedState(mediaL.getStreamUrl());
checkChangeMediaDetails = false;
}
public void bluredImage(String IMAGE_URL) {
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
album_art_blurred.setImageBitmap(BlurImage.fastblur(bitmap, 1f, 50));
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
album_art_blurred.setImageResource(R.mipmap.ic_launcher);
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
album_art_blurred.setTag(target);
Picasso.with(this)
.load(IMAGE_URL)
.error(R.mipmap.ic_launcher)
.placeholder(R.mipmap.ic_launcher)
.into(target);
}
//______________________________________________________________________________________________
//______________________________________initView________________________________________________
public void initRecyclerview() {
recyclerViewArtist = (RecyclerView) findViewById(R.id.queue_recyclerview_horizontal);
recyclerViewArtist.setNestedScrollingEnabled(false);
recyclerViewArtist.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
LinearLayoutManager horizontalLayoutManagaertwo
= new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
recyclerViewArtist.setLayoutManager(horizontalLayoutManagaertwo);
similarSongsAdapter = new SimilarSongsAdapter(this, similarSongsList, recyclerViewArtist);
recyclerViewArtist.setAdapter(similarSongsAdapter);
}
public void initView() {
mPlayerView = (SimpleExoPlayerView) findViewById(R.id.simpleExoPlayerView);
appBarLayout = (AppBarLayout) findViewById(R.id.appbar);
downloadProgressView = (DownloadProgressView) findViewById(R.id.downloadProgressView);
downloadProgressView.setPercentageColor(Color.parseColor("#ffffff"));
downloadProgressView.setDownloadedSizeColor(Color.parseColor("#ffffff"));
downloadProgressView.setTotalSizeColor(Color.parseColor("#ffffff"));
songElapsedTime = (TextView) findViewById(R.id.song_elapsed_time);
songDuration = (TextView) findViewById(R.id.song_duration);
progressBar = (SeekBar) findViewById(R.id.song_progress);
progressBar.setOnSeekBarChangeListener(this);
circleImageView = (ImageView) findViewById(R.id.album_art);
album_art_blurred = (ImageView) findViewById(R.id.album_art_blurred);
title = (TextView) findViewById(R.id.song_title);
artist = (TextView) findViewById(R.id.song_artist);
mPlayPause = (PlayPauseButton) findViewById(R.id.playpause);
download = (ImageView) findViewById(R.id.download);
if (SornaDownloadManager.inQueue) {
if (SornaDownloadManager.checkDownloadId(media.getId())) {
download.setVisibility(View.GONE);
downloadProgressView.show(SornaDownloadManager.lastDownloadID,
new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
}
}
}
//______________________________________________________________________________________________
//_________________________________Cache_and_UpdateProgressBar__________________________________
private void checkCachedState(String url) {
HttpProxyCacheServer proxy = TimberApp.getProxy(this);
boolean fullyCached = proxy.isCached(url);
if (fullyCached) {
progressBar.setSecondaryProgress(100);
}
proxy.registerCacheListener(this, url);
}
private void updateVideoProgress() {
if (mPlayerService != null)
try {
videoProgress = (int) (mPlayerService.getExoPlayer().getCurrentPosition() * 100 / mPlayerService.getExoPlayer().getDuration());
} catch (Exception e) {
}
progressBar.setProgress(videoProgress);
}
private final class VideoProgressUpdater extends Handler {
public void start() {
sendEmptyMessage(0);
}
public void stop() {
removeMessages(0);
}
#Override
public void handleMessage(Message msg) {
updateVideoProgress();
sendEmptyMessageDelayed(0, 500);
if (mPlayerService != null) {
try {
songElapsed = (int) mPlayerService.getExoPlayer().getCurrentPosition();
songDurationTime = (int) mPlayerService.getExoPlayer().getDuration();
} catch (Exception e) {
}
}
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(songElapsed));
songDuration.setText(millisecondsTOminutes.milliSecondsToTimer(songDurationTime));
}
}
#Override
public void onCacheAvailable(File cacheFile, String url, int percentsAvailable) {
progressBar.setSecondaryProgress(percentsAvailable);
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
void seekVideo() {
int videoPosition = (int) (mPlayerService.getExoPlayer().getDuration() * progressBar.getProgress() / 100);
mPlayerService.getExoPlayer().seekTo(videoPosition);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
seekVideo();
songElapsedTime.setText(millisecondsTOminutes.milliSecondsToTimer(mPlayerService.getExoPlayer().getCurrentPosition()) + "");
}
//______________________________________________________________________________________________
//____________________________________setButtonsFuction_________________________________________
public void setFunc(View v) {
switch (v.getId()) {
case R.id.playpause:
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
if (!startService) {
setStopService();
setStartService();
onlinePlay(media.getId());
} else {
mPlayerService.playTrack();
}
} else {
setPlayButton(false);
mPlayerService.pauseTrack();
}
break;
case R.id.next:
mPlayerService.nextTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.previous:
mPlayerService.previousTrack();
//positionOfMusic = mPlayerService.getPlayingMedia();
break;
case R.id.download:
showPopup(media);
break;
case R.id.share:
share.shareTrack(media, this);
break;
}
}
public void showPopup(final Media media) {
View popupView = LayoutInflater.from(this).inflate(R.layout.popup_layout, null);
final PopupWindow popupWindow = new PopupWindow(popupView, WindowManager.LayoutParams.MATCH_PARENT
, WindowManager.LayoutParams.MATCH_PARENT);
popupWindow.setOutsideTouchable(false);
popupWindow.setFocusable(true);
popupWindow.showAtLocation(popupView, Gravity.CENTER, 1, 1);
Button dnlow = (Button) popupView.findViewById(R.id.dnlow);
Button dnhigh = (Button) popupView.findViewById(R.id.dnhigh);
if (media.getDownloadLinksList128().matches("noLink"))
dnlow.setVisibility(View.GONE);
if (media.getDownloadLinksList320().matches("noLink"))
dnhigh.setVisibility(View.GONE);
dnlow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList128(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
dnhigh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SornaDownloadManager sornaDownloadManager = SornaDownloadManager.getInstance(getApplicationContext());
long downloadID = sornaDownloadManager.AddForDownload(media.getDownloadLinksList320(),
media.getTitleMedia() + "-" + media.getSingerName(), media.getId());
downloadProgressView.show(downloadID, new DownloadProgressView.DownloadStatusListener() {
#Override
public void downloadFailed(int reason) {
}
#Override
public void downloadSuccessful() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
#Override
public void downloadCancelled() {
SornaDownloadManager.PullFromQueue(media.getId());
download.setVisibility(View.VISIBLE);
}
});
popupWindow.dismiss();
}
});
popupWindow.showAsDropDown(popupView, 0, 0);
}
//______________________________________________________________________________________________
//__________________________________GetDataFromServer___________________________________________
public void Serach(String searchQuery, String page) {
updateData();
volleyRequestHelper.RequestFetchSearchMedia
(constantsURL.REQUEST_FETCH_SIMILAR_SONGS, searchQuery, page, false);
}
public void getAlbumTrack(String albumId) {
updateData();
volleyRequestHelper.RequestFetchAlbumTrack
(constantsURL.REQUEST_FETCH_ALBUM_TRACKS, albumId, false);
}
public void selectMedia(final Media media) {
if (!constants.refLogId.matches(""))
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "selectSearchResult", media.getId(), constants.refLogId, false);
}
public void onlinePlay(final String mediaid) {
volleyRequestHelper.requestSetLog
(constantsURL.REQUEST_SET_LOG, "onlinePlay", mediaid, constants.refLogId, false);
}
public void updateData() {
similarSongsAdapter.notifyDataSetChanged();
similarSongsAdapter.setLoaded();
}
public void parseJson(String response, List<Media> arrayList) {
try {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(response);
JSONObject jsonObject = new JSONObject(String.valueOf(json));
JSONArray arrey = jsonObject.getJSONArray("result");
if (!media.getCustomMediaType().matches("آلبوم"))
arrayList.add(media);
for (int i = 0; i < arrey.length(); i++) {
JSONObject j = arrey.getJSONObject(i);
Media mdia = new Media(j);
if (!media.getId().matches(mdia.getId()) && !mdia.getCustomMediaType().matches("آلبوم"))
arrayList.add(mdia);
}
} catch (Exception e) {
}
if (mPlayerService != null) {
mPlayerService.setOnlineList(similarSongsList);
}
}
private VolleyRequestHelper.OnRequestCompletedListener requestCompletedListener =
new VolleyRequestHelper.OnRequestCompletedListener() {
#Override
public void onRequestCompleted(String requestName, boolean status,
String response, String errorMessage) {
//homeView.hideProgress();
switch (requestName) {
case "SIMILAR_SONGS":
if (status) {
parseJson(response, similarSongsList);
updateData();
}
break;
case "ALBUM_TRACKS":
if (status) {
parseJson(response, similarSongsList);
updateData();
if (initAlbum) {
setMedia(similarSongsList.get(0));
}
}
break;
}
}
};
//_______________________________________EXOPLAYER______________________________________________
#Override
public void onTimelineChanged(Timeline timeline, Object manifest) {
}
#Override
public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
if (checkChangeMediaDetails) {
musicChange(mPlayerService.getPlayingMedia());
} else checkChangeMediaDetails = true;
}
#Override
public void onLoadingChanged(boolean isLoading) {
}
#Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if ((playbackState == Player.STATE_READY) && playWhenReady) {
if (!mPlayPause.isPlayed()) {
setPlayButton(true);
}
} else if ((playbackState == Player.STATE_READY)) {
setPlayButton(false);
} else if (playbackState == Player.STATE_ENDED) {
}
}
#Override
public void onRepeatModeChanged(int repeatMode) {
}
#Override
public void onPlayerError(ExoPlaybackException error) {
}
#Override
public void onPositionDiscontinuity() {
}
#Override
public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
}
//______________________________________________________________________________________________
public void setStartService() {
Intent intent = new Intent(this, PlayerService.class);
bindService(intent, this, Context.BIND_AUTO_CREATE);
startService(intent);
startService = true;
}
public void setStopService() {
Intent intentStop = new Intent(this, PlayerService.class);
stopService(intentStop);
}
public void setPlayButton(boolean playButton) {
mPlayPause.setPlayed(playButton);
mPlayPause.startAnimation();
}
public void setMusicInService(Media mMedia, int position) {
positionOfMusic = position;
if (mPlayerService != null) {
mPlayerService.setPlayMedia(mMedia, position);
} else {
setStartService();
setMedia(mMedia);
}
//positionOfMusic = position;
/*if (mPlayerService != null) {
mPlayerService.setMediaUri(mMedia.getStreamUrl());
mPlayerService.setMedia(mMedia);
mPlayerService.setPlayingMedia(position);
mPlayerService.preparePlayer();
} else {
positionOfMusic = position;
setStartService();
setMedia(mMedia);
}*/
}
public void musicChange(int newPosition) {
if (similarSongsList != null && similarSongsList.size() != 0) {
setMedia(similarSongsList.get(newPosition));
similarSongsAdapter.setPlayPosition(newPosition);
similarSongsAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder)
{
PlayerService.MyBinder b = (PlayerService.MyBinder) iBinder;
mPlayerService = b.getService();
mPlayerView.setUseController(false);
mPlayerView.setPlayer(mPlayerService.getExoPlayer());
if (mediaServiceRun == 1) {
similarSongsList = mPlayerService.getOnlineList();
initView();
initRecyclerview();
musicChange(mPlayerService.getPlayingMedia());
} else {
mPlayerService.getExoPlayer().addListener(this);
mPlayerService.setPlayingMedia(positionOfMusic);
setMusicInService(media, mPlayerService.getPlayingMedia());
if (similarSongsList != null && similarSongsList.size() != 0) {
mPlayerService.setOnlineList(similarSongsList);
}
}
mBound = true;
}
I have created android application to stream online radio stations but when I click start button to play radio it won't start.In service I read ip address of file from url and add it to string.When user selects radio station I add port to string with ip address.Problem starts in mediaPlayer.setOnPreparedListener !!!
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL;
final String textSource = "http://audiophileradio.stream/Ip.txt";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
new MyTask().execute();
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
#Override
public boolean onUnbind(Intent intent)
{
return super.onUnbind(intent);
}
private class MyTask extends AsyncTask<Void, Void, String>
{
String textResult;
#Override
protected String doInBackground(Void... params) {
URL textUrl;
try {
textUrl = new URL(textSource);
BufferedReader bufferReader
= new BufferedReader(new InputStreamReader(textUrl.openStream()));
String StringBuffer;
String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textResult = stringText;
return textResult;
} catch (MalformedURLException e) {
e.printStackTrace();
textResult = e.toString();
} catch (IOException e) {
e.printStackTrace();
textResult = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String result) {
Log.d("DebugTag", "Value: " + textResult);
super.onPostExecute(result);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
String radio = sharedPreferences.getString("station", "8000");
if (radio != null)
{
STREAM_URL += ":" + radio;
}
mediaPlayer = new MediaPlayer();
if (!mediaPlayer.isPlaying())
{
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
#Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
mediaPlayer.setOnCompletionListener(BackgroundService.this);
}
}
}
public class Main extends Fragment
{
private ImageButton buttonPlay;
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_main,container,false);
buttonPlay = (ImageButton) view.findViewById(R.id.buttonPlay);
mPlayer = new MediaPlayer();
initControls();
buttonPlay.setTag(1);
buttonPlay.setImageResource(R.drawable.play);
buttonPlay.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
if (Integer.parseInt(buttonPlay.getTag().toString()) == 1)
{
buttonPlay.setImageResource(R.drawable.stop);
view.setTag(0);
getActivity().startService(playbackServiceIntent);
Log.e("Play", "onStop");
Toast.makeText(getActivity(), "Play", Toast.LENGTH_SHORT).show();
} else
{
buttonPlay.setImageResource(R.drawable.play);
view.setTag(1);
mPlayer.stop();
getActivity().stopService(playbackServiceIntent);
Log.e("Stop", "onPlay");
Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
}
}
});
playbackServiceIntent = new Intent(getActivity(), BackgroundService.class);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Audiophileradio");
}
private void startService()
{
getActivity().startService(new Intent(getActivity(),BackgroundService.class));
}
private void stopService()
{
getActivity().stopService(new Intent(getActivity(),BackgroundService.class));
}
private void initControls()
{
try
{
volumeSeekbar = (SeekBar) view.findViewById(R.id.seekBar);
audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
//volumeSeekbar.setMax(100);
volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onStopTrackingTouch(SeekBar arg0)
{
}
#Override
public void onStartTrackingTouch(SeekBar arg0)
{
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
{
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
//volume.setText("Volume : " + progress + "%");
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
prepareAsynch should be called after setOnPreparedListener, otherwise it may happen that prepareAsynch finished working before the listener is assigned.
I have fixed the problem! Radio didn't work because I forgot to add http:// in ip address after reading it from url !!!
In my android application while I'm playing a music, the seekbar bar is staying still. The timer of the music is running fine & the music plays from the touched position of the seek bar.
But the problem is that the seekbar is still and not moving while touching on the seekbar .
Any one help me to find a solution for this .. Thank You ..
My Activity code is ....
public class Device_AudioPlayerActivity extends Activity implements Runnable,
OnClickListener, SeekBar.OnSeekBarChangeListener {
Button btnBack;
static Button btnPause;
private Handler mHandler;
Button btnNext;
static Button btnPlay;
static TextView textNowPlaying;
static TextView textAlbumArtist;
static TextView textComposer;
static LinearLayout linearLayoutPlayer;
SeekBar progressBar;
static Context context;
TextView textBufferDuration, textDuration;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//getActionBar().hide();
setContentView(R.layout.device_audio_player);
context = this;
progressBar=(SeekBar)findViewById(R.id.progressBar);
init();
progressBar.setMax(Device_SongService.mp.getDuration());
new Thread().start();
progressBar.setOnSeekBarChangeListener(this);
progressBar.setEnabled(true);
//-=--------------------------------------
}
private void init() {
getViews();
setListeners();
progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.white), Mode.SRC_IN);
Device_PlayerConstants.PROGRESSBAR_HANDLER = new Handler() {
#Override
public void handleMessage(Message msg) {
Integer i[] = (Integer[]) msg.obj;
textBufferDuration.setText(Device_UtilFunctions.getDuration(i[0]));
textDuration.setText(Device_UtilFunctions.getDuration(i[1]));
progressBar.setProgress(i[2]);
}
};
}
private void setListeners() {
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.previousControl(getApplicationContext());
}
});
btnPause.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.pauseControl(getApplicationContext());
}
});
btnPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.playControl(getApplicationContext());
}
});
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Device_Controls.nextControl(getApplicationContext());
}
});
}
public static void changeUI() {
updateUI();
changeButton();
}
private void getViews() {
btnBack = (Button) findViewById(R.id.btnBack);
btnPause = (Button) findViewById(R.id.btnPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPlay = (Button) findViewById(R.id.btnPlay);
textNowPlaying = (TextView) findViewById(R.id.textNowPlaying);
linearLayoutPlayer = (LinearLayout) findViewById(R.id.linearLayoutPlayer);
textAlbumArtist = (TextView) findViewById(R.id.textAlbumArtist);
textComposer = (TextView) findViewById(R.id.textComposer);
progressBar = (SeekBar) findViewById(R.id.progressBar);
textBufferDuration = (TextView) findViewById(R.id.textBufferDuration);
textDuration = (TextView) findViewById(R.id.textDuration);
textNowPlaying.setSelected(true);
textAlbumArtist.setSelected(true);
}
#Override
protected void onResume() {
super.onResume();
boolean isServiceRunning = Device_UtilFunctions.isServiceRunning(Device_SongService.class.getName(), getApplicationContext());
if (isServiceRunning) {
updateUI();
}
changeButton();
}
public static void changeButton() {
if (Device_PlayerConstants.SONG_PAUSED) {
btnPause.setVisibility(View.GONE);
btnPlay.setVisibility(View.VISIBLE);
} else {
btnPause.setVisibility(View.VISIBLE);
btnPlay.setVisibility(View.GONE);
}
}
private static void updateUI() {
try {
String songName = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getTitle();
String artist = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getArtist();
String album = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbum();
String composer = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getComposer();
textNowPlaying.setText(songName);
textAlbumArtist.setText(artist + " - " + album);
if (composer != null && composer.length() > 0) {
textComposer.setVisibility(View.VISIBLE);
textComposer.setText(composer);
} else {
textComposer.setVisibility(View.GONE);
}
} catch (Exception e) {
e.printStackTrace();
}
try {
long albumId = Device_PlayerConstants.SONGS_LIST.get(Device_PlayerConstants.SONG_NUMBER).getAlbumId();
Bitmap albumArt = Device_UtilFunctions.getAlbumart(context, albumId);
if (albumArt != null) {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(albumArt));
} else {
linearLayoutPlayer.setBackgroundDrawable(new BitmapDrawable(Device_UtilFunctions.getDefaultAlbumArt(context)));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onClick(View view) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
try {
if (Device_SongService.mp.isPlaying() || Device_SongService.mp != null) {
if (b)
Device_SongService.mp.seekTo(i);
} else if (Device_SongService.mp == null) {
Toast.makeText(getApplicationContext(), "Media is not running",
Toast.LENGTH_SHORT).show();
seekBar.setProgress(0);
}
} catch (Exception e) {
Log.e("seek bar", "" + e);
seekBar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void run() {
int currentPosition = Device_SongService.mp.getCurrentPosition();
int total = Device_SongService.mp.getDuration();
while (Device_SongService.mp != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = Device_SongService.mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
}
}
}
Have a look at this link.
Try using a thread in progress changed.
you have to use thread on onprogresschnaged....
#Override
public void onProgressChanged(SeekBar arg0, final int progress, boolean arg2) {
Thread thread = new Thread() {
#Override
public void run() {
try {
while(true) {
//here write your code
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
}
I'm working on a music player for android and i'm stuck at this problem.
By now i can play a song with musicservice and send it to background, i also display a notification with current playing song.
What i need is to re-open the main activity from the song notification and continue playing the song, it actually starts the desired activity but the music service is re-created and it stops the current playing song.
Here is my code.
MusicService.java
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private final IBinder musicBind = new MusicBinder();
//media player
private MediaPlayer player;
//song list
private ArrayList<SongModel> songs;
//current position
private int songPosition;
public MusicService() {
}
public void onCreate() {
//create the service
super.onCreate();
//initialize position
songPosition = 0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
//set player properties
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<SongModel> theSongs) {
songs = theSongs;
}
public class MusicBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public int getPosition() {
return player.getCurrentPosition();
}
public int getCurrenListPosition() {
return songPosition;
}
public int getDuration() {
return player.getDuration();
}
public boolean isPlaying() {
return player.isPlaying();
}
public void pausePlayer() {
player.pause();
}
public void stopPlayer() {
player.stop();
}
public void seekToPosition(int posn) {
player.seekTo(posn);
}
public void start() {
player.start();
}
public void playSong() {
try {
//play a song
player.reset();
SongModel playSong = songs.get(songPosition);
String trackUrl = playSong.getFileUrl();
player.setDataSource(trackUrl);
player.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCompletion(MediaPlayer mp) {
if (mp.getCurrentPosition() == 0) {
mp.reset();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
SongModel playingSong = songs.get(songPosition);
Intent intent = new Intent(this, NavDrawerMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_action_playing)
.setTicker(playingSong.getTitle())
.setOngoing(true)
.setContentTitle(playingSong.getTitle())
.setContentText(playingSong.getArtistName());
Notification notification = builder.build();
startForeground((int) playingSong.getSongId(), notification);
}
#Override
public void onDestroy() {
stopForeground(true);
}
public void setSong(int songIndex) {
songPosition = songIndex;
}
}
DiscoverSongsFragment.java
public class DiscoverSongsFragment extends Fragment
implements MediaController.MediaPlayerControl {
JazzyGridView songsContainer;
SongsHelper songsHelper;
SongsAdapter songsAdapter;
ArrayList<SongModel> songsArrayList;
ConnectionState connectionState;
Context mContext;
private static View rootView;
SongModel currentSong;
SeekBar nowPlayingSeekBar;
final Handler handler = new Handler();
// this value contains the song duration in milliseconds.
// Look at getDuration() method in MediaPlayer class
int mediaFileLengthInMilliseconds;
View nowPlayingLayout;
boolean nowPlayingLayoutVisible;
TextView nowPlayingTitle;
TextView nowPlayingArtist;
ImageButton nowPlayingCover;
ImageButton nowPlayingStop;
private MusicService musicService;
private Intent playIntent;
private boolean musicBound = false;
private boolean playbackPaused = false;
private int mCurrentTransitionEffect = JazzyHelper.SLIDE_IN;
public static DiscoverSongsFragment newInstance() {
return new DiscoverSongsFragment();
}
public DiscoverSongsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_discover_songs, container, false);
mContext = rootView.getContext();
setupViews(rootView);
return rootView;
}
#Override
public void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(mContext, MusicService.class);
mContext.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
mContext.startService(playIntent);
}
}
#Override
public void onResume() {
super.onResume();
if (isPlaying()) {
showNowPlayingLayout();
primarySeekBarProgressUpdater();
}
}
#Override
public void onDestroy() {
mContext.stopService(playIntent);
musicService = null;
super.onDestroy();
}
private void hideNowPlayingLayout() {
nowPlayingLayoutVisible = false;
nowPlayingLayout.setVisibility(View.GONE);
Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_out);
nowPlayingLayout.startAnimation(animationFadeIn);
}
private void showNowPlayingLayout() {
nowPlayingLayoutVisible = true;
nowPlayingLayout.setVisibility(View.VISIBLE);
Animation animationFadeIn = AnimationUtils.loadAnimation(mContext, R.anim.fade_in);
nowPlayingLayout.startAnimation(animationFadeIn);
}
private void setupViews(View rootView) {
songsHelper = new SongsHelper();
songsArrayList = new ArrayList<SongModel>();
connectionState = new ConnectionState(mContext);
songsAdapter = new SongsAdapter(mContext, songsArrayList);
nowPlayingLayout = rootView.findViewById(R.id.nowPlayingLayout);
nowPlayingLayout.setVisibility(View.GONE);
nowPlayingLayoutVisible = false;
songsContainer = (JazzyGridView) rootView.findViewById(R.id.songsContainerView);
songsContainer.setTransitionEffect(mCurrentTransitionEffect);
songsContainer.setAdapter(songsAdapter);
songsContainer.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
musicService.setSong(position);
musicService.playSong();
if (playbackPaused) {
playbackPaused = false;
}
currentSong = songsArrayList.get(position);
// gets the song length in milliseconds from URL
mediaFileLengthInMilliseconds = getDuration();
if (currentSong != null) {
nowPlayingTitle.setText(currentSong.getTitle());
nowPlayingArtist.setText(currentSong.getArtistName());
nowPlayingCover.setImageBitmap(currentSong.getCoverArt());
}
primarySeekBarProgressUpdater();
if (!nowPlayingLayoutVisible) {
showNowPlayingLayout();
}
}
});
nowPlayingSeekBar = (SeekBar) rootView.findViewById(R.id.nowPlayingSeekbar);
nowPlayingSeekBar.setMax(99);
nowPlayingTitle = (TextView) rootView.findViewById(R.id.nowPlayingTitle);
nowPlayingArtist = (TextView) rootView.findViewById(R.id.nowPlayingArtist);
nowPlayingStop = (ImageButton) rootView.findViewById(R.id.nowPlayingStop);
nowPlayingStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isPlaying()) {
currentSong = null;
playbackPaused = false;
musicService.stopPlayer();
mediaFileLengthInMilliseconds = 0;
nowPlayingSeekBar.setProgress(0);
hideNowPlayingLayout();
}
}
});
nowPlayingCover = (ImageButton) rootView.findViewById(R.id.nowPlayingCover);
nowPlayingCover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(mContext, SongDetailsActivity.class);
intent.putExtra("Title", currentSong.getTitle());
intent.putExtra("Artist", currentSong.getArtistName());
intent.putExtra("Album", currentSong.getAlbumName());
intent.putExtra("Genre", currentSong.getGenre());
intent.putExtra("CoverUrl", currentSong.getCoverArtUrl());
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
getSongs();
hideNowPlayingLayout();
}
private void getSongs() {
if (!connectionState.isConnectedToInternet()) {
}
songsAdapter.clear();
String songsUrl = Constants.getAPI_SONGS_URL();
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(songsUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray jsonArray) {
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
SongModel song = songsHelper.getSongFromJson(jsonObject);
songsAdapter.add(song);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
});
AppController.getInstance().addToRequestQueue(jsonArrayRequest);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
/**
* Method which updates the SeekBar primary progress by current song playing position
*/
private void primarySeekBarProgressUpdater() {
nowPlayingSeekBar.setProgress((int) (((float) getCurrentPosition() / getDuration()) * 100));
//if (isPlaying()) {
Runnable runnable = new Runnable() {
public void run() {
primarySeekBarProgressUpdater();
}
};
handler.postDelayed(runnable, 1000);
//}
}
#Override
public void start() {
musicService.start();
}
#Override
public void pause() {
playbackPaused = true;
musicService.pausePlayer();
}
#Override
public int getDuration() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getDuration();
}
return 0;
}
#Override
public int getCurrentPosition() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getPosition();
}
return 0;
}
public int getCurrentListPosition() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.getCurrenListPosition();
}
return 0;
}
#Override
public void seekTo(int pos) {
musicService.seekToPosition(pos);
}
#Override
public boolean isPlaying() {
if (musicService != null && musicBound && musicService.isPlaying()) {
return musicService.isPlaying();
}
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
//get service
musicService = binder.getService();
//pass list
musicService.setList(songsArrayList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
}
(The fragment also re-creates itself when navigating through drawer menu items)
I hope somebody can help me achieve this. I dont know how to maintane the state when re-starting the MainActivity (by the way, im using navdrawer to hold fragments)
Include the currently playing song in your notification intent. Update the intent as the song changes. Include the flag to clear top and the flag to update current in the notification intent. :( sorry IDK if I have the flags right for your situation but you'll have a place to do more research.
In your service where you create the notification intent.
// link the notifications to the recorder activity
Intent resultIntent = new Intent(context, KmlReader.class);
resultIntent
.setAction(ServiceLocationRecorder.INTENT_COM_GOSYLVESTER_BESTRIDES_LOCATION_RECORDER);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent resultPendingIntent = PendingIntent
.getActivity(context, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
return mBuilder.build();
}
Then in main onCreate check the bundle for the name of the currently playing song and display it. Notice how I check for the existence of a bundle key before using it.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String intentaction = intent.getAction();
// First Run checks
if (savedInstanceState == null) {
// first run init
...
} else {
// get the saved_Instance state
// always get the default when key doesn't exist
// default is null for this example
currentCameraPosition = savedInstanceState
.containsKey(SAVED_INSTANCE_CAMERA_POSITION) ? (CameraPosition) savedInstanceState
.getParcelable(SAVED_INSTANCE_CAMERA_POSITION) : null;
...
hi i have my app aacplayer but im trying to implement a tab menu i achieved that but my issue here when my app opens have to run MainActivity.java but that one have a service of audio but i added anothers tabs and works perfect that ones doesnt use services.
here is the log of error:
02-14 19:24:11.685: E/AndroidRuntime(31027): java.lang.RuntimeException: Error receiving broadcast Intent { act=STARTED flg=0x10 } in com.webcraftbd.radio.MainActivity$RadioUpdateReceiver#42e09468
tabactivity.java:
public class AndroidTabLayoutActivity extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TabHost tabHost = getTabHost();
// Tab for Photos
TabSpec photospec = tabHost.newTabSpec("En Vivo");
photospec.setIndicator("En Vivo", getResources().getDrawable(R.drawable.icon_songs_tab));
Intent photosIntent = new Intent(this, MainActivity.class);
photospec.setContent(photosIntent);
// Tab for Songs
TabSpec songspec = tabHost.newTabSpec("Twitter");
// setting Title and Icon for the Tab
songspec.setIndicator("Twitter", getResources().getDrawable(R.drawable.icon_photos_tab));
Intent songsIntent = new Intent(this, SongsActivity.class);
songspec.setContent(songsIntent);
// Tab for Videos
TabSpec videospec = tabHost.newTabSpec("Contactenos");
videospec.setIndicator("Contactenos", getResources().getDrawable(R.drawable.icon_videos_tab));
Intent videosIntent = new Intent(this, VideosActivity.class);
videospec.setContent(videosIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(photospec); // Adding photos tab
tabHost.addTab(songspec); // Adding songs tab
tabHost.addTab(videospec); // Adding videos tab
for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
{
TextView tv = (TextView) tabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
tv.setTextColor(Color.WHITE);
tv.setPadding(0, 0, 0, 5);
tv.setShadowLayer(2, 2, 2, Color.BLACK);
}
}
}
MainActivity.java:
public class MainActivity extends BaseActivity{
private static boolean displayAd;
private Button playButton;
private Button pauseButton;
private Button stopButton;
private Button nextButton;
private Button previousButton;
private ImageView stationImageView;
private TextView albumTextView;
private TextView artistTextView;
private TextView trackTextView;
private TextView statusTextView;
private TextView timeTextView;
private Intent bindIntent;
private TelephonyManager telephonyManager;
private boolean wasPlayingBeforePhoneCall = false;
private RadioUpdateReceiver radioUpdateReceiver;
private RadioService radioService;
private AdView adView;
private String STATUS_BUFFERING;
private static final String TYPE_AAC = "aac";
private static final String TYPE_MP3 = "mp3";
private SeekBar volumeSeekbar = null;
private AudioManager audioManager = null;
private Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
setContentView(R.layout.activity_main);
initControls();
// Bind to the service
try {
bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
}
catch(Exception e) {
}
telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(telephonyManager != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
handler = new Handler();
initialize();
}
private void initControls() {
try {
volumeSeekbar = (SeekBar) findViewById(R.id.seekBar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
volumeSeekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
volumeSeekbar
.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0,
int progress, boolean arg2) {
audioManager.setStreamVolume(
AudioManager.STREAM_MUSIC, progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
int index = volumeSeekbar.getProgress();
volumeSeekbar.setProgress(index + 1);
return false;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
int index = volumeSeekbar.getProgress();
volumeSeekbar.setProgress(index - 1);
return false;
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT || newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
setContentView(R.layout.activity_main);
try {
handler.post( new Runnable() {
public void run() {
initialize();
if(radioService.getTotalStationNumber()<=1) {
nextButton.setEnabled(false);
nextButton.setVisibility(View.INVISIBLE);
previousButton.setEnabled(false);
previousButton.setVisibility(View.INVISIBLE);
}
updateStatus();
updateMetadata();
//updateAlbum();
System.out.println("radioService.isPreparingStarted() = "+radioService.isPreparingStarted());
}
});
}
catch(Exception e) {
e.printStackTrace();
}
}
}
public void initialize() {
try {
displayAd = (boolean) Boolean.parseBoolean(getResources().getString(R.string.is_display_ad));
STATUS_BUFFERING = getResources().getString(R.string.status_buffering);
playButton = (Button) this.findViewById(R.id.PlayButton);
pauseButton = (Button) this.findViewById(R.id.PauseButton);
stopButton = (Button) this.findViewById(R.id.StopButton);
nextButton = (Button) this.findViewById(R.id.NextButton);
previousButton = (Button) this.findViewById(R.id.PreviousButton);
pauseButton.setEnabled(false);
pauseButton.setVisibility(View.INVISIBLE);
stationImageView = (ImageView) findViewById(R.id.stationImageView);
playButton.setEnabled(true);
stopButton.setEnabled(false);
albumTextView = (TextView) this.findViewById(R.id.albumTextView);
artistTextView = (TextView) this.findViewById(R.id.artistTextView);
trackTextView = (TextView) this.findViewById(R.id.trackTextView);
statusTextView = (TextView) this.findViewById(R.id.statusTextView);
timeTextView = (TextView) this.findViewById(R.id.timeTextView);
startService(new Intent(this, RadioService.class));
displayAd();
} catch (Exception e) {
e.printStackTrace();
}
}
public void displayAd() {
if(displayAd==true) {
// Create the adView
try {
if (adView != null) {
adView.destroy();
}
adView = new AdView(this, AdSize.SMART_BANNER, this.getString(R.string.admob_publisher_id));
LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
layout.addView(adView);
adView.loadAd(new AdRequest());
} catch (OutOfMemoryError e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
else {
LinearLayout layout = (LinearLayout)findViewById(R.id.adLayout);
layout.setLayoutParams(new LinearLayout.LayoutParams(0,0));
layout.setVisibility(View.INVISIBLE);
}
}
public void updatePlayTimer() {
timeTextView.setText(radioService.getPlayingTime());
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
timeTextView.setText(radioService.getPlayingTime());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
}
public void onClickPlayButton(View view) {
radioService.play();
}
public void onClickPauseButton(View view) {
radioService.pause();
}
public void onClickStopButton(View view) {
radioService.stop();
//resetMetadata();
//updateDefaultCoverImage();
}
public void onClickNextButton(View view) {
resetMetadata();
playNextStation();
//updateDefaultCoverImage();
}
public void onClickPreviousButton(View view) {
resetMetadata();
playPreviousStation();
//updateDefaultCoverImage();
}
public void playNextStation() {
radioService.stop();
radioService.setNextStation();
/*
if(radioService.isPlaying()) {
radioService.setStatus(STATUS_BUFFERING);
updateStatus();
radioService.stop();
radioService.play();
}
else {
radioService.stop();
}
*/
}
public void playPreviousStation() {
radioService.stop();
radioService.setPreviousStation();
/*
if(radioService.isPlaying()) {
radioService.setStatus(STATUS_BUFFERING);
updateStatus();
radioService.stop();
radioService.play();
}
else {
radioService.stop();
}
*/
}
public void updateDefaultCoverImage() {
String mDrawableName = "station_"+(radioService.getCurrentStationID()+1);
int resID = getResources().getIdentifier(mDrawableName , "drawable", getPackageName());
stationImageView.setImageResource(resID);
albumTextView.setText("");
}
public void updateAlbum() {
String album = radioService.getAlbum();
String artist = radioService.getArtist();
String track = radioService.getTrack();
Bitmap albumCover = radioService.getAlbumCover();
albumTextView.setText(album);
if(albumCover==null || (artist.equals("") && track.equals("")))
updateDefaultCoverImage();
else {
stationImageView.setImageBitmap(albumCover);
radioService.setAlbum(LastFMCover.album);
if(radioService.getAlbum().length() + radioService.getArtist().length()>50) {
albumTextView.setText("");
}
}
}
public void updateMetadata() {
String artist = radioService.getArtist();
String track = radioService.getTrack();
//if(artist.length()>30)
//artist = artist.substring(0, 30)+"...";
artistTextView.setText(artist);
trackTextView.setText(track);
albumTextView.setText("");
}
public void resetMetadata() {
radioService.resetMetadata();
artistTextView.setText("");
albumTextView.setText("");
trackTextView.setText("");
}
#Override
public void onDestroy() {
super.onDestroy();
if(radioService!=null) {
if(!radioService.isPlaying() && !radioService.isPreparingStarted()) {
//radioService.stopSelf();
radioService.stopService(bindIntent);
}
}
if (adView != null) {
adView.destroy();
}
if(telephonyManager != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
}
#Override
protected void onResume() {
super.onResume();
/* Register for receiving broadcast messages */
if (radioUpdateReceiver == null) radioUpdateReceiver = new RadioUpdateReceiver();
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_CREATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_DESTROYED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STARTED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_START_PREPARING));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PREPARED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PLAYING));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_PAUSED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_STOPPED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_COMPLETED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_ERROR));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_START));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_BUFFERING_END));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_METADATA_UPDATED));
registerReceiver(radioUpdateReceiver, new IntentFilter(RadioService.MODE_ALBUM_UPDATED));
if(wasPlayingBeforePhoneCall) {
radioService.play();
wasPlayingBeforePhoneCall = false;
}
}
/* Receive Broadcast Messages from RadioService */
private class RadioUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(RadioService.MODE_CREATED)) {
}
else if (intent.getAction().equals(RadioService.MODE_DESTROYED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
//updateDefaultCoverImage();
updateMetadata();
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_STARTED)) {
pauseButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
playButton.setEnabled(true);
stopButton.setEnabled(false);
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_START_PREPARING)) {
pauseButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
playButton.setEnabled(false);
stopButton.setEnabled(true);
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_PREPARED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_START)) {
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_BUFFERING_END)) {
updateStatus();
}
else if (intent.getAction().equals(RadioService.MODE_PLAYING)) {
if(radioService.getCurrentStationType().equals(TYPE_AAC)) {
playButton.setEnabled(false);
stopButton.setEnabled(true);
}
else {
playButton.setEnabled(false);
pauseButton.setEnabled(true);
stopButton.setEnabled(true);
playButton.setVisibility(View.INVISIBLE);
pauseButton.setVisibility(View.VISIBLE);
}
updateStatus();
}
else if(intent.getAction().equals(RadioService.MODE_PAUSED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(true);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
}
else if(intent.getAction().equals(RadioService.MODE_STOPPED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
}
else if(intent.getAction().equals(RadioService.MODE_COMPLETED)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
}
else if(intent.getAction().equals(RadioService.MODE_ERROR)) {
playButton.setEnabled(true);
pauseButton.setEnabled(false);
stopButton.setEnabled(false);
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.INVISIBLE);
updateStatus();
}
else if(intent.getAction().equals(RadioService.MODE_METADATA_UPDATED)) {
updateMetadata();
updateStatus();
//updateDefaultCoverImage();
}
else if(intent.getAction().equals(RadioService.MODE_ALBUM_UPDATED)) {
//updateAlbum();
}
}
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
wasPlayingBeforePhoneCall = radioService.isPlaying();
radioService.stop();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
if(wasPlayingBeforePhoneCall) {
radioService.play();
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
wasPlayingBeforePhoneCall = radioService.isPlaying();
radioService.stop();
}
super.onCallStateChanged(state, incomingNumber);
}
};
public void updateStatus() {
String status = radioService.getStatus();
if(radioService.getTotalStationNumber() > 1) {
if(status!="")
status = radioService.getCurrentStationName()+" - "+status;
else
status = radioService.getCurrentStationName();
}
try {
statusTextView.setText(status);
}
catch(Exception e) {
e.printStackTrace();
}
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioService = ((RadioService.RadioBinder)service).getService();
if(radioService.getTotalStationNumber()<=1) {
nextButton.setEnabled(false);
nextButton.setVisibility(View.INVISIBLE);
previousButton.setEnabled(false);
previousButton.setVisibility(View.INVISIBLE);
}
updateStatus();
updateMetadata();
//updateAlbum();
updatePlayTimer();
radioService.showNotification();
//radioService.play();
}
public void onServiceDisconnected(ComponentName className) {
radioService = null;
}
};
}
baseactivity.java:
public class BaseActivity extends Activity {
private Intent bindIntent;
private RadioService radioService;
private static boolean isExitMenuClicked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isExitMenuClicked = false;
// Bind to the service
bindIntent = new Intent(this, RadioService.class);
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
#Override
protected void onResume() {
super.onResume();
if(isExitMenuClicked==true)
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i;
final String thisClassName = this.getClass().getName();
final String thisPackageName = this.getPackageName();
switch (item.getItemId()) {
case R.id.radio:
if(!thisClassName.equals(thisPackageName+".MainActivity")) {
i = new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return true;
}
break;
case R.id.facebook:
if(!thisClassName.equals(thisPackageName+".FacebookActivity")) {
i = new Intent(this, FacebookActivity.class);
startActivity(i);
return true;
}
break;
case R.id.twitter:
if(!thisClassName.equals(thisPackageName+".TwitterActivity")) {
i = new Intent(this, TwitterActivity.class);
startActivity(i);
return true;
}
break;
case R.id.about:
if(!thisClassName.equals(thisPackageName+".AboutActivity")) {
i = new Intent(this, AboutActivity.class);
startActivity(i);
return true;
}
break;
case R.id.exit:
String title = "Exit Radio";
String message = "Desea salir de la aplicacion?";
String buttonYesString = "Si";
String buttonNoString = "No";
isExitMenuClicked = true;
AlertDialog.Builder ad = new AlertDialog.Builder(this);
//ad.setTitle(title);
ad.setMessage(message);
ad.setCancelable(true);
ad.setPositiveButton(buttonYesString, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(radioService!=null) {
radioService.exitNotification();
radioService.stop();
radioService.stopService(bindIntent);
isExitMenuClicked = true;
finish();
}
}
});
ad.setNegativeButton(buttonNoString, null);
ad.show();
return true;
}
return super.onOptionsItemSelected(item);
}
// Handles the connection between the service and activity
private ServiceConnection radioConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
radioService = ((RadioService.RadioBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
radioService = null;
}
};
}
I dont know what else i can do to fix my main activity.
thank you very much.
bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);
In MainActivity.java, this code must be as below;
getApplicationContext().bindService(bindIntent, radioConnection, Context.BIND_AUTO_CREATE);