Cannot stop and start service when I want - android

That's my MainActivity.
package com.example.simeon.cookingbook.activities;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import com.example.simeon.cookingbook.R;
import com.example.simeon.cookingbook.services.BackgroundMusic;
public class MainActivity extends AppCompatActivity {
Intent srv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.srv = new Intent(this, BackgroundMusic.class);
startService(srv);
}
#Override
protected void onDestroy() {
super.onDestroy();
stopService(srv);
}
#Override
protected void onPause() {
super.onPause();
stopService(srv);
}
#Override
protected void onStop() {
super.onStop();
stopService(srv);
}
#Override
protected void onRestart() {
super.onRestart();
startService(srv);
}
#Override
protected void onResume() {
super.onResume();
startService(srv);
}
}
That's BackgroundMusic Service.
package com.example.simeon.cookingbook.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import com.example.simeon.cookingbook.R;
public class BackgroundMusic extends Service {
private static final String TAG = null;
public MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
}
I have other activities and I want the music to be heard when my application is opened, but when it goes to background, I don't want music to continue playing. I tried with BaseActivityClass and have read a lot, but still no solution. Please help, thank you in advance.

When you are done using MediaPlayer you need to release it with the release() method. I guess the onDestroy() method of you Service is a good place for that:
public class BackgroundMusic extends Service {
private static final String TAG = null;
public MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.background);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return START_STICKY;
}
public int onDestroy() {
player.release();
}
}

Related

How to make service for Play Pause of music Player

