How do I override the actions of the ExoPlayer buttons - android

I created my layout for the ExoPlayer buttons
***
<ImageButton
android:id="#id/exo_play"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPlayClick"
android:background="#drawable/btn_play" />
<ImageButton
android:id="#id/exo_pause"
android:layout_width="50dp"
android:layout_height="50dp"
android:onClick="onPauseClick"
android:background="#drawable/btn_pause" />
***
I have a program in my program that starts and stops from the PlayerActivity. How to make the service stop when clicking on the pause button in the EcxoPlayer, and when you click on play, the service was restarted?
Code PlayerActivity
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private ImageButton exo_pause;
private ImageButton exo_play;
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (!isPlay) {
startPlayerService();
}
}
}
});
}
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
exo_pause.setVisibility(View.VISIBLE);
exo_play.setVisibility(View.GONE);
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
I tried to implement the actions of buttons in onresume but when I pause the service it stops and the play button does not play

Your OnClickListener should be in OnCreate, try this and let me know:
public class PlayerActivity extends AppCompatActivity {
private int id;
private String title;
private String autor;
private String file;
private String img;
private String MAYBE_ACTION = "MAYBE_ACTION";
static boolean isPlay = false;
ImageButton btnPLayPause;
private TextView txtRadio;
private TextView txtTitle;
private RoundedImageView imgRadio;
private SimpleExoPlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageButton exo_pause;
private ImageButton exo_play;
public static String LOG_TAG = "my_log";
private String internetStatus = "";
BroadcastReceiver br;
BroadcastReceiver serviceReceiver;
private AsyncTask jsonTask;
public final static String SERVICE_PARAM = "param";
public final static int SERVICE_STATUS = 0;
public final static String BROADCAST_ACTION = "ru.myapps";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
id = getIntent().getExtras().getInt("id");
title = getIntent().getExtras().getString("title");
autor = getIntent().getExtras().getString("autor");
file = "link_mp3_files";
img = getIntent().getExtras().getString("img");
RadioPlayer.simpleExoPlayerView = new SimpleExoPlayerView(this);
RadioPlayer.simpleExoPlayerView = (SimpleExoPlayerView) findViewById(R.id.player);
btnPLayPause = (ImageButton) findViewById(R.id.btnPLayPause);
txtRadio = (TextView) findViewById(R.id.txtRadio);
imgRadio = (RoundedImageView) findViewById(R.id.imgRadio);
exo_pause = (ImageButton) findViewById(R.id.exo_pause);
exo_play = (ImageButton) findViewById(R.id.exo_play);
setTitle(title);
txtRadio.setText(title);
if (NetworkUtil.getConnectivityStatus(this) != 0) {
startPlayerService();
}
exo_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isPlay) {
stopPlayerService();
}
}
});
exo_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (NetworkUtil.getConnectivityStatus(PlayerActivity.this) != 0 ) {
if (isPlay) {
startPlayerService();
}
}
}
});
br = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter intentFilter = new IntentFilter(MAYBE_ACTION);
registerReceiver(br, intentFilter);
}
#Override
protected void onStart() {
super.onStart();
}
public void startPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.putExtra(PlayerService.KEY_STREAM, file);
serviceIntent.putExtra(PlayerService.KEY_RADIO, title);
serviceIntent.setAction(PlayerConstants.ACTION.STARTFOREGROUND_ACTION);
startService(serviceIntent);
isPlay = true;
btnPLayPause.setImageResource(R.drawable.icon_stop);
if(exo_play.getVisibility() == View.VISIBLE) {
exo_play.setVisibility(View.GONE);
exo_pause.setVisibility(View.VISIBLE);
}
}
private void stopPlayerService() {
Intent serviceIntent = new Intent(PlayerActivity.this, PlayerService.class);
serviceIntent.setAction(PlayerConstants.ACTION.STOPFOREGROUND_ACTION);
stopService(serviceIntent);
isPlay = false;
btnPLayPause.setImageResource(R.drawable.icon_play);
if(exo_pause.getVisibility() == View.VISIBLE) {
exo_pause.setVisibility(View.GONE);
exo_play.setVisibility(View.VISIBLE);
}
}
private BroadcastReceiver NetworkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
internetStatus = NetworkUtil.getConnectivityStatusString(context);
//Toast.makeText(context, internetStatus, Toast.LENGTH_LONG).show();
}
};
#Override
protected void onResume() {
super.onResume();
serviceReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int serviceStatus = intent.getIntExtra(SERVICE_PARAM, 0);
if (serviceStatus == SERVICE_STATUS) {
btnPLayPause.setImageResource(R.drawable.icon_play);
}
}
};
IntentFilter filter = new IntentFilter(BROADCAST_ACTION);
registerReceiver(serviceReceiver, filter);
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
registerReceiver(NetworkChangeReceiver, new IntentFilter("android.net.wifi.WIFI_STATE_CHANGED"));
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (NetworkChangeReceiver != null) unregisterReceiver(NetworkChangeReceiver);
unregisterReceiver(br);
unregisterReceiver(serviceReceiver);
}
}
In OnResume you can check if it is running or not then stoo it if you would like to.
Your problem is that you never called startPlayerService(); when exo_play is tapped. Please see exo_play.setOnClickListener. I also removed the else statement as it is unnecessary.

