Issues with tabactivity and mainactivity using service - android

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);

Related

when back to activity from click music notification when click to next music view not update

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;
}

Cleveroad WaveInApp shows error after song completion

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.

Interstitial appears immediatelly after pressing a button, want to add a delay

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!

sinch conference call hung up right after it starts

I managed to start a conference call cut it closes right after I start it with HUNG_UP cause and I got this in my log:
11-03 17:28:08.940: E/sinch-android-rtc(19101): peermediaconnection: virtual void rebrtc::SetSDPObserver::OnFailure(const string&)Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
11-03 17:28:08.940: E/sinch-android-rtc(19101): mxp: Failed to set remote answer sdp: Offer and answer descriptions m-lines are not matching. Rejecting answer.
can anybody help me solve this please?
Edit:
my scenario is when a user clicks the call button I ask him if he wants to start a new call or join an already created one.
I managed to make my code from this question (Sinch conference call error) work as my GroupService class had some bugs.
I start my call like this:
Intent intent1 = new Intent(CreateGroupCallActivity.this,SinchClientService.class);
intent1.setAction(SinchClientService.ACTION_GROUP_CALL);
String id = String.valueOf(uid) + "-" + call_id.getText().toString();
intent1.putExtra(SinchClientService.INTENT_EXTRA_ID,id);
startService(intent1);
and in my SinchClientService:
if(intent.getAction().equals(ACTION_GROUP_CALL))
{
String id = intent.getStringExtra(INTENT_EXTRA_ID);
if(id != null)
groupCall(id);
}
public void groupCall(String id) {
if (mCallClient != null) {
Call call = mCallClient.callConference(id);
CurrentCall.currentCall = call;
Log.d("call", "entered");
Intent intent = new Intent(this, GroupCallService.class);
startService(intent);
}
}
nd here is my GroupCallService
public class GroupCallScreenActivity extends AppCompatActivity implements ServiceConnection {
private SinchClientService.MessageServiceInterface mMessageService;
private GroupCallService.GroupCallServiceInterface mCallService;
private UpdateReceiver mUpdateReceiver;
private ImageButton mEndCallButton;
private TextView mCallDuration;
private TextView mCallState;
private TextView mCallerName;
//private TextView locationview;
private ImageView user_pic;
private long mCallStart;
private Timer mTimer;
private UpdateCallDurationTask mDurationTask;
ImageButton chat;
ImageButton speaker;
ImageButton mic;
boolean speaker_on = false;
boolean mic_on = true;
PowerManager mPowerManager;
WakeLock mProximityWakeLock;
final static int PROXIMITY_SCREEN_OFF_WAKE_LOCK = 32;
com.galsa.example.main.ImageLoader mImageLoader;
/*String location;
String longitude;
String latitude;*/
private class UpdateCallDurationTask extends TimerTask {
#Override
public void run() {
GroupCallScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
updateCallDuration();
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
setContentView(R.layout.callscreen);
doBind();
mCallDuration = (TextView) findViewById(R.id.callDuration);
mCallerName = (TextView) findViewById(R.id.remoteUser);
mCallState = (TextView) findViewById(R.id.callState);
//locationview = (TextView) findViewById(R.id.location);
mEndCallButton = (ImageButton) findViewById(R.id.hangupButton);
chat = (ImageButton) findViewById(R.id.chat);
chat.setVisibility(View.GONE);
speaker = (ImageButton) findViewById(R.id.speaker);
mic = (ImageButton) findViewById(R.id.mic);
user_pic = (ImageView) findViewById(R.id.user_pic);
/*location = getIntent().getStringExtra("location");
longitude = getIntent().getStringExtra("longitde");
latitude = getIntent().getStringExtra("latitude");
locationview.setText(location);*/
mImageLoader = new com.galsa.example.main.ImageLoader(GroupCallScreenActivity.this, R.dimen.caller_image_height);
//mCallerName.setText(mCall.getRemoteUserId());
mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mProximityWakeLock = mPowerManager.newWakeLock(PROXIMITY_SCREEN_OFF_WAKE_LOCK, Utils.TAG);
/*chat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(GroupCallScreenActivity.this, MessagingActivity.class);
intent.putExtra(SinchClientService.INTENT_EXTRA_ID, mCallService.getCallerId());
intent.putExtra(SinchClientService.INTENT_EXTRA_NAME, mCallService.getCallerName());
startActivity(intent);
}
});*/
speaker.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(speaker_on)
{
mMessageService.speakerOn(speaker_on);
speaker_on = false;
speaker.setImageResource(R.drawable.speaker_off);
}
else
{
mMessageService.speakerOn(speaker_on);
speaker_on = true;
speaker.setImageResource(R.drawable.speaker_on);
}
}
});
mic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mic_on)
{
mMessageService.micOn(mic_on);
mic_on = false;
mic.setImageResource(R.drawable.mic_off);
}
else
{
mMessageService.micOn(mic_on);
mic_on = true;
mic.setImageResource(R.drawable.mic_on);
}
}
});
mEndCallButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCallService.endCall();
}
});
mCallStart = System.currentTimeMillis();
}
private void doBind() {
Intent intent = new Intent(this, SinchClientService.class);
bindService(intent, this, BIND_AUTO_CREATE);
intent = new Intent(this, GroupCallService.class);
bindService(intent, this, BIND_AUTO_CREATE);
}
private void doUnbind() {
unbindService(this);
}
#Override
protected void onStart() {
super.onStart();
mUpdateReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(GroupCallService.ACTION_FINISH_CALL_ACTIVITY);
filter.addAction(GroupCallService.ACTION_CHANGE_AUDIO_STREAM);
filter.addAction(GroupCallService.ACTION_UPDATE_CALL_STATE);
LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateReceiver, filter);
}
#Override
public void onResume() {
super.onResume();
if(mProximityWakeLock != null && !mProximityWakeLock.isHeld()){
mProximityWakeLock.acquire();
}
mTimer = new Timer();
mDurationTask = new UpdateCallDurationTask();
mTimer.schedule(mDurationTask, 0, 500);
}
#Override
public void onPause() {
super.onPause();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
mDurationTask.cancel();
}
#Override
protected void onStop() {
super.onStop();
if(isFinishing() && mProximityWakeLock != null && mProximityWakeLock.isHeld()){
mProximityWakeLock.release();
}
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
}
#Override
public void onBackPressed() {
// User should exit activity by ending call, not by going back.
}
private void updateCallDuration() {
mCallDuration.setText(Utils.formatTimespan(System.currentTimeMillis() - mCallStart));
}
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
if(iBinder instanceof GroupCallService.GroupCallServiceInterface)
{
mCallService = (GroupCallService.GroupCallServiceInterface) iBinder;
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
ActionBar actionBar = getSupportActionBar();
if(mCallService.getCallerName() != null)
actionBar.setTitle(mCallService.getCallerName());
else
actionBar.setTitle("Group call");
actionBar.setIcon(R.drawable.callscreen);
if(mCallService.getCallerName() != null)
mCallerName.setText(mCallService.getCallerName());
else
mCallerName.setText("Group call");
mCallState.setText(mCallService.getCallState());
String pic = ChatDatabaseHandler.getInstance(this).getFriendpic(mCallService.getCallerId());
mImageLoader.displayImage(UserFunctions.hostImageDownloadURL + pic, user_pic);
}
else
mMessageService = (SinchClientService.MessageServiceInterface) iBinder;
mMessageService.enableMic();
mMessageService.disableSpeaker();
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mMessageService = null;
mCallService = null;
}
#Override
public void onDestroy() {
if(mUpdateReceiver != null)
{
LocalBroadcastManager.getInstance(this).unregisterReceiver(mUpdateReceiver);
mUpdateReceiver = null;
}
doUnbind();
super.onDestroy();
}
private class UpdateReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if(GroupCallService.ACTION_FINISH_CALL_ACTIVITY.equals(intent.getAction()))
{
finish();
}
else if(GroupCallService.ACTION_CHANGE_AUDIO_STREAM.equals(intent.getAction()))
{
setVolumeControlStream(intent.getIntExtra("STREAM_TYPE", AudioManager.USE_DEFAULT_STREAM_TYPE));
}
else if(GroupCallService.ACTION_UPDATE_CALL_STATE.equals(intent.getAction()))
{
mCallState.setText(intent.getStringExtra("STATE"));
}
}
}
}
I start the call with the same way whether the user will start a new call or join a created one.

NullPointerException when initializing the media player on url

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;
}

Categories

Resources