foreground Service recursively calls new activity and cant be stopped - android

I am working on Integrating a Quickblox based video chat into my app.
Here i am running a listener in foreground service which listens to the video call initiated by opponent. here in switch statement, at call accept state i am calling a new activity which is nothing but a dialler screen with accept and disconnect button. accept button connects the call but disconnect cuts the call and closes the activity, but again the same activity (dialler screen) opens repeatedly after multiple times, My question is how to make service to call once and ignore the rest calls if its disconnected. (Am sending reject signal to opponent thus call drops from opponent but here service calls activity repeatedly though call is dropped from opponent)
Here is the code
VchatListener service with OnQBVideoChatListener with switch statement has a accept call state which calls new activity
public class VChatListener extends Service {
private VideoChatConfig videoChatConfig;
private CallState state;
QBUser a=DataHolder.getInstance().getCurrentQbUser();
/* private AlertDialog alertDialog;*/
private static final int notif_id=1;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//startForeground(FOREGROUND_ID, notification);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Log.i("******Service Call user Here","now*******");
if(a!=null){
Log.i("******Service testing",""+a);
}else{
Log.i("******Service testing user","nothing");
}
Log.i("***Still","running****");
QBVideoChatController.getInstance().setQBVideoChatListener(a, qbVideoChatListener);
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
};
};
new Thread(runnable).start();
return Service.START_REDELIVER_INTENT;
private OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {
#Override
public void onVideoChatStateChange(CallState state, VideoChatConfig receivedVideoChatConfig) {
Debugger.logConnection("onVideoChatStateChange: " + state);
videoChatConfig = receivedVideoChatConfig;
/*if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}*/
Log.i("service state",""+state.toString());
switch (state) {
case ACCEPT:
Intent intent = new Intent(VChatListener.this, CallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(VideoChatConfig.class.getCanonicalName(), videoChatConfig);
startActivity(intent);
// showCallDialog();
Log.i("service state 1",""+state.toString());
break;
case ON_ACCEPT_BY_USER:
Log.i("service state 2",""+state.toString());
/* QBVideoChatController.getInstance().onAcceptFriendCall(videoChatConfig, null);*/
//startVideoChatActivity();
break;
case ON_REJECTED_BY_USER:
Log.i("service state 3",""+state.toString());
/*Toast.makeText(VChatListener.this, "Rejected by user", Toast.LENGTH_SHORT).show();*/
break;
case ON_DID_NOT_ANSWERED:
Log.i("service state 4",""+state.toString());
/* Toast.makeText(VChatListener.this, "User did not answer", Toast.LENGTH_SHORT).show();*/
break;
case ON_CANCELED_CALL:
videoChatConfig = null;
Log.i("service state 5","nothing");
/*if (alertDialog != null && alertDialog.isShowing()){
alertDialog.dismiss();
}
autoCancelHandler.removeCallbacks(autoCancelTask);*/
break;
}
}
};
public void onDestroyed(){
super.onDestroy();
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
/* PendingIntent contentIntent = PendingIntent.getActivity(this,0, new Intent(this,Appointment.class), 0);*/
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.getNotification();
}
}
Here is the activity which will be called by service the end button associated with function end, disconnects the call.
public class CallActivity extends Activity {
private ProgressDialog progressDialog;
private VideoChatConfig videoChatConfig;
private VChatListener vChatListener;
QBUser qbuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageButton b1 = (ImageButton) findViewById(R.id.button1);
ImageButton b2 = (ImageButton) findViewById(R.id.button2);
playRingtone();
/*while(!b1.isPressed() || !b2.isPressed()){
playRingtone();
}*/
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO add stopCalling here, send Cancel message if
// need
// XMPPSender.sendCancelCallMsg(videoChatConfig);
// QBVideoChatController.getInstance().stopCalling();
}
});
qbuser = DataHolder.getInstance().getCurrentQbUser();
videoChatConfig = getIntent().getParcelableExtra(
VideoChatConfig.class.getCanonicalName());
;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAcceptCallClick();
mMediaPlayer.stop();
}
private void onAcceptCallClick() {
//mMediaPlayer.stop();
QBVideoChatController.getInstance().acceptCallByFriend(
videoChatConfig, null);
startVideoChatActivity();
}
private void startVideoChatActivity() {
if (videoChatConfig.getCallType() == CallType.VIDEO_AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityVideoChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
} else if(videoChatConfig.getCallType() == CallType.AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityAudioChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
}
}
});
}
public void end(View view)
{
mMediaPlayer.stop();
QBVideoChatController.getInstance().finishVideoChat(videoChatConfig);
XMPPSender.sendCancelCallMsg(videoChatConfig);
QBVideoChatController.getInstance().stopCalling();
super.onDestroy();
finish();
}
public void playRingtone() {
try {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch(Exception e) {
e.printStackTrace();
}
/* try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
to limit the service to call activity once i included in manifest launch mode = "singleTask" which launches activity once, but when activity get closed by disconnect it is called again and doesnt stop.
<activity
android:name="com.yugays.videochatsample.ui.CallActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="landscape" >
</activity>
How to stop activity getting created after call is disconnected and activity is closed.

Related

Why would a service's onUnbind method not execute on a call to unbindService from the only connected client in Android?

I am working on an application which will poll and record data from a remote device even when the application that launched it isn't in the foreground. In order to do this I created a service which is launched by my main app once the user has adjusted a few settings. Currently I am able to start the service from my app and pass configuration data to it through the intent. It is my understanding that onUnbind only runs when all clients have disconnected. I am only connecting a single client to the service so I would expect this method to fire as soon as I command my app to unbind.
Problem
After originally binding to the service, if I later try to unbind the onUnbind function doesn't execute. Similarly, if I try to bind to it again neither onBind nor onRebind execute. I've tried printing to the log and toaster notifications to indicate the respective functions are being called. I get no feedback in either case. This has me quite convinced there is something wrong with my interface to the service.
I'm sure these issues are related but I'm new to Android Services and have been unable to locate a section of the docs which explains the problem. Any direction as to what I'm doing wrong would be very helpful. Code is included below, thanks!
Activity Code:
public class MainActivity extends AppCompatActivity {
String TAG = "MainActivity";
Boolean isBound = false;
private static final int PICKFILE_RESULT_CODE = 1;
Button rec_button;
TextView dmr_fname;
TextView dmr_status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Remove this button...", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
rec_button = findViewById(R.id.rec_button);
rec_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Recorder started (not really)", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
doUnBind();
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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) {
// Open settings activity
Intent myIntent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(myIntent);
return true;
}
else if (id == R.id.action_dmr) {
// TODO: Open a file dialog so user can select DMR to parse
Intent fileintent = new Intent(Intent.ACTION_GET_CONTENT);
//fileintent.addCategory(Intent.CATEGORY_OPENABLE);
fileintent.setType("text/*");
try {
startActivityForResult(Intent.createChooser(fileintent, "Open CSV"), PICKFILE_RESULT_CODE);
} catch (ActivityNotFoundException e) {
Log.e("tag", "No activity can handle picking a file. Showing alternatives.");
}
return true;
}
else if (id == R.id.action_quitservice) {
try {
doUnBind();
} catch (Exception e) {
Log.e(TAG,"Error encountered unbinding from DMR service: "+e);
}
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
dmr_fname = findViewById(R.id.DMR_filename);
dmr_status = findViewById(R.id.DMR_status);
switch (requestCode) {
case PICKFILE_RESULT_CODE:
if (resultCode == RESULT_OK) {
String FilePath = data.getData().getPath();
// TODO: Add a function here to try two different file paths (one for SD, one internal, and return the proper one
// For now, just assume it's internal downloads
Log.d(TAG,"Path Segments: "+data.getData().getPathSegments());
FilePath = Environment.getExternalStorageDirectory()+"/"+FilePath.split(":")[1];
dmr_fname.setText(FilePath);
dmr_status.setText("Parsing...");
List<DMR_Data_Item> DMR_List = parseDMR(FilePath);
dmr_status.setText("Setting up service...");
doBind(DMR_List);
if (dmrConnection != null) {
Log.v(TAG,"dmrConnection bound successfully!");
}
dmr_status.setText("Ready!");
}
break;
}
}
private ArrayList<DMR_Data_Item> parseDMR(String file) {
ArrayList<DMR_Data_Item> out_data = new ArrayList<>();
try {
Log.d(TAG,"Attempting to open "+file);
/* TODO: Someday request permissions so we can target SDK versions above 23, sample code is below:
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(thisActivity,
arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),1)
}*/
FileReader input = new FileReader(new File(file));
//InputStreamReader inputStreamReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(input);
String inString;
while ((inString = bufferedReader.readLine()) != null) {
// Split up the line and put it into the array if it matches the format
try {
Log.d(TAG, "Line from file: "+inString);
String[] row_data = inString.split(",");
out_data.add(new DMR_Data_Item(row_data[0], row_data[2], Integer.parseInt(row_data[4]),row_data[5].charAt(0),row_data[9]));
}
catch (Exception e) {
Log.e(TAG, "Exception parsing the DMR.. Perhaps the header was not removed? "+e);
}
}
input.close();
}
catch (Exception e) {
Log.e(TAG, "Exception encountered: " + e.toString());
}
return out_data;
}
private ServiceConnection dmrConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
Log.v(TAG,"Connected to DMRService");
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
Log.v(TAG, "Disconnected from DMRService");
}
};
void doBind(List<DMR_Data_Item> DMR_List) {
Intent intent = new Intent(getApplicationContext(),DMRService.class);
for (int i=0; i<DMR_List.size();i++) {
intent.putExtra("DMR_List["+i+"]",DMR_List.get(i));
}
bindService(intent,dmrConnection,BIND_AUTO_CREATE);
isBound = true;
}
void doUnBind() {
if (isBound) {
Log.v(TAG,"Requesting unbind from DMRService");
unbindService(dmrConnection);
isBound = false;
}
}
}
Service Code:
public class DMRService extends Service {
String TAG = "DMRService";
IBinder mBind;
boolean writing = false;
long write_timeout = -1;
Long oldest_arr[];
ArrayList<DMR_Data_Item> DMR_List = new ArrayList<>();
ArrayList<ArrayList<My_Measurement>> data_array = new ArrayList<>();
int idx = 0;
int MEMORY = 60; // Number of seconds of data to store before and after a trigger
public DMRService() {
Log.v(TAG,"DMR Service is running");
}
#Override
public int onStartCommand(Intent intent, int flags, int startID) {
Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show();
Log.v(TAG,"Running onStartCommand");
super.onStartCommand(intent, flags, startID);
return START_REDELIVER_INTENT;
}
#Override
public IBinder onBind(Intent intent) {
Toast.makeText(this,"Service binding", Toast.LENGTH_LONG).show();
Log.v(TAG,"Bind requested from intent "+intent);
// Get DMR list from intent
try {
Bundle bundle = intent.getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
DMR_List.add((DMR_Data_Item) bundle.get(key));
Log.v(TAG,"New DMR Item: "+DMR_List.get(DMR_List.size()-1).getName());
}
}
} catch (Exception e) {
Log.e(TAG,"Error encountered: "+e);
return null;
}
// Initialize oldest array
oldest_arr = new Long[DMR_List.size()];
Arrays.fill(oldest_arr,Long.valueOf(0));
// Make lists for storing data within the data array (one per DMR variable)
for (int i=0; i<DMR_List.size();i++) {
data_array.add(new ArrayList<My_Measurement>());
}
// Make a list to store the lists of data items
// Create a vehicle manager instance and CAN listener
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Log.v(TAG, "Finished binding! Data Array Size: "+data_array.size()+" Oldest Array Length: "+oldest_arr.length);
return mBind;
}
#Override
public void onCreate() {
Toast.makeText(this,"Service created", Toast.LENGTH_LONG).show();
super.onCreate();
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service destroyed", Toast.LENGTH_LONG).show();
super.onDestroy();
}
#Override
public void onRebind(Intent intent) {
Toast.makeText(this,"Service rebound", Toast.LENGTH_LONG).show();
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Toast.makeText(this,"Service unBinding", Toast.LENGTH_LONG).show();
Log.v(TAG,"Unbind requested by intent "+intent);
unbindService(mConnection);
// Reset all variables and lists
writing = false;
write_timeout = -1;
Long oldest_arr[];
DMR_List = new ArrayList<>();
data_array = new ArrayList<>();
idx = 0;
return false; // Not rebind-able
}
}