Related

MediaBrowserServiceCompat stopped playing music when app goes background

Mediabrowsercompat not playing the music when app goes background. If I don't disconnect the mediabrowsercompat instance in activity onStop method then it is working. But that is not the solution as according to documentation we have to disconnect the service once app goes background.
This is my mediabroweserservicecomat class (I am using Exoplayer to play music):
private static final String PLAYBACK_CHANNEL_ID = "100";
private static final int PLAYBACK_NOTIFICATION_ID =101 ;
private MediaSessionCompat mediaSessionCompat;
private PlaybackStateCompat.Builder stateBuilder;
private SimpleExoPlayer exoPlayer;
private Uri oldUri;
private AudioAttributes audioAttributes;
private PlayerNotificationManager playerNotificationManager;
#Override
public void onCreate() {
super.onCreate();
Log.i("Test","Hi");
initPlayer();
initAttributes();
ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);
mediaSessionCompat = new MediaSessionCompat(getApplicationContext(), "Tag", mediaButtonReceiver, null);
mediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS|
MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
stateBuilder = new PlaybackStateCompat.Builder();
stateBuilder.setActions(PlaybackStateCompat.ACTION_PLAY|PlaybackStateCompat.ACTION_PLAY_PAUSE);
mediaSessionCompat.setPlaybackState(stateBuilder.build());
mediaSessionCompat.setCallback(mediaSessionCompatCallback);
setSessionToken(mediaSessionCompat.getSessionToken());
mediaSessionCompat.setActive(true);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setClass(this, MediaButtonReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
mediaSessionCompat.setMediaButtonReceiver(pendingIntent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaButtonReceiver.handleIntent(mediaSessionCompat,intent);
return super.onStartCommand(intent, flags, startId);
}
private MediaSessionCompat.Callback mediaSessionCompatCallback = new MediaSessionCompat.Callback() {
#Override
public void onPlayFromUri(Uri uri, Bundle extras) {
super.onPlayFromUri(uri, extras);
if (uri!=null){
MediaItem mediaSource = MediaItem.fromUri(uri);
if (uri!=oldUri){
play(mediaSource);
onPlay();
}else {
oldUri = uri;
}
}
}
#Override
public void onPlay() {
super.onPlay();
Log.i("onPlay","onPlay");
//startService(new Intent(MusicService.this,MusicForegroundService.class));
playerNotificationManager = PlayerNotificationManager.createWithNotificationChannel(MusicService.this,
PLAYBACK_CHANNEL_ID, R.string.channel_name, PLAYBACK_NOTIFICATION_ID,
new PlayerNotificationManager.MediaDescriptionAdapter() {
#Override
public CharSequence getCurrentContentTitle(Player player) {
return "title";
}
#Nullable
#Override
public PendingIntent createCurrentContentIntent(Player player) {
Intent intent = new Intent(getBaseContext(), PlayerFullViewActivity.class);
return PendingIntent.getActivity(getBaseContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
#Nullable
#Override
public CharSequence getCurrentContentText(Player player) {
return "content";
}
#Nullable
#Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
return null;
}
},
new PlayerNotificationManager.NotificationListener() {
#Override
public void onNotificationPosted(int notificationId, Notification notification, boolean ongoing) {
startForeground(notificationId,notification);
}
#Override
public void onNotificationCancelled(int notificationId, boolean dismissedByUser) {
stopSelf();
}
});
playerNotificationManager.setPlayer(exoPlayer);
}
#Override
public void onPause() {
super.onPause();
pause();
}
#Override
public void onStop() {
playerNotificationManager.setPlayer(null);
super.onStop();
stop();
}
};
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
private void stop() {
exoPlayer.setPlayWhenReady(false);
exoPlayer.release();
exoPlayer =null;
updatePlayBackState(PlaybackStateCompat.STATE_NONE);
mediaSessionCompat.setActive(false);
mediaSessionCompat.release();
}
#SuppressLint("WrongConstant")
private void pause() {
if (exoPlayer!=null){
exoPlayer.setPlayWhenReady(false);
if (exoPlayer.getPlaybackState()==PlaybackStateCompat.STATE_PLAYING){
updatePlayBackState(PlaybackStateCompat.STATE_PAUSED);
}
}
}
private void play(MediaItem mediaSource){
if (exoPlayer==null) {
initPlayer();
}
if (audioAttributes==null) {
initAttributes();
}
exoPlayer.setAudioAttributes(audioAttributes,true);
exoPlayer.setMediaItem(mediaSource);
exoPlayer.prepare();
play();
}
private void initAttributes() {
audioAttributes = new AudioAttributes.Builder().setUsage(C.USAGE_MEDIA)
.setContentType(C.CONTENT_TYPE_MUSIC)
.build();
}
private void initPlayer() {
exoPlayer = new SimpleExoPlayer.Builder(this, new DefaultRenderersFactory(getBaseContext()),
new DefaultExtractorsFactory()).build();
}
private void play() {
exoPlayer.setPlayWhenReady(true);
updatePlayBackState(PlaybackStateCompat.STATE_PLAYING);
mediaSessionCompat.setActive(true);
}
private void updatePlayBackState(int statePlaying) {
mediaSessionCompat.setPlaybackState(new PlaybackStateCompat.Builder().
setState(statePlaying,0L,0).build());
}
#Nullable
#Override
public BrowserRoot onGetRoot(#NonNull String clientPackageName, int clientUid, #Nullable Bundle rootHints) {
return new BrowserRoot("",null);
}
#Override
public void onLoadChildren(#NonNull String parentId, #NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
result.sendResult(null);
}
This is my activity class:
ActivityPlayerFullViewBinding activityPlayerFullViewBinding;
private MediaBrowserCompat mediaBrowserCompat;
private MediaBrowserCompat.ConnectionCallback connectionCallback = new MediaBrowserCompat.ConnectionCallback(){
#Override
public void onConnected() {
super.onConnected();
MediaSessionCompat.Token sessionToken = mediaBrowserCompat.getSessionToken();
if (sessionToken!=null){
try {
MediaControllerCompat mediaControllerCompat = new
MediaControllerCompat(PlayerFullViewActivity.this, sessionToken);
MediaControllerCompat.setMediaController(PlayerFullViewActivity.this,mediaControllerCompat);
playPauseBuild();
Log.d("onConnected","ConnectionSuccess");
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
#Override
public void onConnectionFailed() {
super.onConnectionFailed();
Log.d("onConnectionFaild","ConnectionFailed");
}
};
MediaControllerCompat.Callback controllerCallback =
new MediaControllerCompat.Callback() {
#Override
public void onMetadataChanged(MediaMetadataCompat metadata) {}
#Override
public void onPlaybackStateChanged(PlaybackStateCompat state) {}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityPlayerFullViewBinding = DataBindingUtil.setContentView(this,R.layout.activity_player_full_view);
ComponentName componentName = new ComponentName(this,MusicService.class);
mediaBrowserCompat = new MediaBrowserCompat(this,componentName,connectionCallback,null);
}
private void playPauseBuild() {
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(PlayerFullViewActivity.this);
activityPlayerFullViewBinding.playPauseBtn
.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int state = mediaController.getPlaybackState().getState();
if (state== PlaybackStateCompat.STATE_PAUSED||state==PlaybackStateCompat.STATE_STOPPED||
state==PlaybackStateCompat.STATE_NONE){
mediaController.getTransportControls().playFromUri(
Uri.parse("https://www.mboxdrive.com/Eminem-Sing-For-The-Moment9jamo.com_.mp3"),null);
activityPlayerFullViewBinding.playPauseBtn.setText("Pause");
}else if (state == PlaybackStateCompat.STATE_PLAYING ||
state == PlaybackStateCompat.STATE_BUFFERING ||
state == PlaybackStateCompat.STATE_CONNECTING){
mediaController.getTransportControls().pause();
activityPlayerFullViewBinding.playPauseBtn.setText("Play");
}
}
});
mediaController.registerCallback(controllerCallback);
}
#Override
protected void onStart() {
super.onStart();
mediaBrowserCompat.connect();
}
#Override
public void onResume() {
super.onResume();
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
#Override
protected void onStop() {
super.onStop();
Log.i("onStop","onStop");
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(this);
if (mediaController != null) {
mediaController.unregisterCallback(controllerCallback);
}
mediaBrowserCompat.disconnect();
}
After wasting 2 sleepless nights. I found a workaround. I don't know whether it's a correct way to handle this. But if you have ever faced this problem. You can try it:
#Override
protected void onStart() {
super.onStart();
if (!mediaBrowserCompat.isConnected())
mediaBrowserCompat.connect();
}
#Override
protected void onStop() {
super.onStop();
Log.i("onStop","onStop");
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(this);
if (mediaController != null) {
mediaController.unregisterCallback(controllerCallback);
}
// mediaBrowserCompat.disconnect();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaBrowserCompat.disconnect();
}

Cannot stop timer in Android? How to solve it?

I am writing a class to control start and stop timer in Android. The controller is an Activity that will send start or stop value. In the TimerControl class, I write two functions that use to start and stop the timer. I can start the timer, but I cannot stop it. How can I solve it? This is my code
//In Controller class
//===========Start========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "start");
getApplicationContext().startActivity(smsTimer);
//===========Stop========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "stop");
getApplicationContext().startActivity(smsTimer);
This is my code of TimerControl
public class TimmerControl extends Activity {
private CountDownTimer timer_SMS;
private String TAG="TimmerControl";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent != null &&intent.getExtras() != null) {
Bundle bundle = intent.getExtras();
if (!bundle.getString("input_timer").equals(null)) {
String input_timer = bundle.getString("input_timer");
if(input_timer.equals("start")) {// start
startSMSTimer();
}
else if(input_timer.equals("stop")) {// stop
stopSMSTimer();
}
else{}
}
}
finish();
}
public void startSMSTimer(){
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
timer_SMS = new CountDownTimer(100000, 20000) {
#Override
public void onTick(long millisUntilFinished) {
long timOver = 100000 - millisUntilFinished;
Log.d(TAG, String.valueOf(timOver));
}
#Override
public void onFinish() { }
};
timer_SMS.start();
}
public void stopSMSTimer(){
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
}
}
You need to send "stop" while sending intent for stop as follows :
//In Controller class
//===========Start========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "start"); // start
getApplicationContext().startActivity(smsTimer);
//===========Stop========
Intent smsTimer = new Intent(getApplicationContext(), TimmerControl.class);
smsTimer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
smsTimer.putExtra("input_timer", "stop"); // stop
getApplicationContext().startActivity(smsTimer);
public class TimmerControl extends Service {
CountDownTimer timer_SMS;
private BroadcastReceiver mReceiver;
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("start");
intentFilter.addAction("stop");
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//extract our message from intent
if (intent.getAction().equals("start")) {
startSMSTimer();
}
if (intent.getAction().equals("stop")) {
stopSMSTimer();
}
}
};
this.registerReceiver(mReceiver, intentFilter);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
this.unregisterReceiver(this.mReceiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void startSMSTimer() {
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
}
timer_SMS = new CountDownTimer(100000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
long timOver = 100000 - millisUntilFinished;
Log.e("Time: ", ""+timOver);
}
#Override
public void onFinish() {
Log.e("finished: ","");
}
};
timer_SMS.start();
}
public void stopSMSTimer() {
if (timer_SMS != null) {
timer_SMS.cancel();
timer_SMS = null;
Log.e("Stop: ","");
}
stopSelf();
}
}
SMSControllerActivity.java
public class SMSControllerActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smscontroller);
findViewById(R.id.btn_start).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!isServiceRunning(TimmerControl.class))
startService(new Intent(SMSControllerActivity.this, TimmerControl.class));
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
sendBroadcast(new Intent("start"));
}
}, 500);
}
});
findViewById(R.id.btn_stop).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
sendBroadcast(new Intent("stop"));
}
});
;
}
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
activity_smscontroller.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/btn_start"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Start" />
<Button
android:id="#+id/btn_stop"
android:layout_width="match_parent"
android:layout_height="50dp"
android:text="Stop" />
</LinearLayout>

