I set an interstitial after press a play button in the app.
Ok, this runs perfect but the interstitial appears immediately after the button pressed.
Is there a way to add a delay of to say 10 sec before it pop ups? Ie. user press plays and 10 sec after the interstitial appears.
In the code I have the following lines:
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
}
}
public void onClickPlayButton(View view) {
radioService.play();
interstitial.show();
}
Here is my full MainActity.java
public class MainActivity extends BaseActivity {
private InterstitialAd interstitial;
private static boolean displayAd;
private Button playButton;
private Button pauseButton;
private Button stopButton;
private Button nextButton;
private Button previousButton;
private ImageView stationImageView;
private TextView titleTextView;
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;
public static RadioService radioService;
private AdView mAdView;
private String STATUS_BUFFERING;
private static final String TYPE_AAC = "aac";
private static final String TYPE_MP3 = "mp3";
private Handler handler;
private AudioManager leftAm;
private SeekBar volControl;
private ContentObserver mVolumeObserver;
public static int stationID = 0;
public static boolean isStationChanged = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
interstitial = new InterstitialAd(MainActivity.this);
interstitial.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXXXXX");
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
interstitial.loadAd(adRequest);
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
displayInterstitial();
}
}, 60000);
// 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();
// Prepare an Interstitial Ad Listener
//interstitial.setAdListener(new AdListener() {
//public void onAdLoaded() {
// Call displayInterstitial() function
//displayInterstitial();
//}
//});
}
///public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
///if (interstitial.isLoaded()) {
///interstitial.show();
///}
///}
// agrega boton share a la app
#SuppressLint("NewApi")
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
MenuItem shareItem = (MenuItem) menu.findItem(R.id.action_share);
ShareActionProvider mShare = (ShareActionProvider)shareItem.getActionProvider();
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Listen to my radio https://play.google.com/store/apps/details?id=radio");
mShare.setShareIntent(shareIntent);
}
return true;
}
// fin boton share
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT
|| newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
try {
setContentView(R.layout.activity_main);
handler.post(new Runnable() {
#Override
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();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void initialize() {
try {
displayAd = 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);
titleTextView = (TextView) this.findViewById(R.id.titleTextView);
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);
// volume
leftAm = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = leftAm
.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = leftAm.getStreamVolume(AudioManager.STREAM_MUSIC);
volControl = (SeekBar) findViewById(R.id.volumebar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl
.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar a0, int a1,
boolean a2) {
leftAm.setStreamVolume(AudioManager.STREAM_MUSIC,
a1, 0);
}
});
Handler mHandler = new Handler();
// in onCreate put
mVolumeObserver = new ContentObserver(mHandler) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
if (volControl != null && leftAm != null) {
int volume = leftAm
.getStreamVolume(AudioManager.STREAM_MUSIC);
volControl.setProgress(volume);
}
}
};
this.getContentResolver()
.registerContentObserver(
System.getUriFor(System.VOLUME_SETTINGS[AudioManager.STREAM_MUSIC]),
false, mVolumeObserver);
// vloume
startService(new Intent(this, RadioService.class));
displayAd();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
volControl = (SeekBar) findViewById(R.id.volumebar);
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
int index = volControl.getProgress();
volControl.setProgress(index + 1);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
int index = volControl.getProgress();
volControl.setProgress(index - 1);
return true;
}
return super.onKeyDown(keyCode, event);
}
public void displayAd() {
if (displayAd == true) {
// Create the adView
try {
if (mAdView != null) {
mAdView.destroy();
}
mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(new AdRequest.Builder().build());
} 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() {
#Override
public void run() {
timeTextView.setText(radioService.getPlayingTime());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000);
}
public void displayInterstitial() {
// If Ads are loaded, show Interstitial else show nothing.
if (interstitial.isLoaded()) {
}
}
public void onClickPlayButton(View view) {
radioService.play();
interstitial.show();
}
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() {
try {
String mDrawableName = "station_"
+ (radioService.getCurrentStationID() + 1);
int resID = getResources().getIdentifier(mDrawableName, "drawable",
getPackageName());
int resID_default = getResources().getIdentifier("station_default",
"drawable", getPackageName());
if (resID > 0)
stationImageView.setImageResource(resID);
else
stationImageView.setImageResource(resID_default);
albumTextView.setText("");
} catch(Exception e) {
e.printStackTrace();
}
}
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
protected void onDestroy() {
super.onDestroy();
if (radioService != null) {
if (!radioService.isPlaying() && !radioService.isPreparingStarted()) {
// radioService.stopSelf();
radioService.stopService(bindIntent);
}
}
if (mAdView != null) {
mAdView.destroy();
}
if (telephonyManager != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
unbindDrawables(findViewById(R.id.RootView));
Runtime.getRuntime().gc();
}
private void unbindDrawables(View view) {
try {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
super.onPause();
if (radioUpdateReceiver != null)
unregisterReceiver(radioUpdateReceiver);
// finish();
}
#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_CONNECTING));
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;
}
if (radioService != null) {
if (isStationChanged) {
if (stationID != radioService.getCurrentStationID()) {
radioService.stop();
radioService.setCurrentStationID(stationID);
resetMetadata();
updateDefaultCoverImage();
}
if (!radioService.isPlaying())
radioService.play();
isStationChanged = 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_CONNECTING)) {
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_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);
// radioService.setCurrentStationURL2nextSlot();
// radioService.play();
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();
*/
String title = radioService.getCurrentStationName();
try {
titleTextView.setText(title);
} catch (Exception e) {
e.printStackTrace();
}
}
try {
statusTextView.setText(status);
} catch (Exception e) {
e.printStackTrace();
}
}
// Handles the connection between the service and activity
private final ServiceConnection radioConnection = new ServiceConnection() {
#Override
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();
/*
* Uncomment following line if you want auto-play while starting the
* app
*/
// radioService.play();
}
#Override
public void onServiceDisconnected(ComponentName className) {
radioService = null;
}
};
}
Use a Handler. See this code:
new Handler().postDelayed(new Runnable(){
public void run() {
//Your your code here.
}
}, 5000); //Here 5000 is the time delay. Change it accordingly.
Kvaibhav01's answer will work. You can also use Timer:
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
public void run() {
//your code here
}
}, 1000); //delay in ms
I tried the handler and now works (I messed up the order)
This is the correct code:
public void onClickPlayButton(View view) {
radioService.play();
new Handler().postDelayed(new Runnable(){
public void run() {
interstitial.show();
}
}, 10000);
Thank you very much for the help!
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'm trying to using Cleveroad WaveInApp in my Application
https://github.com/Cleveroad/WaveInApp everything is working fine as I want but when Song Completed it also stops mediaPlayer.setOnCompletionListener(which works fine when I removed this code).
When I try to change the song it crashes.
Error :-
java.lang.NullPointerException: Attempt to invoke interface method 'void com.cleveroad.audiovisualization.InnerAudioVisualization.stopRendering()' on a null object reference
at com.cleveroad.audiovisualization.DbmHandler.stopRendering(DbmHandler.java:61)
at com.cleveroad.audiovisualization.DbmHandler$2.onCalmedDown(DbmHandler.java:82)
at com.cleveroad.audiovisualization.GLAudioVisualizationView$1.onCalmedDown(GLAudioVisualizationView.java:49)
at com.cleveroad.audiovisualization.GLRenderer.onDrawFrame(GLRenderer.java:87)
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1608)
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1299)
MainContainer.class
public class MainContainer extends AppCompatActivity
implements
NavigationView.OnNavigationItemSelectedListener,
SeekBar.OnSeekBarChangeListener {
private static final String LOGTAG = "Friday";
public static final String isPlay = "isPlay";
public static final String NOTIFICATION_ACTION = "Notification_Action";
private static final String VOLUME_BUTTON = "android.media.VOLUME_CHANGED_ACTION";
SlidingUpPanelLayout slideLayout;
MusicService mService;
boolean mBound = false;
Timer t = new Timer();
SeekBar seekBar;
ImageView albumArt;
ImageView panelAlbumart;
TextView songname;
TextView singername;
TextView seekCurrentDuration;
TextView seekTotalDuration;
TextView panelSongname;
TextView panelSingername;
ImageView playBtn;
IntentFilter mIntentFilter;
RelativeLayout panelHead;
SeekBar volumeControl;
AudioManager audioManager;
AudioVisualization audioVisualization;
VisualizerDbmHandler vizualizerHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_container);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setVolumeControlStream(AudioManager.STREAM_MUSIC); //best practice to set volume control
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ViewPager vp_pages = findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter = new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(isPlay);
mIntentFilter.addAction(VOLUME_BUTTON);
mIntentFilter.addAction(NOTIFICATION_ACTION);
TabLayout tbl_pages = findViewById(R.id.tbl_pages);
tbl_pages.setupWithViewPager(vp_pages);
seekBar = findViewById(R.id.seek_bar_red);
seekBar.setOnSeekBarChangeListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_container, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
// Bind to LocalService
Intent intent = new Intent(this, MusicService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
unbindService(mConnection);
mBound = false;
}
// control Volume by Seekbar
private void volumeControl() {
volumeControl = findViewById(devil.jarvis.friday.R.id.volume_control);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager != null) {
volumeControl.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
volumeControl.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_MUSIC));
}
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
init();
//todo add this when song is played
audioVisualization.onResume();
updateUI();
volumeControl();
}
#Override
public void onPause() {
audioVisualization.onPause();
unregisterReceiver(mReceiver);
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private void init() {
albumArt = findViewById(R.id.musicArt);
panelAlbumart = findViewById(R.id.slidePanelArt);
songname = findViewById(R.id.song_name);
singername = findViewById(R.id.singer_name);
panelSingername = findViewById(R.id.singer_name_head);
panelSongname = findViewById(R.id.song_name_head);
seekCurrentDuration = findViewById(R.id.current_time);
seekTotalDuration = findViewById(R.id.song_duration);
playBtn = findViewById(R.id.play);
panelHead = findViewById(R.id.header);
slideLayout = findViewById(R.id.sliding_layout);
audioVisualization = findViewById(R.id.visualizer_view);
}
public void updateUI() {
//Update UI
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (mBound) {
try {
setupMusicUI(mService.getCurrentDuration(), mService.getDuration());
} catch (Exception e) {
//
}
}
}
}, 0, 1000);
}
private void setupMusicUI(int currentDuration, int duration) {
seekBar.setMax(duration);
seekBar.setProgress(currentDuration);
}
// code for update song details
private void updateTextInfo() {
if (mBound) {
int pos = mService.getPosition();
panelSongname.setText(arrayList.get(pos));
panelSingername.setText(artistName.get(pos));
songname.setText(arrayList.get(pos));
singername.setText(artistName.get(pos));
//update album art with text also
updateAlbumArt();
changePlayBtn();
startEqualiser();
// try{
// startEqualiser();
// }catch (Exception e){
// //
// }
}
}
private void setSeekbarTime(int position, int duration) {
int curr_time_seconds = (position / 1000) % 60;
int curr_time_minutes = (position / 1000) / 60;
int dur_time_seconds = (duration / 1000) % 60;
int dur_time_minutes = (duration / 1000) / 60;
String current_zero_minutes = "0";
String current_zero_seconds = "0";
String duration_zero_minues = "0";
String duration_zero_seconds = "0";
if (curr_time_minutes > 9)
current_zero_minutes = "";
if (curr_time_seconds > 9)
current_zero_seconds = "";
if (dur_time_minutes > 9)
duration_zero_minues = "";
if (dur_time_seconds > 9)
duration_zero_seconds = "";
seekCurrentDuration.setText(current_zero_minutes + curr_time_minutes + ":" + current_zero_seconds + curr_time_seconds);
seekTotalDuration.setText(duration_zero_minues + dur_time_minutes + ":" + duration_zero_seconds + dur_time_seconds);
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(VOLUME_BUTTON)) {
volumeControl();
}
if (intent.getAction().equals(isPlay)) {
boolean show = intent.getBooleanExtra("showPanel", false);
if (show) {
//show Panel here
slideLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
updateTextInfo();
}
} else if (intent.getAction().equals(NOTIFICATION_ACTION)) {
int action = intent.getIntExtra("action", 0);
switch (action) {
case 1:
changePlayBtn();
break;
case 2:
updateTextInfo();
break;
case 3:
updateTextInfo();
break;
case 4:
audioVisualization.release();
break;
default:
break;
}
}
}
};
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
public void playBtn(View view) {
if (mBound) {
mService.play();
changePlayBtn();
}
}
private void changePlayBtn() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
playBtn.setImageResource(R.drawable.ic_pause_button);
} else {
playBtn.setImageResource(R.drawable.ic_play_arrow);
}
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
setSeekbarTime(i, mediaPlayer.getDuration());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mService.changeSeekTo(seekBar.getProgress());
}
public void previousBtn(View view) {
if (mBound) {
mService.previous();
updateTextInfo();
}
}
public void nextBtn(View view) {
if (mBound) {
mService.next();
updateTextInfo();
}
}
public void startEqualiser() {
try {
vizualizerHandler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(vizualizerHandler);
} catch (Exception e) {
// TODO change it to snackbar message
Toast.makeText(mService, "Please Give Mic Permission", Toast.LENGTH_SHORT).show();
}
}
public void updateAlbumArt() {
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(panelAlbumart);
Glide
.with(getApplicationContext())
.load(songThumb.get(musicPosition))
.placeholder(R.drawable.ic_default_icon)
.into(albumArt);
}
}
and this is my MusicService.class
public class MusicService extends MediaBrowserServiceCompat implements
MediaPlayer.OnCompletionListener,
AudioManager.OnAudioFocusChangeListener {
private static final String LOGTAG = "Friday";
public static int musicPosition;
public static MediaPlayer mediaPlayer;
Uri u;
// Binder given to clients
private final IBinder mBinder = new LocalBinder();
Notification status;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && intent.getExtras() != null && intent.getExtras().containsKey("pos")) {
musicPosition = intent.getIntExtra("pos", 0);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
}
if (arrayList != null) {
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
}
try {
playSong();
} catch (Exception e) {
next();
}
}
if (intent.getAction() != null) {
if (intent.getAction().equals(Constants.ACTION.PREV_ACTION)) {
previous();
} else if (intent.getAction().equals(Constants.ACTION.PLAY_ACTION)) {
play();
sendAction(1);
} else if (intent.getAction().equals(Constants.ACTION.NEXT_ACTION)) {
next();
}
}
return super.onStartCommand(intent, flags, startId);
}
private void playSong() {
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.start();
showNotification();
}
private void sendAction(int action){
/* 1 for play or pause
* 2 for next
* 3 for previous
*/
Intent intent = new Intent();
intent.setAction(MainContainer.NOTIFICATION_ACTION);
intent.putExtra("action",action);
sendBroadcast(intent);
}
public int getPosition() {
return musicPosition;
}
public int getCurrentDuration() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public void changeSeekTo(int progress) {
mediaPlayer.seekTo(progress);
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MusicService getService() {
// Return this instance of LocalService so clients can call public methods
return MusicService.this;
}
}
public void next() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition + 1) % songPath.size();
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(2);
}
}
public void previous() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
musicPosition = (musicPosition - 1 < 0) ? songPath.size() - 1 : musicPosition - 1;
u = Uri.parse(songPath.get(musicPosition));
mediaPlayer = MediaPlayer.create(getApplicationContext(), u);
playSong();
sendAction(3);
}
}
public void play() {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
showNotification();
} else {
mediaPlayer.start();
showNotification();
}
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onAudioFocusChange(int i) {
mediaPlayer.stop();
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
sendAction(4);
next();
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return null;
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
}
.
.
.
}
I don't know what happened.
Can anybody know about it.
There is already mediaPlayer.setOnCompleteListener inside VisualizerDbmHandler. So, for use it in other places you should use setInnerOnCompletionListener method to add own complete listener to VisualizerDbmHandler
Try do not recreate mediaPlayer but setup new source to it
**My conclusion is**: As you can see in source code of MediaPlayer - it will call onCompletion in cases that unhandled error appears). So, I think, because of recreating mediaPlayer in time, when you call startEqualizer ( recreate visualizerHandler and link it to visualizer view) inside the method linkTo - library call release to previous visualizerHandler and setup variable audioVisualizer to null, that provide you to calling stopRendering on null reference in case of onCompletion calling during to some error during reset/stop/release of MediaPlayer.
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();
}
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);
I created a Karaoke application. But I can't stop the MediaPlayer with out an error. When I press Back Button to go to home, I get "sorry ,Application has stopped working" The same thing happens if I try to start another activity
public class Main extends Activity implements MediaPlayerControl {
private MediaController mMediaController;
private MediaPlayer mMediaPlayer;
Handler mHandler = new Handler();
public TextView subtitles,subtitles2;
static Context context;
#SuppressLint("HandlerLeak")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.Main);
subtitles = (TextView) findViewById(R.id.subs2);
subtitles2 = (TextView) findViewById(R.id.subs21);
mMediaPlayer = new MediaPlayer();
mMediaController = new MediaController(this)
/*
* {
*
* #Override public void hide() { mMediaController.show(0); } }
*/;
mMediaController.setMediaPlayer(Main.this);
mMediaController.setAnchorView(findViewById(R.id.AudioView));
mMediaController.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Next button clicked
Intent intent = new Intent(Main.this, Hello.class);
startActivity(intent);
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
// Previous button clicked
Intent intent = new Intent(Main.this, Sorry.class);
startActivity(intent);
}
});
// String audioFile = "" ;
try {
mMediaPlayer.setDataSource(this, Uri
.parse("android.resource://com.app.suadmon/raw/buchatri"));
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
final long currentPos = mMediaPlayer.getCurrentPosition();
if (currentPos < 5130) {
subtitles.setText("1111+");
} else if (currentPos > 5130 && currentPos < 10572) {
subtitles.setText("555+");
} else if (currentPos > 10572 && currentPos < 10597) {
subtitles.setText("666+");
} else if (currentPos > 15312 && currentPos < 18478) {
subtitles.setText("777+");
} else if (currentPos > 18478 && currentPos < 24191) {
subtitles.setText("888+");
} else if (currentPos > 24191 && currentPos < 28137) {
subtitles.setText("999+");
} else if (currentPos > 28137 && currentPos < 29500) {
subtitles.setText("Thank you");
subtitles2.setText(".............");
}
mHandler.sendEmptyMessageDelayed(0, 1);
}
};
mHandler.sendEmptyMessage(0);
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mHandler.post(new Runnable() {
public void run() {
mMediaController.show(0);
// mMediaPlayer.reset();
mMediaPlayer.start();
}
});
}
});
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
Intent stopplay = new Intent(Main.this, Hello.class);
startActivity(stopplay);
}
});
}
protected void onDestroy() {
super.onDestroy();
mMediaPlayer.stop();
mMediaPlayer.release();
}
public void releaseMediaPlayer(){
if(mMediaPlayer != null){
mMediaPlayer.release();
mMediaPlayer = null;
}
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
int percentage = (mMediaPlayer.getCurrentPosition() * 100)
/ mMediaPlayer.getDuration();
return percentage;
}
public int getCurrentPosition() {
return mMediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mMediaPlayer.getDuration();
}
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
public void seekTo(int pos) {
mMediaPlayer.seekTo(pos);
}
#Override
public void pause() {
// TODO Auto-generated method stub
mMediaPlayer.pause();
}
protected void onPause() {
super.onPause();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.pause();
}
protected void onResume() {
super.onResume();
mMediaPlayer.seekTo(0);
mMediaPlayer.start();
}
// public void onUserLeaveHint(){
// mMediaPlayer.stop();
// super.onUserLeaveHint();
// }
/*
* public void stopPlayback(){ mMediaPlayer.stop(); }
*/
public void start() {
mMediaPlayer.start();
}
public boolean onTouchEvent(MotionEvent event) {
mMediaController.show(0);
return false;
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
finish();
Intent intent = new Intent(Main.this, Show.class);
startActivity(intent);
super.onBackPressed();
}
}
and Log Cat's here.
How can I fix this. I have no idea.
Can anyone help me. Please !!!
You need to stop and release the media player before your activity finishes. Try adding this to your activity:
#Override
protected void onDestroy() {
super.onDestroy();
if(mMediaPlayer != null)
{
mMediaPlayer.stop();
mMediaPlayer.release();
}
}