How can i bind my media player activity with existing media player service?

I know similar kind of question has been asked before, but none of them are helping me. I am building a music player in which I want to connect my Music through my music player like play, pause etc. Currently, media player service is connected with playlist activity but I have custom designed my media player and I am not able to connect it to the service class.
my MusicPlayer Activity is like this:
public class MusicPlayer extends AppCompatActivity implements PlaylistFragment.OnFragmentInteractionListener{
public static final String Broadcast_PLAY_NEW_AUDIO = "com.example.anuj.musicmetest.PlayNewAudio";
ImageView buttonPlayToggle;
MediaPlayer mediaPlayer;
MediaPlayerService player;
boolean serviceBound = false;
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Music Player");
buttonPlayToggle = (ImageView) findViewById(R.id.button_play_toggle);
buttonPlayToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
updatePlayToggle(true);
mediaPlayer.pause();
} else {
updatePlayToggle(false);
mediaPlayer.start();
}
}
});
if (!serviceBound) {
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
public void updatePlayToggle(boolean play) {
buttonPlayToggle.setImageResource(play ? R.drawable.ic_pause : R.drawable.ic_play);
}
My ServicecClass is like this:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
public static final String ACTION_PLAY = "com.example.anuj.musicmetest.ACTION_PLAY";
public static final String ACTION_PAUSE = "com.example.anuj.musicmetest.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "com.example.anuj.musicmetest.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "com.example.anuj.musicmetest.ACTION_NEXT";
public static final String ACTION_STOP = "com.example.anuj.musicmetest.ACTION_STOP";
private MediaPlayer mediaPlayer;
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
private static final int NOTIFICATION_ID = 101;
//Used to pause/resume MediaPlayer
private int resumePosition;
//AudioFocus
private AudioManager audioManager;
// Binder given to clients
private final IBinder iBinder = new LocalBinder();
private ArrayList<Audio> audioList;
private int audioIndex = -1;
private Audio activeAudio; //an object on the currently playing audio
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
/**
* Service lifecycle methods
*/
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
callStateListener();
//ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
registerBecomingNoisyReceiver();
//Listen for new Audio to play -- BroadcastReceiver
register_playNewAudio();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Load data from SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
audioList = storage.loadAudio();
audioIndex = storage.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
//Request audio focus
if (!requestAudioFocus()) {
//Could not gain focus
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlaybackStatus.PLAYING);
}
//Handle Intent action from MediaSession.TransportControls
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
mediaSession.release();
removeNotification();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.release();
}
removeAudioFocus();
//Disable the PhoneStateListener
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
//unregister BroadcastReceivers
unregisterReceiver(becomingNoisyReceiver);
unregisterReceiver(playNewAudio);
//clear cached playlist
new StorageUtil(getApplicationContext()).clearCachedAudioPlaylist();
}
/**
* Service Binder
*/
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of LocalService so clients can call public methods
return MediaPlayerService.this;
}
}
/**
* MediaPlayer callback methods
*/
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
}
#Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
stopMedia();
removeNotification();
//stop the service
stopSelf();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
//Invoked to communicate some info
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
playMedia();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
//Invoked indicating the completion of a seek operation.
}
#Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* AudioFocus
*/
private boolean requestAudioFocus() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//Focus gained
return true;
}
//Could not gain focus
return false;
}
private boolean removeAudioFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
audioManager.abandonAudioFocus(this);
}
/**
* MediaPlayer actions
*/
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();//new MediaPlayer instance
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// Set the data source to the mediaFile location
mediaPlayer.setDataSource(activeAudio.getLocalData());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
private void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
private void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
}
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
}
}
private void skipToNext() {
if (audioIndex == audioList.size() - 1) {
//if last in playlist
audioIndex = 0;
activeAudio = audioList.get(audioIndex);
} else {
//get next in playlist
activeAudio = audioList.get(++audioIndex);
}
//Update stored index
new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
//reset mediaPlayer
mediaPlayer.reset();
initMediaPlayer();
}
private void skipToPrevious() {
if (audioIndex == 0) {
//if first in playlist
//set index to the last of audioList
audioIndex = audioList.size() - 1;
activeAudio = audioList.get(audioIndex);
} else {
//get previous in playlist
activeAudio = audioList.get(--audioIndex);
}
//Update stored index
new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
//reset mediaPlayer
mediaPlayer.reset();
initMediaPlayer();
}
/**
* ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs
*/
private BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//pause audio on ACTION_AUDIO_BECOMING_NOISY
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
};
private void registerBecomingNoisyReceiver() {
//register after getting audio focus
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(becomingNoisyReceiver, intentFilter);
}
/**
* Handle PhoneState changes
*/
private void callStateListener() {
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//Starting listening for PhoneState changes
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//if at least one call exists or the phone is ringing
//pause the MediaPlayer
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
ongoingCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (ongoingCall) {
ongoingCall = false;
resumeMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
// Listen for changes to the device call state.
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* MediaSession and Notification actions
*/
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
// Create a new MediaSession
mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
//Set mediaSession's MetaData
updateMetaData();
// Attach Callback to receive MediaSession updates
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
skipToNext();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
skipToPrevious();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onStop() {
super.onStop();
removeNotification();
//Stop the service
stopSelf();
}
#Override
public void onSeekTo(long position) {
super.onSeekTo(position);
}
});
}
private void updateMetaData() {
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, activeAudio.getLocalArtist())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getLocalAlbum())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getLocalTitle())
.build());
}
private void buildNotification(PlaybackStatus playbackStatus) {
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
PendingIntent play_pauseAction = null;
//Build a new notification according to the current state of the MediaPlayer
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
//create the pause action
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
//create the play action
play_pauseAction = playbackAction(0);
}
// Create a new Notification
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
// Hide the timestamp
.setShowWhen(false)
// Set the Notification style
.setStyle(new NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compat view
.setShowActionsInCompactView(0, 1, 2))
// Set the Notification color
.setColor(getResources().getColor(R.color.colorAccent))
// Set the large and small icons
.setSmallIcon(android.R.drawable.stat_sys_headset)
// Set Notification content information
.setContentText(activeAudio.getLocalArtist())
.setContentTitle(activeAudio.getLocalAlbum())
.setContentInfo(activeAudio.getLocalTitle())
// Add playback actions
.addAction(android.R.drawable.ic_media_previous, "previous", playbackAction(3))
.addAction(notificationAction, "pause", play_pauseAction)
.addAction(android.R.drawable.ic_media_next, "next", playbackAction(2));
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent playbackAction(int actionNumber) {
Intent playbackAction = new Intent(this, MediaPlayerService.class);
switch (actionNumber) {
case 0:
// Play
playbackAction.setAction(ACTION_PLAY);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 1:
// Pause
playbackAction.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 2:
// Next track
playbackAction.setAction(ACTION_NEXT);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 3:
// Previous track
playbackAction.setAction(ACTION_PREVIOUS);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
default:
break;
}
return null;
}
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
} else if (actionString.equalsIgnoreCase(ACTION_NEXT)) {
transportControls.skipToNext();
} else if (actionString.equalsIgnoreCase(ACTION_PREVIOUS)) {
transportControls.skipToPrevious();
} else if (actionString.equalsIgnoreCase(ACTION_STOP)) {
transportControls.stop();
}
}
/**
* Play new Audio
*/
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get the new media index form SharedPreferences
audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
//A PLAY_NEW_AUDIO action received
//reset mediaPlayer to play the new Audio
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void register_playNewAudio() {
//Register playNewMedia receiver
IntentFilter filter = new IntentFilter(FragmentRight.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
And my Playlist fragment is like this:
public class FragmentRight extends Fragment {
public static final String Broadcast_PLAY_NEW_AUDIO = "com.example.anuj.musicmetest.PlayNewAudio";
private OnFragmentInteractionListener mListener;
ArrayList<Audio> localList;
TextView nameView;
private MediaPlayerService mediaPlayer;
boolean serviceBound = false;
public FragmentRight() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_right, container, false);
nameView = (TextView) rootView.findViewById(R.id.name1);
loadAudio();
RecyclerView recyclerView1 = (RecyclerView) rootView.findViewById(R.id.recycler_view1);
LocalListAdapter localListAdapteradapter = new LocalListAdapter(getActivity().getApplication(), localList);
recyclerView1.setAdapter(localListAdapteradapter);
recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity().getApplication()));
recyclerView1.addOnItemTouchListener(new CustomTouchListener(getActivity(), new onItemClickListener() {
#Override
public void onClick(View view, int index) {
playAudio(index);
Intent intent = new Intent(getActivity(), MusicPlayer.class);
startActivity(intent);
}
}));
return rootView;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
mediaPlayer = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
private void playAudio(int audioIndex) {
//Check is service is active
if (!serviceBound) {
//Store Serializable audioList to SharedPreferences
StorageUtil storage = new StorageUtil(getActivity().getApplicationContext());
storage.storeAudio(localList);
storage.storeAudioIndex(audioIndex);
Intent playerIntent = new Intent(getActivity(), MediaPlayerService.class);
getActivity().startService(playerIntent);
getActivity().bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Store the new audioIndex to SharedPreferences
StorageUtil storage = new StorageUtil(getActivity().getApplicationContext());
storage.storeAudioIndex(audioIndex);
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
getActivity().sendBroadcast(broadcastIntent);
}
}
private void loadAudio() {
ContentResolver contentResolver = getActivity().getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);
if (cursor != null && cursor.getCount() > 0) {
localList = new ArrayList<>();
while (cursor.moveToNext()) {
String localData = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String localTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String localAlbum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String localArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
// Save to audioList
localList.add(new Audio(localData, localTitle, localAlbum, localArtist));
}
}
cursor.close();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onDestroy() {
super.onDestroy();
if (serviceBound) {
getContext().unbindService(serviceConnection);
//service is active
mediaPlayer.stopSelf();
}
}

