Problem: When I use the home button to close the app the music continues playing. So I manually close the app by killing the activity, the music stops... for a few seconds and then starts again (and this time a restart is in order to turn it off).
MusicService.class:
package com.MyApp.App;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MusicService extends Service implements
MediaPlayer.OnErrorListener {
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
private int length = 0;
public MusicService() {
}
public class ServiceBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
#Override
public void onCreate() {
super.onCreate();
mPlayer = MediaPlayer.create(this, R.raw.test_music);
mPlayer.setOnErrorListener(this);
if (mPlayer != null) {
mPlayer.setLooping(true);
mPlayer.setVolume(100, 100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
onError(mPlayer, what, extra);
return true;
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mPlayer.start();
return START_STICKY;
}
public void pauseMusic() {
if (mPlayer.isPlaying()) {
mPlayer.pause();
length = mPlayer.getCurrentPosition();
}
}
public void resumeMusic() {
if (mPlayer.isPlaying() == false) {
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic() {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if (mPlayer != null) {
try {
mPlayer.stop();
mPlayer.release();
} finally {
mPlayer = null;
}
}
return false;
}
}
MainPage.class:
package com.MyApp.App;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
public class MainPage extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
#Override
protected void onDestroy() {
super.onDestroy();
mServ.stopMusic();
}
#Override
protected void onPause() {
super.onPause();
mServ.pauseMusic();
}
#Override
protected void onStop() {
super.onStop();
mServ.stopMusic();
}
private boolean mIsBound = false;
private MusicService mServ;
private ServiceConnection Scon = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
mServ = ((MusicService.ServiceBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName name) {
mServ = null;
}
};
void doBindService() {
bindService(new Intent(this, MusicService.class), Scon,
Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
unbindService(Scon);
mIsBound = false;
}
}
}
(NOTE: I have taken excerpts from my app, so I may have forgotten imports in this code, but all imports are correctly included in the app.)
Fixed:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
doBindService();
Intent music = new Intent();
music.setClass(this, MusicService.class);
startService(music);
}
and
#Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
please red : onCreate, OnPause , OnResume
Related
I have an activity named Player Activity in which I am streaming music with the help of MediaPlayer API. Whenever my activity is created a notification is displayed which has some basic control of the music player.
So when I tap on my notification it jumps back to the Player Activity, but the state of the activity is lost.
Before tapping on notification :
After tapping on notification :
Here is the code of my notification's Pending Intent
Intent notifyIntent = new Intent(context, PlayerActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
notifyIntent.setAction("android.intent.action.MAIN");
notifyIntent.addCategory("android.intent.category.LAUNCHER");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Here is the code for PlayerActivity.java :
package com.example.user.musicplayer;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import java.util.concurrent.TimeUnit;
import de.hdodenhof.circleimageview.CircleImageView;
public class PlayerActivity extends AppCompatActivity implements MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnCompletionListener{
private static Button btn_play_pause;
private Button btnToggleRepeat;
private Button btnStop;
private SeekBar seekBar;
private TextView textView;
public static MediaPlayer mediaPlayer;
private int mediaFileLength;
private int realtimeLength;
private String musicUrl;
private String imageUrl;
final Handler handler = new Handler();
private boolean isRepeat;
private CircleImageView musicImage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Log.d("TAG", "onCreate");
NotificationGenerator.customBigNotification(getApplicationContext());
musicUrl = getIntent().getStringExtra("musicUrl");
imageUrl = getIntent().getStringExtra("imageUrl");
seekBar = (SeekBar)findViewById(R.id.seekbar);
seekBar.setMax(99); // 100% (0~99)
seekBar.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaPlayer.isPlaying())
{
SeekBar seekBar = (SeekBar)v;
int playPosition = (mediaFileLength/100)*seekBar.getProgress();
mediaPlayer.seekTo(playPosition);
}
return false;
}
});
textView = (TextView)findViewById(R.id.txtTime);
btnToggleRepeat = findViewById(R.id.btnRepeat);
btnStop = findViewById(R.id.btnStop);
musicImage = findViewById(R.id.musicImgView);
Picasso.get().load(imageUrl).placeholder(R.drawable.music).error(R.drawable.music).into(musicImage);
btn_play_pause = (Button) findViewById(R.id.btnTogglePlay);
btn_play_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final ProgressDialog mDialog = new ProgressDialog(PlayerActivity.this);
AsyncTask<String,String,String> mp3Play = new AsyncTask<String, String, String>() {
#Override
protected void onPreExecute() {
mDialog.setMessage("Please wait");
mDialog.show();
}
#Override
protected String doInBackground(String... params) {
try{
mediaPlayer.setDataSource(params[0]);
mediaPlayer.prepare();
}
catch (Exception ex)
{
}
return "";
}
#Override
protected void onPostExecute(String s) {
mediaFileLength = mediaPlayer.getDuration();
realtimeLength = mediaFileLength;
if(!mediaPlayer.isPlaying())
{
playMusic();
}
else
{
pauseMusic();
}
updateSeekBar();
mDialog.dismiss();
}
};
mp3Play.execute(musicUrl); // direct link mp3 file
}
});
btnToggleRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(isRepeat){
isRepeat = false;
mediaPlayer.setLooping(false);
btnToggleRepeat.setText("Repeat");
}
else{
isRepeat = true;
mediaPlayer.setLooping(true);
btnToggleRepeat.setText("Single");
}
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
mediaPlayer.stop();
}
catch (Exception e){
Toast.makeText(PlayerActivity.this, "Opps! sorry something bad happened", Toast.LENGTH_SHORT).show();
}
}
});
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
public void pauseMusic() {
mediaPlayer.pause();
btn_play_pause.setText("Play");
}
public void playMusic() {
mediaPlayer.start();
btn_play_pause.setText("Pause");
}
private void updateSeekBar() {
seekBar.setProgress((int)(((float)mediaPlayer.getCurrentPosition() / mediaFileLength)*100));
if(mediaPlayer.isPlaying())
{
Runnable updater = new Runnable() {
#Override
public void run() {
updateSeekBar();
realtimeLength-=1000; // declare 1 second
textView.setText(String.format("%d:%d",TimeUnit.MILLISECONDS.toMinutes(realtimeLength),
TimeUnit.MILLISECONDS.toSeconds(realtimeLength) -
TimeUnit.MILLISECONDS.toSeconds(TimeUnit.MILLISECONDS.toMinutes(realtimeLength))));
}
};
handler.postDelayed(updater,1000); // 1 second
}
}
#Override
protected void onResume() {
super.onResume();
Log.d("TAG", "onResume");
}
#Override
protected void onStart() {
super.onStart();
Log.d("TAG", "onStart");
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
if(!mediaPlayer.isLooping())
btn_play_pause.setText("Play");
}
#Override
protected void onStop() {
super.onStop();
}
#Override
protected void onPause() {
super.onPause();
}
public static class DownloadCancelReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("notificationPlayer","Received Cancelled Event");
}
}
}
Thanks in advance. Pardon me if the explanation is not clear, because if i might have right words to explain it, I would have googled it.
Add this to your PlayerActivity activity in manifest :
android:launchMode="singleTask"
And use these flags in the intent for pendingintent :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
Youtube API crashes when I am in onpause state.
When I am playing Youtube video onclick it is working fine but when I am minimizing my app in onpause state it crashes. So give me some suggestions. I never used Youtube API before so I have no idea about it. Please review my code whether it is good. if not, then please provide good
suggestion too. Thanks in advance.
package com.app.embedyoutube;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
String key="AIzaSyASLaX32-EG2Rx0EWZFPbwhuBDgsBgC6e0";
YouTubePlayer youTubePlayer1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final YouTubePlayerView youtubePlayerView = findViewById(R.id.youtubePlayerView);
youtubePlayerView.initialize(key,this);
findViewById(R.id.b1).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play("ScQrLSBAuQk");
}
});
findViewById(R.id.b2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
play("Ow9-fzf4Qbk");
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer1=youTubePlayer;
youTubePlayer1.cueVideo("Ow9-fzf4Qbk");
youTubePlayer1.setPlayerStateChangeListener(new YouTubePlayer.PlayerStateChangeListener() {
#Override public void onAdStarted() { }
#Override public void onError(YouTubePlayer.ErrorReason arg0) { }
#Override public void onLoaded(String arg0) { }
#Override public void onLoading() { }
#Override public void onVideoEnded() { }
#Override public void onVideoStarted() { }
});
youTubePlayer1.setPlaybackEventListener(new YouTubePlayer.PlaybackEventListener() {
#Override public void onBuffering(boolean arg0) { }
#Override public void onPaused() { }
#Override public void onPlaying() { }
#Override public void onSeekTo(int arg0) { }
#Override public void onStopped() { }
});
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
public void play(String url)
{
if( youTubePlayer1 != null ) {
youTubePlayer1.cueVideo(url);
}
}
#Override
public void onPause()
{
super.onPause();
if (youTubePlayer1 != null) {
if(youTubePlayer1.isPlaying()) {
// currentPlayerTime = youTubePlayer1.getCurrentTimeMillis();
youTubePlayer1.pause();
}
}
}
}
#Override
public void onPause()
{
super.onPause();
if (youTubePlayer1 != null) {
youTubePlayer1.release();
}
}
and you can save your current video time in savedInstanceState
but for better solution i will recommend you to initialize your player in onResume and release it in onStop like this.
#Override
protected void onResume() {
super.onResume();
playerView.initialize(KEY, this);
}
#Override
public void onStop() {
if (player != null) {
player.release();
}
player = null;
super.onStop();
}
i am developing one app where just show clouds walking through the screen using surface view everything gone good until push the Button "HOME BUTTON" so when i returned to my app just showing screen in black, the rest of the app works fine just is when you push the "Home Button"
Where is my Code for the surfaceView
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class mysurfaceview extends SurfaceView implements SurfaceHolder.Callback {
private mysurfaceviewThread bbThread = null;
private int xPosition = (getHeight()/2);
private int yPosition = (getHeight()/2);
private int posicion2 = (getWidth()/2)-40;
private int posicion3 = (getWidth()/4);
private int xDirection = 1;
public mysurfaceview(Context ctx,AttributeSet attrs){
super(ctx, attrs);
getHolder().addCallback(this);
}
public void doDraw(Canvas c){
Paint paint = new Paint();
paint.setColor(Color.WHITE);
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.myimage);
c.drawColor(Color.WHITE);
c.drawBitmap(icon, xPosition, yPosition, new Paint());
c.drawBitmap(icon,posicion2,(getHeight()/2),new Paint());
c.drawBitmap(icon,posicion3,(getHeight()/2)+40,new Paint());
}
public void surfaceCreated(SurfaceHolder holder){
if (bbThread!=null) return;
bbThread = new mysurfaceviewThread(getHolder());
bbThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height){
}
public void surfaceDestroyed (SurfaceHolder holder){
bbThread.detener();
}
public class mysurfaceviewThread extends Thread{
private boolean corriendo,pausa;
private SurfaceHolder surfaceHolder;
public mysurfaceviewThread(SurfaceHolder surfaceHolder){
this.surfaceHolder = surfaceHolder;
}
public synchronized void pausar() {
pausa = true;
}
public synchronized void reanudar() {
pausa = false;
notify();
}
public void detener() {
corriendo = false;
if (pausa)
reanudar();
}
public void run(){
corriendo=true;
while(corriendo){
xPosition+=xDirection;
posicion2+=2;
posicion3+=1;
if(xPosition==getWidth()){
xPosition = -200; }
if(posicion2==getWidth()){
posicion2 = -200; }
if(posicion3==getWidth()){
posicion3 = -200; }
Canvas c = null;
try {
c = surfaceHolder.lockCanvas();
doDraw(c);
synchronized (surfaceHolder){
}
} finally {
if(c != null) surfaceHolder.unlockCanvasAndPost(c);}
synchronized (this) {
while (pausa) {
try {
wait();
} catch (Exception e) {
}
}
}
}
}
}
public mysurfaceviewThread getThread(){
return bbThread;
}
}
Here is the code for Activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.SurfaceView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class animadofondo2 extends Activity{
private mysurfaceview Clouds;
private mysurfaceview.mysurfaceviewThread CloudsThread;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sufeaviewfondo);
Clouds= (mysurfaceview ) findViewById(R.id.ViewsLaynubes);
}
#Override
protected void onPause() {
super.onPause();
Clouds.getThread().pausar();
Toast.makeText(this, "Pausa", Toast.LENGTH_SHORT).show();
}
#Override
protected void onRestart(){
super.onRestart();
Clouds.getThread().reanudar();
Toast.makeText(this, "Restart", Toast.LENGTH_SHORT).show();
}
#Override protected void onStart() {
super.onStart();
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
}
#Override protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
}
#Override protected void onStop() {
super.onStop();
Nubecitas.getThread().pausar();
Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
}
#Override protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed(){
Lamar(null);
finish();
}
public void Lamar (View view){
Intent i = new Intent(this, main.class);
startActivity(i);
}
}
Here is the XML for the layout
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linear1"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.app.example.proyectsurface.mysurfaceview
android:id="#+id/ViewsLaynubes"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
The "stop" and "play" work fine, but "pause" works like "stop". When I press pause, the audiofile stops playing and when I press play, it starts from the beginning.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class HelloMoonFragment extends Fragment
{
private AudioPlayer mPlayer = new AudioPlayer();
private Button mPlayButton;
private Button mStopButton;
private Button mPauseButton;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_hello_moon, parent, false);
mPlayButton = (Button)v.findViewById(R.id.hellomoon_playButton);
mPlayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
mPlayer.play(getActivity());
}
});
mPauseButton = (Button) v.findViewById(R.id.hellomoon_pauseButton);
mPauseButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.pause();
}
});
mStopButton = (Button)v.findViewById(R.id.hellomoon_stopButton);
mStopButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
mPlayer.stop();
}
});
return v;
}
#Override
public void onDestroy()
{
super.onDestroy();
mPlayer.stop();
}
}
package com.example.hellomoon;
import android.content.Context;
import android.media.MediaPlayer;
public class AudioPlayer {
private MediaPlayer mPlayer;
public void stop()
{
if(mPlayer != null)
{
mPlayer.release();
mPlayer = null;
}
}
public void pause()
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
}
}
public void play(Context c)
{
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
stop();
}
});
mPlayer.start();
}
}
it starts from the beginning because here:
public void play(Context c) {
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
you are releasing the old one a create it again
Try remembering the the player is paused:
public class AudioPlayer {
boolean isPaused = false;
public void pause() {
if(mPlayer.isPlaying()) {
mPlayer.pause();
isPaused = true;
}
}
public void play(Context c) {
if (isPaused && mPlayer != null) {
mPlayer.start();
isPaused = false
return;
}
stop();
mPlayer = MediaPlayer.create(c, R.raw.one_small_step);
i have an android service that plays music.i start in my main activity with this code:
Intent service = new Intent(MainMenu.this, musicservice.class);
MainMenu.this.startService(service);
and this is my service:
public class musicservice extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
MediaPlayer mp;
mp = MediaPlayer.create(musicservice.this, R.raw.music);
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
it stsrts work fine, but when i start another activity, my music goes off and seems my service destroys!! but dont want this, i want my service only stops when my application ends. music plays only when user works with app. even when app in in the background i want my music dont play! how i can implement this?
If you want your application to play music while your activity is on, try bind it.
it should look something like this:
Service:
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import com.example.playmusic.R;
public class PlayMusicService extends Service {
private final IBinder binder = new LocalBinder();
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class LocalBinder extends Binder {
public PlayMusicService getService() {
return PlayMusicService.this;
}
}
public void play() {
player = MediaPlayer.create(this, R.raw.music);
player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
player.start();
}
public void pause() {
player.pause();
}
}
Activity:
package com.example.playmusic;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import com.example.service.PlayMusicService;
import com.example.service.PlayMusicService.LocalBinder;
public class MainActivity extends Activity {
private PlayMusicService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onPause() {
super.onPause();
service.pause();
}
#Override
protected void onStart() {
super.onStart();
if (service != null) {
service.play();
} else {
bindService();
}
}
private void bindService() {
bindService(new Intent(this, PlayMusicService.class), new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
LocalBinder localBinder = (LocalBinder) binder;
service = localBinder.getService();
service.play();
}
}, Context.BIND_AUTO_CREATE);
}
}
Service destroy when your activity destroy when you start service from activity.
Use AlarmManager to schedule the service repeatedly.