There is a delay when showing webview which loading url is completed at invisible

First, WebView starting load a url at invisible(setVisibility(View.INVISIBLE))on service. and wait until the url loading is done.
finally, set the visibility is show(setVisibility(View.VISIBLE)), the WebView show empty screen(white screen) about 0.5 second. then show rendered web page.
I want to show rendered web page immediately on WebView without empty screen.
like this
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, ServiceViewManager.class));
setUI();
}
private void setUI()
{
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(createLoadUrlInvisible());
layout.addView(createShowWebView());
this.setContentView(layout);
}
private Button createLoadUrlInvisible()
{
Button button = new Button(this);
button.setText("LoadUrlInvisible (Click first)");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WebPageServiceView.instance().loadUrlInvisible();
}
});
return button;
}
private Button createShowWebView()
{
Button button = new Button(this);
button.setText("ShowWebView (Click second)");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WebPageServiceView.instance().setVisibility(View.VISIBLE);
}
});
return button;
}
}
public class ServiceViewManager extends Service {
private static ServiceViewManager inst = null;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public static ServiceViewManager Instance()
{
return inst;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
inst = this;
return START_NOT_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
inst = null;
super.onDestroy();
}
public void add(final View view, final WindowManager.LayoutParams params)
{
((WindowManager)getSystemService(Service.WINDOW_SERVICE)).addView(view, params);
}
}
public class WebPageServiceView extends FrameLayout {
private static WebPageServiceView inst = null;
public WebPageServiceView() {
super(ServiceViewManager.Instance());
}
public static WebPageServiceView instance() {
if(inst == null)
inst = new WebPageServiceView();
return inst;
}
private void addViewToService()
{
WindowManager.LayoutParams serviceParams = new WindowManager.LayoutParams();
serviceParams.x = 0;
serviceParams.y = 0;
serviceParams.type = WindowManager.LayoutParams.TYPE_PHONE;
serviceParams.flags = WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
serviceParams.format = PixelFormat.TRANSPARENT;
ServiceViewManager.Instance().add(this, serviceParams);
}
private void addWebViewAndLoadUrl()
{
WebView webView = new WebView(getContext());
webView.loadUrl("http://naver.com");
webView.setWebViewClient(new WebViewClient());
this.addView(webView);
}
public void loadUrlInvisible() {
addViewToService();
addWebViewAndLoadUrl();
setVisibility(INVISIBLE);
}
}

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.