Here is my code which is play song from the resources folder and now I am stuck with service so please help me.....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler=new Handler();
seekBar=findViewById(R.id.seekBar);
mp=MediaPlayer.create(MainActivity.this,R.raw.ed);
final int Duration=mp.getDuration();
Media Player Prepared Listener.....
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
updateSeekBar();
mp.start();
}
});
Runnable Thread for Seekbar.....
runnable=new Runnable() {
#Override
public void run() {
updateSeekBar();
}
};
Phone State Listener for Incoming and Outgoing Calls.....
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
mp.pause();
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
mp.start();
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
mp.pause();
}
super.onCallStateChanged(state, incomingNumber);
}
};
TelephonyManager mgr = (TelephonyManager)
getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
Seek Bar Update Method....
private void updateSeekBar() {
seekBar.setProgress(mp.getCurrentPosition());
mHandler.postDelayed(runnable, 100);
}
}
Now, it's my service code.......
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
public class MyMusicService extends Service {
On Create method of service....
#Override
public void onCreate() {
super.onCreate();
}
On start method of service....
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
On Destroy method of service....
#Override
public void onDestroy() {
super.onDestroy();
}
Binder of Service.....
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
see i have added the code of service which is work for me.
you can try this code for your need
package com.example.musicplayer;
import java.util.ArrayList;
import java.util.Random;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentUris;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
/*
* This is demo code to accompany the Mobiletuts+ series:
* Android SDK: Creating a Music Player
*
*/
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
//binder
private final IBinder musicBind = new MusicBinder();
//title of current song
private String songTitle="";
//notification id
private static final int NOTIFY_ID=1;
//shuffle flag and random
private boolean shuffle=false;
private Random rand;
public void onCreate(){
//create the service
super.onCreate();
//initialize position
songPosn=0;
//random
rand=new Random();
//create player
player = new MediaPlayer();
//initialize
initMusicPlayer();
}
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set listeners
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
//pass song list
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
//binder
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
//activity will bind to service
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
//release resources when unbind
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
//play a song
public void playSong(){
//play
player.reset();
//get song
Song playSong = songs.get(songPosn);
//get title
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
//set the data source
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
//set the song
public void setSong(int songIndex){
songPosn=songIndex;
}
#Override
public void onCompletion(MediaPlayer mp) {
//check if playback has reached the end of a track
if(player.getCurrentPosition()>0){
mp.reset();
playNext();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.v("MUSIC PLAYER", "Playback Error");
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
//notification
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
//playback methods
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
//skip to previous track
public void playPrev(){
songPosn--;
if(songPosn<0) songPosn=songs.size()-1;
playSong();
}
//skip to next
public void playNext(){
if(shuffle){
int newSong = songPosn;
while(newSong==songPosn){
newSong=rand.nextInt(songs.size());
}
songPosn=newSong;
}
else{
songPosn++;
if(songPosn>=songs.size()) songPosn=0;
}
playSong();
}
#Override
public void onDestroy() {
stopForeground(true);
}
//toggle shuffle
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
}
}
OR
if you want to learn from scratch then
follow this link to learn and create your self too.
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-project-setup--mobile-22764
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-song-playback--mobile-22778
http://code.tutsplus.com/tutorials/create-a-music-player-on-android-user-controls--mobile-22787
i hope it helps you.
thanks.

AsyncTask not getting excused after app is terminated?

I want perform some check continuously. I have defined AsyncTask as
follows,
new AsyncTask<String, Void, String>() {
#Override
protected void onPreExecute() {
Log.d(TAG, "onPreExecute()");
}
#Override
protected String doInBackground(String... params) {
sendData(array);
return null;
}
#Override
protected void onPostExecute(String res) { }
}.execute(userResponse);
But when I terminate the application then thread stops execution.
Service class demo :-
package com.example.My Application;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Activity :-
package com.example.My Application;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Method to start the service
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}
Manifest :-
Add <service android:name=".MyService" />

Service Intent must be explicit

I'm trying to use service for a background music.
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service implements MediaPlayer.OnPreparedListener {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.yedid_nefesh);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
return flags;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
I call it from the MainActivity with the line: startService(new Intent(PlayMusicService.ACTION_PLAY));
and of course I added an intent-filter
<intent-filter>
<action android:name="com.example.neotavraham.PLAY"/>
</intent-filter>
I was looking for a fine solution in the internet but couldn't find one...what should I do?
Please call the service from intent and set the action of that intent like this:
Intent i = new Intent(this,PlayMusicService.class);
i.setAction("com.example.neotavraham.PLAY");
startService(i);
This code will work.
Background service for start media player
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.idil);
mMediaPlayer.setLooping(true); // Set looping
mMediaPlayer.setVolume(100,100);
mMediaPlayer.start();
}
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
Thanks
In your activity do the following:
Intent i = new Intent(this,PlayMusicService.class);
i.putExtra("action","com.example.neotavraham.PLAY");
startService(i);
In your service do the following:
package com.example.neotavraham;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
public class PlayMusicService extends Service {
public static final String ACTION_PLAY = "com.example.neotavraham.PLAY";
MediaPlayer mMediaPlayer = null;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getStringExtra("action").equals(ACTION_PLAY)) {
mMediaPlayer = MediaPlayer.create(this, R.raw.yedid_nefesh);
mMediaPlayer = MediaPlayer.create(this, R.raw.idil);
mMediaPlayer.setLooping(true); // Set looping
mMediaPlayer.setVolume(100,100);
mMediaPlayer.start();
}
return flags;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
}
In your manifiest do the following:
<service
android:name="com.example.neotavraham.PlayMusicService"
/>
This is the perfect code for your app. Hope this will work finally....

Application crash with no exception after resuming