Play background music in all activities of Android app

I spend about 20 hours until now and my problem there still is .
I am creating an android application that has several Activities (mainMenu , aboutUs,setting).
I followed the best answered of below link and that was O.K .
Music played using asyncTask isn't stopping by using cancel
When i run my app,(my code is in mainActivity ), the music begin and it does not stop when navigate to other Activities . This is GOOD .
But i put a ToggleButton in my setting_activity Activity that i hope this Button starts and stops this music. NOW my question is how can i stop and/or start music again from setting_activity ?
in another solution :
I create a class MusicManager and i call it`s start and stop .
But this was several problems too :
Music started in mainMenu_activity but only play for about 15 seconds and then stopped.
I could not stop the music from another activities.At this time i play music in mainMenua_ctivity as this line codes :
MusicManager mm = new MusicManager(this, R.raw.background_sound);
mm.play();
How can i stop playing that ?
3. The music stopped when i navigate to other activities .
public class MusicManager implements OnPreparedListener {
static MediaPlayer mPlayer;
Context context;
private int mySoundId;
public MusicManager(Context ctx, int musicID) {
context = ctx;
mySoundId = musicID;
mPlayer = MediaPlayer.create(context, mySoundId);
mPlayer.setOnPreparedListener(this);
}
public void play() {
mPlayer = MediaPlayer.create(context, mySoundId);
}
public void stop() {
mPlayer.stop();
mPlayer.release();
}
#Override
public void onPrepared(MediaPlayer player) {
player.start();
mPlayer.setLooping(true);
mPlayer.setVolume(25, 25);
}
}
Finally i want to play a background music in all activities without stop/start music .
How can i do it ?
You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.
Here are some code example about it: https://stackoverflow.com/a/8209975/2804473
The code below is written by Synxmax here at StackOverflow, and covered in the link above:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
#Override
public void onCreate (){
super.onCreate();
Player = MediaPlayer.create(this, R.raw.jingle);
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;
}
});
}
public class serv extends Service{
MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
mp = MediaPlayer.create(this, R.raw.b);
mp.setLooping(false);
}
public void onDestroy()
{
mp.stop();
}
public void onStart(Intent intent,int startid){
Log.d(tag, "On start");
mp.start();
}
}
The top answer is correct, however you have to add the service to the manifest file.
<service android:enabled="true" android:name="BackgroundSoundService" />
Simon's answer above is correct. I had similar problem where I have fragments which had music player and I needed to go back to that UI on click of a button. Your case is similar but instead of going back to UI, you want to control playback. Here is what I did for my application. This takes care of playback of audio list including shuffle and repeat functionality. This takes care of showing media controls in notification bar too.
Create a service MusicPlayerService with following code:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
public static final String ACTION_PLAY = "pkg_name.ACTION_PLAY";
public static final String ACTION_PAUSE = "pkg_name.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "pkg_name.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "pkg_name.ACTION_NEXT";
public static final String ACTION_STOP = "pkg_name.ACTION_STOP";
private MediaPlayer mediaPlayer;
//MediaSession
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
//AudioPlayer notification ID
private static final int NOTIFICATION_ID = 101;
//Used to pause/resume MediaPlayer
private int resumePosition;
// Binder given to clients
private final IBinder iBinder = new LocalBinder();
//List of available Audio files
private ArrayList<PlayableTrack> audioList;
private int audioIndex = -1;
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private Bitmap albumArtBitmap;
private boolean shuffle = false;
private boolean repeat = false;
private Random rand;
/**
* Service lifecycle methods
*/
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
// Perform one-time setup procedures
// Manage incoming phone calls during playback.
// Pause MediaPlayer on incoming call,
// Resume on hangup.
callStateListener();
//ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
registerBecomingNoisyReceiver();
//Listen for new Audio to play -- BroadcastReceiver
register_playNewAudio();
rand = new Random();
StorageUtil storage = new StorageUtil(getApplicationContext());
shuffle = storage.loadShuffleRepeat("Shuffle");
repeat = storage.loadShuffleRepeat("Repeat");
}
//The system calls this method when an activity, requests the service be started
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Load data from SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
audioList = storage.loadAudio();
audioIndex = storage.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlaybackStatus.PLAYING);
}
//Handle Intent action from MediaSession.TransportControls
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
mediaSession.release();
removeNotification();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.reset();
}
//Disable the PhoneStateListener
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
//unregister BroadcastReceivers
unregisterReceiver(becomingNoisyReceiver);
unregisterReceiver(playNewAudio);
Picasso.get().cancelRequest(target);
}
/**
* Service Binder
*/
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of LocalService so clients can call public methods
return MediaPlayerService.this;
}
}
/**
* MediaPlayer callback methods
*/
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
}
#Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
stopMedia();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
playMedia();
}
#Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* MediaPlayer actions
*/
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();//new MediaPlayer instance
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
try {
// Set the data source to the mediaFile location
mediaPlayer.setDataSource(activeAudio.getFileLocation());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
public void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
public void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
buildNotification(PlaybackStatus.PAUSED);
Intent intent = new Intent("PLAYBACK_PAUSED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
/**
* ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs
*/
private BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//pause audio on ACTION_AUDIO_BECOMING_NOISY
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
};
private void registerBecomingNoisyReceiver() {
//register after getting audio focus
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(becomingNoisyReceiver, intentFilter);
}
/**
* Handle PhoneState changes
*/
private void callStateListener() {
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//Starting listening for PhoneState changes
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//if at least one call exists or the phone is ringing
//pause the MediaPlayer
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
ongoingCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (ongoingCall) {
ongoingCall = false;
resumeMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
// Listen for changes to the device call state.
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* MediaSession and Notification actions
*/
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
// Create a new MediaSession
mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
//Set mediaSession's MetaData
updateMetaData();
// Attach Callback to receive MediaSession updates
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
}
});
}
private void updateMetaData() {
fetchBitmapOfAlbum();
// Update the current metadata
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArtBitmap)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getTrackName())
.build());
}
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
albumArtBitmap = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
private void fetchBitmapOfAlbum() {
Picasso.get().load(activeAudio.getAlbumArt())
.placeholder(R.drawable.rotate_animation)
.error(R.drawable.ic_blank)
.into(target);
}
private void buildNotification(PlaybackStatus playbackStatus) {
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
PendingIntent play_pauseAction = null;
//Build a new notification according to the current state of the MediaPlayer
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
//create the pause action
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
//create the play action
play_pauseAction = playbackAction(0);
}
fetchBitmapOfAlbum(); //replace with your own image
String channelId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelId = "APP_MUSIC";
}
// Create a new Notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
// Hide the timestamp
.setShowWhen(false)
// Set the Notification style
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compat view
.setShowActionsInCompactView(0, 1, 2))
// Set the Notification color
.setColor(ContextCompat.getColor(this.getApplicationContext(), R.color.colorAccent))
// Set the large and small icons
.setLargeIcon(albumArtBitmap)
.setSmallIcon(R.drawable.ic_stat_notifications)
// Set Notification content information
.setContentText(activeAudio.getTrackName())
.setTicker(activeAudio.getAlbumName() + "-" + activeAudio.getTrackName())
.setOngoing(true)
.setContentTitle(activeAudio.getAlbumName())
.setContentInfo(activeAudio.getTrackName())
// Add playback actions
.addAction(notificationAction, "pause", play_pauseAction)
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent playbackAction(int actionNumber) {
Intent playbackAction = new Intent(this, MediaPlayerService.class);
switch (actionNumber) {
case 0:
// Play
playbackAction.setAction(ACTION_PLAY);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 1:
// Pause
playbackAction.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
default:
break;
}
return null;
}
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
}
}
/**
* Play new Audio
*/
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get the new media index form SharedPreferences
audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
//A PLAY_NEW_AUDIO action received
//reset mediaPlayer to play the new Audio
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void register_playNewAudio() {
//Register playNewMedia receiver
IntentFilter filter = new IntentFilter(MainActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
public boolean isPlaying(){
return mediaPlayer.isPlaying();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Shuffle", shuffle);
}
public void setRepeat(){
if(repeat) repeat=false;
else repeat=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Repeat", repeat);
}
}
Add the service to your manifest
<service android:name=".service.MediaPlayerService" />
Bind the service in MainActivity and declare methods to call the service
public class MainActivity {
private MediaPlayerService player;
boolean serviceBound = false;
public static final String Broadcast_PLAY_NEW_AUDIO = "pkg_name.PlayNewAudio";
//Binding this Client to the AudioPlayer Service
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
// Call this method to play track
public void playAudio(int audioIndex, ArrayList<PlayableTrack> updatedList) {
//Check is service is active
audioList = updatedList;
if (!serviceBound) {
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Service is active
//Send a broadcast to the service -> PLAY_NEW_AUDIO
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
// Additional methods for control
public void start() {
player.playMedia();
}
public void pause() {
player.pauseMedia();
}
public boolean isPlaying() {
if (player != null && serviceBound) {
return player.isPlaying();
}
return false;
}
}
This is my solution:
1- first add a music file in raw folder (in my case coffee.mp3)
2- create a class named BackgroundSoundService that extends Service:
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.coffee);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("PLAY")) {
if(mediaPlayer.isPlaying() == false) {
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Music Is Playing", Toast.LENGTH_SHORT).show();
}
}
if (intent.getAction().equals("STOP")) {
this.stopService(intent);
Toast.makeText(getApplicationContext(), "Music Stopped", Toast.LENGTH_SHORT).show();
}
return startId;
}
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
do not forget to define this service in application tag of android manifest.xml:
<service android:name=".BackgroundSoundService" />
3- for play button in your activity use this code:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "PLAY";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
3- for stop button in your activity use this code:
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "STOP";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
I have created a simple android app with two activity which play music in background service, the app will pause the music if app is not visible to the user (for example user pressed home button).
you can see it in my github for more details.

Android- listview, service mediaplayer, and boolean flags

I currently have a listview and when you click on an item it runs a service with a mediaplayer. If I click on another item in the listview the service that's running should stop and run the new service. I am using a boolean isRunning set to false and when the service is created it returns true. Then in the listview I call that flag in an if statement. However, its not exactly working. I think I may be doing this wrong. Any ideas?
This probably sounds confusing the way I described it so Here is the code to my listview and my service. I am only testing this on case 3 (so I press this item to start the service and then click on case 2 to see if it will stop it).
Listview class:
public class PlaylistActivity extends ListActivity{
private static final String TAG = PlaylistActivity.class.getSimpleName();
// Data to put in the ListAdapter
private String[] sdrPlaylistNames = new String[] {
"Best of June 2011", "Best of May 2011", "Dubstep",
"House", "Other"};
private ListAdapter sdrListAdapter;
Intent playbackServiceIntentBOJ, playbackServiceIntentBOM, playbackServiceIntentDUB;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.playlists_layout);
//fill the screen with the list adapter
playlistFillData();
playbackServiceIntentDUB = new Intent(this, DUBAudioService.class);
Log.d(TAG, "Made DUB Service Intent");
}
public void playlistFillData() {
//create and set up the Array adapter for the list view
ArrayAdapter sdrListAdapter = new ArrayAdapter(this, R.layout.list_item, sdrPlaylistNames);
setListAdapter(sdrListAdapter);
}
//set up the on list item Click
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//create a switch so that each list item is a different playlist
switch(position){
case 0:
Intent BOJintent = new Intent(this, BOJAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOJintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view);
// playbackServiceIntentBOJ = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOJ Intent");
// startService(playbackServiceIntentBOJ);
Log.d(TAG, "started BOJ Service");
break;
case 1:
Intent BOMintent = new Intent(this, BOMAudioActivity.class);
// Create the view using PlaylistGroup's LocalActivityManager
View view2 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", BOMintent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
// Again, replace the view
PlaylistGroup.group.replaceView(view2);
Log.d(TAG, "Replace view");
//getApplicationContext().stopService(playbackServiceIntentBOJ);
//playbackServiceIntentBOM = new Intent(this, BOJAudioService.class);
Log.d(TAG, "Made BOM Service Intent");
// startService(playbackServiceIntentBOM);
Log.d(TAG, "started BOM Service");
if(DUBAudioActivity.isRunningDUB = true){
stopService(playbackServiceIntentDUB);
Log.d(TAG, "stop service isRunningDUB");
}
//
break;
case 2:
Intent DUBIntent = new Intent (this, DUBAudioActivity.class);
View view3 = PlaylistGroup.group.getLocalActivityManager()
.startActivity("show_city", DUBIntent
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
PlaylistGroup.group.replaceView(view3);
Log.d(TAG, "Replace view");
startService(playbackServiceIntentDUB);
Log.d(TAG, "started DUB service");
break;
}
}
}
Service Class:
public class DUBAudioService extends Service implements OnPreparedListener, OnCompletionListener{
Toast loadingMessage;
private static final String TAG = DUBAudioService.class.getSimpleName();
public static boolean isRunningDUB = false;
//to keep track of the playlist item
Vector<PlaylistFile> playlistItems;
MediaPlayer mediaPlayer;
String baseURL = "";
//keep track of which item from the vector we are on
int currentPlaylistltemNumber = 0;
public class DUBBackgroundAudioServiceBinder extends Binder {
DUBAudioService getService() {
return DUBAudioService.this;
}
}
private final IBinder basBinderDUB = new DUBBackgroundAudioServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return basBinderDUB;
}
#Override
public void onCreate() {
Log.v("PLAYERSERVICE", "onCreate");
mediaPlayer = new MediaPlayer();
new MusicAsync().execute();
Log.d(TAG, "execute'd async");
mediaPlayer.setOnPreparedListener(this);
Log.d(TAG, "set on prepared listener");
mediaPlayer.setOnCompletionListener(this);
Log.d(TAG, "set on completion listener");
isRunningDUB = true;
Log.d(TAG, "isRunningRUB = true");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//if (!mediaPlayer.isPlaying()) {
// mediaPlayer.start();
//}
return START_STICKY;
}
class MusicAsync extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
//create empty vector
playlistItems = new Vector<PlaylistFile>();
//HTTP client library
HttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet ("http://dl.dropbox.com/u/24535120/m3u%20playlist/DubstepPlaylist.m3u"); //i think you could add the m3u thing in here
Log.v("URI",getRequest.getURI().toString());
try {
HttpResponse httpResponse = httpClient.execute(getRequest);
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
// ERROR MESSAGE
Log.v("HTTP ERROR",httpResponse.getStatusLine().getReasonPhrase());
}
else {
InputStream inputStream = httpResponse.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
Log.v("PLAYLISTLINE","ORIG: " + line);
if (line.startsWith("#")) {
//Metadata
//Could do more with this but not fo now
} else if (line.length() > 0) {
String filePath = "";
if (line.startsWith("http://")) {
// Assume its a full URL
filePath = line;
} else {
//Assume it’s relative
filePath = getRequest.getURI().resolve(line).toString();
}
PlaylistFile playlistFile = new PlaylistFile(filePath);
playlistItems.add (playlistFile);
}
}
inputStream.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e. printStackTrace();
}
currentPlaylistltemNumber = 0;
if (playlistItems.size() > 0)
{
String path = ((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();}
catch (IllegalArgumentException e)
{ e.printStackTrace();
}catch (IllegalStateException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();}
}
return null;
}
//
protected void onPostExecute(Void result){
//playButton. setEnabled (false);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
Log.d(TAG, "music stopp'd");
}
//mediaPlayer.release();
Log.d(TAG, "onDestroy");
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub\
Log.d(TAG, "music is prepared and will start");
mediaPlayer.start();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
Log.d(TAG, "Song completed, next song");
mediaPlayer.stop();
mediaPlayer.reset();
if (playlistItems.size() > currentPlaylistltemNumber + 1) {
currentPlaylistltemNumber++;
String path =
((PlaylistFile)playlistItems.get(currentPlaylistltemNumber)).getFilePath();
try {
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
e. printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class PlaylistFile {
String filePath;
public PlaylistFile(String _filePath) {
filePath = _filePath;
}
public void setFilePath(String _filePath) {
filePath = _filePath;
}
public String getFilePath() {
return filePath;
}
}
public void playSong(){
Log.d(TAG, "start'd");
mediaPlayer.start();
}
public void pauseSong(){
Log.d(TAG, "pause'd");
mediaPlayer.pause();
}
}
This gets pretty complicated but I used the following to see if my service was running:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("com.example.MyService".equals(service.service.getClassName())) {
return true;
}
}
return false;
}
I added this in my listview class and put if statements in each case to see if it was running and if so would stop the service.
I also made my all of my binding conenctions public so that the listview class could access them and start them on click.
If anyone wants to further understand, etc message me.
let your app track the state, not your service.

Can't get song duration in onCreate , but can get it on button pressed

I have a custom media service and an audio player class which communicates with it but is not bound to the service.
When I create an object of MyService and write the code :-
myService.player.getDuration() in onCreate I get the null pointer exception on this line.
But if I write this code on click of some button listener on the same screen then I get the exact duration.
I have tried every possible syntax to solve this but m still not able to resolve the problem.
** The code of my service is :-**
private static final String TAG = "MyService";
public static MediaPlayer player;
String song_uri,url;
Bundle b;
private IBinder myBinder;
private boolean isplaying;
public static final String Song_uri="song_uri";
public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyBinder extends Binder{
MyService getService()
{
return MyService.this;
}
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate "+song_uri);
}
#Override
public void onDestroy() {
//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setCurrentPosition(0);
Log.d(TAG, "onDestroy");
player.stop();
//player.release();
}
public void onPause()
{
player.pause();
}
public double duration()
{
return player.getDuration();
}
public void onStart(Intent intent, int startid) {
DataManager.getInstance().setWantsToPlaySong(true);
Bundle b=intent.getExtras();
song_uri=b.getString("song_uri");
Uri path=Uri.parse(song_uri);
player = MediaPlayer.create(this,path );
player.setLooping(false); // Set looping
//Toast.makeText(this, "My Service Started"+" Duration = "+(player.getDuration()/1000)/60, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart"+song_uri);
player.start();
}
The code of Audio Player is :-
uri = this.getIntent().getExtras().getString("song_uri");
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonPause = (Button) findViewById(R.id.buttonPause);
tracks = dbManager.getAllSongs(AudioPlayer2.this);
buttonForward = (Button) findViewById(R.id.buttonforward);
buttonBackward = (Button) findViewById(R.id.buttonbackward);
//=========================================================================================
sArtworkUri = Uri.parse("content://media/external/audio/albumart");
//myservice=new MyService();
Uri path = Uri.parse(uri);
current_song=this.getIntent().getExtras().getInt("current_song");
albumArtUri = this.getIntent().getExtras().getString("album_art");
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
album_id = Long.parseLong(this.getIntent().getStringExtra("album_id"));
int id = Integer.parseInt(this.getIntent().getStringExtra("album_id"));
albumImageUri = ContentUris.withAppendedId(sArtworkUri, album_id);
ivAlbumArt = (ImageView) findViewById(R.id.album_art);
songName = this.getIntent().getStringExtra("song_name");
albumName = this.getIntent().getStringExtra("album_name");
tvName = (TextView) findViewById(R.id.tv_name);
tvAlbum = (TextView) findViewById(R.id.tv_album);
if (songName != null) {
tvName.setText(songName);
}
if (albumName != null) {
tvAlbum.setText(albumName);
}
// buttonStart.performClick();
if (DataManager.getInstance().getOnPausedSong()=="y"){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
if(DataManager.getInstance().getPausedSongName()==songName){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
}
}
FetchImage fetchImage = new FetchImage();
fetchImage.execute();
/*if(DataManager.getInstance().getSong_uri()!=null)
{
stopService(new Intent(this, MyService.class));
}*/
// if(myService.player.isPlaying())
//{
stopService(new Intent(this, MyService.class));
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
myService.player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
}
});
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// Toast.makeText(this, "Duration: "+myService.player.getDuration(), Toast.LENGTH_LONG).show();
/*//}//DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
*/ //buttonStart.setPressed(true);
//=======================================================================================
buttonStart.setOnClickListener(this);
buttonPause.setOnClickListener(this);
buttonForward.setOnClickListener(this);
buttonBackward.setOnClickListener(this);
buttonStop.setOnClickListener(this);
// buttonPause.performClick();
/* new Thread(myThread).start();
*/ }
// Thread for seekbar
// song starts playing
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
if(DataManager.getInstance().getSongPause()=="y"){
myService.player.start();
DataManager.getInstance().setSongPause("n");
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// DataManager.getInstance().setWantsToPlaySong(true);
//DataManager.getInstance().setOnPausedSong("n");
//DataManager.getInstance().setOnPausedSong("y");
}else{
stopService(new Intent(this, MyService.class));
DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
}
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
break;
case R.id.buttonforward:
stopService(new Intent(this, MyService.class));
current_song++;
FetchAllMusic fetchAllMusic = new FetchAllMusic();
fetchAllMusic.execute();
//new Thread(myThread).start();
break;
case R.id.buttonbackward:
Log.d(TAG, "onClick: stopping service");
stopService(new Intent(this, MyService.class));
if(current_song>0){
current_song--;
}
FetchAllMusic fetchAllMusic2 = new FetchAllMusic();
fetchAllMusic2.execute();
break;
case R.id.buttonPause:
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
/* MyService myservice=new MyService();
myservice.onPause();*/
myService.player.pause();
DataManager.getInstance().setSongPause("y");
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setOnPausedSong("n");
DataManager.getInstance().setPausedSongName(songName);
//duration=myService.player.getDuration();
// Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show();
}
}
public void onBackPressed() {
try {
//addvideo.removeView(DBManager.getInstance().getVideo());
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setAlbum_id(""+album_id);
DataManager.getInstance().setAlbumName(albumName);
DataManager.getInstance().setSongName(songName);
DataManager.getInstance().setAlbumArtUri(albumArtUri);
DataManager.getInstance().setCurrent_song(current_song);
DataManager.getInstance().setWantsToPlaySong(false);
} catch (Exception e) {
e.printStackTrace();
}
super.onBackPressed();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
Log.d(TAG, "Thread Starts");
// TODO Auto-generated method stub
while (myProgress<100){
try{
Log.d(TAG, "Thread Starts");
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(3000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
myProgress++;
seekbar.setProgress(myProgress);
}
};
};
It's not a syntax problem; it's a variable initialization problem. Either myService or myService.player is null when that line executes in onCreate(). Check your code for where you are initializing these and make sure that you don't reference them before they are set.

Categories

Resources