Android Service stops automatically without calling stopService()

I have made an android Service to play music, when i close my application then it keeps on playing song for few minutes and then automatically stops without even calling destroy method. I am not able to understand why is it happening.
Below is the code of my Service class.
public class MusicService extends Service implements MediaPlayer.OnSeekCompleteListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener {
private MediaPlayer player;
private int songPosition;
private IBinder iBinder = new LocalBinder();
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private boolean isPaused = false;
private ArrayList<Song> songsList;
private boolean isRepeat = false;
private boolean isShuffle = false;
private Intent broadcastIntent;
public static final String BROADCAST_INTENT = "music.akumar.com.musicplayer.seekbarintent";
private Handler handler = new Handler();
public class LocalBinder extends Binder {
public MusicService getService() {
return MusicService.this;
}
}
#Override
public void onCreate() {
broadcastIntent = new Intent(BROADCAST_INTENT);
player = new MediaPlayer();
player.setOnBufferingUpdateListener(this);
player.setOnCompletionListener(this);
player.setOnSeekCompleteListener(this);
player.setOnPreparedListener(this);
player.setOnInfoListener(this);
player.setOnErrorListener(this);
player.setLooping(true);
player.reset();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
telephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch(state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (player.isPlaying()) {
pauseMedia();
isPaused = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
if (player != null) {
if (isPaused) {
playMedia();
isPaused = false;
}
}
break;
}
}
};
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
return START_STICKY;
}
public void playMedia() {
if (player != null && !player.isPlaying()) {
player.start();
}
}
public void pauseMedia() {
if (player != null && player.isPlaying()) {
player.pause();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (player.isPlaying()) {
player.stop();
}
player.release();
}
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
public void playSong(Song song) {
player.reset();
try {
player.setDataSource(getApplicationContext(), Uri.parse(song.getPath()));
player.prepare();
playMedia();
setHandler();
} catch (IOException e) {
e.printStackTrace();
}
}
private void setHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 500);
}
private Runnable sendUpdatesToUI = new Runnable() {
#Override
public void run() {
logMediaPosition();
handler.postDelayed(this, 500);
}
};
private void logMediaPosition() {
}
public void playNext() {
}
public void playPrev() {
}
public boolean isPlaying() {
return player.isPlaying();
}
public int getSongPosition() {
return songPosition;
}
public void setSongPosition(int songPosition) {
this.songPosition = songPosition;
}
public ArrayList<Song> getSongsList() {
return songsList;
}
public void setSongsList(ArrayList<Song> songsList) {
this.songsList = songsList;
}
public boolean isRepeat() {
return isRepeat;
}
public void setRepeat(boolean isRepeat) {
this.isRepeat = isRepeat;
}
public boolean isShuffle() {
return isShuffle;
}
public void setShuffle(boolean isShuffle) {
this.isShuffle = isShuffle;
}
public void addSongToList(Song song) {
songsList.add(song);
}
public Song getCurrentSong() {
return songsList.get(songPosition);
}
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
}
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i2) {
return false;
}
#Override
public boolean onInfo(MediaPlayer mediaPlayer, int i, int i2) {
return false;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
#Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
}
}
And below the code of my activity class.
public class MusicPlayer extends FragmentActivity implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
private boolean mBound = false;
private MusicService musicService;
private ArrayList<Song> songsList = new ArrayList<Song>();
private boolean isRepeat = false;
private boolean isShuffle = false;
private int position;
private ImageButton btnPlay;
private ImageButton btnPlayNext;
private ImageButton btnPlayPrev;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private ImageButton btnFavorite;
private TextView currentSongView;
private SeekBar seekBar;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private ViewPager viewPager;
private BroadcastReceiver broadcastReceiver;
private boolean mBroadcastIsRegistered;
ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
mBound = true;
MusicService.LocalBinder localBinder = (MusicService.LocalBinder)iBinder;
musicService = localBinder.getService();
musicService.setSongsList(songsList);
musicService.setSongPosition(0);
musicService.playSong(0);
btnPlay.setImageResource(R.drawable.btn_pause);
registerReceiver(broadcastReceiver, new IntentFilter(MusicService.BROADCAST_INTENT));
mBroadcastIsRegistered = true;
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music_player);
songsList = prepareListOfSongsAndAlbumMap();
currentSongView = (TextView)findViewById(R.id.currentSongView);
btnPlay = (ImageButton)findViewById(R.id.btnPlay);
btnPlayNext = (ImageButton)findViewById(R.id.btnNext);
btnPlayPrev = (ImageButton)findViewById(R.id.btnPrevious);
btnRepeat = (ImageButton)findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton)findViewById(R.id.btnShuffle);
btnFavorite = (ImageButton)findViewById(R.id.btnFavourite);
seekBar = (SeekBar)findViewById(R.id.SeekBar01);
songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);
viewPager = (ViewPager)findViewById(R.id.viewPagerMusicPlayer);
position = 0;
btnPlay.setOnClickListener(this);
btnPlayNext.setOnClickListener(this);
btnPlayPrev.setOnClickListener(this);
btnRepeat.setOnClickListener(this);
btnShuffle.setOnClickListener(this);
btnFavorite.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
DataTransferBetweenActivity data = new DataTransferBetweenActivity(songsList, position);
MusicPlayerTabAdapter musicPlayerTabAdapter = new MusicPlayerTabAdapter(getSupportFragmentManager(), data);
viewPager.setAdapter(musicPlayerTabAdapter);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateUI(intent);
}
};
}
private void updateUI(Intent serviceIntent) {
}
private ArrayList<Song> prepareListOfSongsAndAlbumMap() {
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String[] projection;
projection = null;
String sortOrder = null;
String selectionMimeType = MediaStore.Audio.Media.IS_MUSIC + " !=0";
Cursor musicCursor = getContentResolver().query(musicUri, projection, selectionMimeType, null, sortOrder);
int count = musicCursor.getCount();
if (musicCursor.moveToFirst()) {
do {
String path = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String title = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String album = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String artist = musicCursor.getString(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
int artistId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
int albumId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
int trackId = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.TRACK));
long duration = musicCursor.getInt(musicCursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
Uri sArtworkUri = Uri
.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
Song song = new Song(path, title, album, artist, albumId, trackId, duration, albumArtUri.toString(), artistId);
songsList.add(song);
} while (musicCursor.moveToNext());
Collections.sort(songsList, new Comparator<Song>() {
#Override
public int compare(Song song, Song song2) {
return song.getTitle().toUpperCase().compareTo(song2.getTitle().toUpperCase());
}
});
musicCursor.close();
}
return songsList;
}
#Override
protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, MusicService.class);
startService(serviceIntent);
bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBound) {
unbindService(serviceConnection);
mBound = false;
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnPlay:
break;
case R.id.btnNext:
break;
case R.id.btnPrevious:
break;
case R.id.btnRepeat:
break;
case R.id.btnShuffle:
break;
}
}
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
protected void onPause() {
if (mBroadcastIsRegistered) {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
}
super.onPause();
}
#Override
protected void onResume() {
if (!mBroadcastIsRegistered) {
registerReceiver(broadcastReceiver, new IntentFilter(MusicService.BROADCAST_INTENT));
mBroadcastIsRegistered = true;
}
super.onResume();
}
public void playSong(int position) {
musicService.playSong(position);
musicService.setSongPosition(position);
}
}
I am starting my service with startService() method and i am not calling stopService() or stopSelf() anywhere, but i am not able to figure out why it stops playing after sometime.
I think you should call startForeground() from your service.
Here is a sample project of a music player. I might be helpful
FakePlayer

Categories

Resources