I am making simple app to display video and plaing audio playback if activity is in background.
My app works fine if i just turn screen off/on.
It crashes when I resume my app after brawsing another application.
Log cat show no error.
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import com.squareup.otto.Subscribe;
public class MainActivity
extends Activity
implements android.view.SurfaceHolder.Callback {
private SurfaceView surfaceViewFrame;
private SurfaceHolder holder;
private Bundle extras;
private static final String TAG = "log_tag";
private boolean b = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceViewFrame = (SurfaceView) findViewById(R.id.surfaceView);
surfaceViewFrame.setClickable(false);
holder = surfaceViewFrame.getHolder();
holder.addCallback(this);
}
#Subscribe
public void attachPlayer(MediaPlayer player) {
player.setDisplay(holder);
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
public void surfaceCreated(SurfaceHolder holder) {
startService(new Intent(this, MediaPlayerService.class));
}
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
protected void onStart() {
super.onStart();
BusProvider.getInstance().register(this);
}
#Override
protected void onStop() {
super.onStop();
BusProvider.getInstance().unregister(this);
}
Service
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class MediaPlayerService
extends Service
implements MediaPlayer.OnPreparedListener,
MediaPlayer.OnCompletionListener,
MediaPlayer.OnSeekCompleteListener {
private static final String TAG = "MediaService";
private static final String ACTION_PLAY = "com.example.action.PLAY";
private MediaPlayer player;
public String[]
video_path =
{"https://ellovidsout.s3.amazonaws.com/1265/9/1422967594.mp4.m3u8", "https://ellovidsout.s3.amazonaws.com/1260/9/1422887544.mp4.m3u8"};
#Override
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnSeekCompleteListener(this);
player.setScreenOnWhilePlaying(true);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
playVideo();
Notification note = new Notification(
R.drawable.ic_launcher, "Can you hear the music?", System.currentTimeMillis()
);
Intent i = new Intent(this, MediaPlayerService.class);
i.setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
);
PendingIntent pi = PendingIntent.getActivity(
this, 0, i, 0
);
note.setLatestEventInfo(
this, "Fake Player", "Now Playing: \"Ummmm, Nothing\"", pi
);
note.flags |= Notification.FLAG_NO_CLEAR;
startForeground(1337, note);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.release();
player = null;
}
private Thread playback = new Thread(
new Runnable() {
public void run() {
try {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
player.prepareAsync();
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
}
}
);
private void playVideo() {
if (player!=null&&!playback.isAlive()) playback.start();
}
public void onPrepared(MediaPlayer mp) {
if (!player.isPlaying()) {
player.start();
BusProvider.getInstance()
.post(player);
}
}
public void onCompletion(MediaPlayer mp) {
try {
player.setDataSource(
MediaPlayerService.this, Uri.parse(
video_path[0]
)
);
} catch (IOException e) {
Log.e(TAG, "Error while playing video: " + e.getMessage());
}
player.prepareAsync();
}
public void onSeekComplete(MediaPlayer mp) {
}
}
you missed in onStop:
#Override
protected void onStop() {
holder.removeCallback(this);
super.onStop();
}
please add the crash report

In Android, How can I avoid the onStart method from being deprecated?

I am having a problem with setting the onStart method in my app. It always has a strikethrough, saying "This method was deprecated in API level 5. I need onStart, not onStartCommand.
How can I resolve this?
MyNotificationService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyNotificationService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "OnCreate()", Toast.LENGTH_SHORT).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
}
Reminder_2.java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.DatePicker;
import android.widget.ImageButton;
public class Reminder_2 extends Activity {
String message;
DatePicker datepicker;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder_2);
datepicker=(DatePicker)findViewById(R.id.datePicker1);
Home();
Next();
Save();
}
private void Next() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton1);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
finish();
}
};
Button.setOnClickListener(myListener);
}
private void Save() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton3);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent();
intent.setClass(getApplicationContext(), MyNotificationService.class);
startService(intent);
}
};
Button.setOnClickListener(myListener);
}
private void Home() {
final MediaPlayer button_tone = MediaPlayer.create(this, R.raw.button_sound);
ImageButton Button = (ImageButton) findViewById(R.id.imageButton2);
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
button_tone.start();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
};
Button.setOnClickListener(myListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reminder, menu);
return true;
}
}
Use onStartCommand().
It you want to know more about how they change it, refer to google documentation like below.
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
#Override
public void onStart(Intent intent, int startId) {
handleStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleStart(intent, startId);
return START_NOT_STICKY;
}
You can use like this with onStartCommand().
package htin.linnzaw.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
private MediaPlayer mediaplayer;
public MyService()
{
}
#Override
public IBinder onBind(Intent intent)
{
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate()
{
Toast.makeText(this, "Service created", Toast.LENGTH_SHORT).show();
mediaplayer = MediaPlayer.create(this, R.raw.eventually);
mediaplayer.setLooping(false);
}
#Override
public int onStartCommand(Intent intent, int flags, int startid)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
mediaplayer.start();
return startid;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
mediaplayer.stop();
}
}

Categories

Resources