I have been trying to stream .wav file from server in the background. It works fine with .mp3 audio files. But when I try to play an .wav file, it is not playing. I implemented the audio player as a service. The following is the code
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class SoundService extends Service implements MediaPlayer.OnPreparedListener {
private static final String TAG = "MyService";
String url;
MediaPlayer mp;
public IBinder onBind(Intent intent) {
Log.i("OnBind", "Inside OnBind");
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.i(TAG, "onCreate");
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d("Stopping", "onDestroy");
mp.stop();
}
#Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.i("Starting", "onStart");
url = intent.getExtras().getString("url");
Log.i("Starting2", "onStart2");
try {
mp.reset();
Log.i("URLIS",""+url);
mp.setDataSource(url);
Log.i("Datasource", "datasource");
mp.setOnPreparedListener(this);
Log.i("preparedlistener", "PreparedListener");
mp.prepareAsync();
Log.i("prepareasync", "prepareAsync");
} catch(Exception e){}
return START_STICKY;
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
Log.i("onprepared", "insideprepared");
mediaPlayer.start();
}
}
The service is called from the onactivityresult in mainActivity passing the url of audio file in intent.
public void onResponse(String response) {
Log.i("Myresponse",""+response);
Intent i = new Intent(MainActivity.this, SoundService.class);
i.putExtra("url",response);
startService(i);
Log.i("Myresponse",""+response);
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
}
My log cat when streaming .wav file is as follows
10-02 15:00:03.527 27677-27734/com.example.gkrish.momdadme E/MediaPlayer: error (1, -2147483648)
10-02 15:00:03.534 27677-27677/com.example.gkrish.momdadme E/MediaPlayer: Error (1,-2147483648)
The code u have written is correct and most probably because of the response
Related
i have shared a valid mp3 file in my google drive however I am not able to play it due to
E/MediaPlayer: Error (1,-1015)
I cannot find any documentation for this error
my link :"https://drive.google.com/file/d/1m_TKhtlPRBzBEencnU5-RITxheXm4x6q/view?usp=sharing"
my music service:
enter code here
package com.example.mpservice;
import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
import java.io.IOException;
public class PlayService extends Service implements
MediaPlayer.OnCompletionListener,MediaPlayer.OnPreparedListener
,MediaPlayer.OnSeekCompleteListener,MediaPlayer.OnInfoListener,
MediaPlayer.OnBufferingUpdateListener,MediaPlayer.OnErrorListener {
MediaPlayer mediaPlayer;
public final String TAG="MyService";
#Override
public void onCreate() {
Log.d(TAG,"playService start");
mediaPlayer=new MediaPlayer();
//mediaPlayer=MediaPlayer.create(this,R.raw.summer);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
mediaPlayer.reset();
super.onCreate();
Log.d(TAG,"onCreate Finish");
}
#Override
public int onStartCommand(Intent intent,int flags, int startId) {
Log.d(TAG, "onStartCommand");
String url = intent.getStringExtra("URL");
Log.d(TAG, "URL :" + url);
// Uri myUri = Uri.parse("android.resource://" + this.getPackageName() + "/" + R.raw.summer);
// Uri myUri = Uri.parse(url);
//Log.d(TAG ,"URI: " +myUri);
try {
mediaPlayer.setDataSource(url);
} catch (IOException e) {
Log.d(TAG, "data source" + e);
e.printStackTrace();
}
try {
mediaPlayer.prepareAsync();
} catch (Exception e) {
Log.d(TAG,"prepare :" + e);
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
if(( mediaPlayer !=null)&& mediaPlayer.isPlaying())
{
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
Log.d(TAG, "media player stoped " );
}
Log.d(TAG, "on Destroy " );
Log.d(TAG, "media lpayer :"+mediaPlayer );
super.onDestroy();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "error media player " + what +extra);
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
Log.d(TAG, "info media player " + what +extra);
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "mp start ");
mp.start();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
}
}
I am starting a service from MainActivity, which run indefinitely looking for incoming and outgoing calls to record.
Why is that the sample "switch-case" doesn't work?
No error occurs but I can record only each of incoming and outgoing.
The service is killed after recording the call, it will be recreated START_STICKY but never going to get started.
Please help. Thanks in advance!
Is there any other codes to record incoming and outgoing call in android?
package com.exampled.demoserv;
import java.io.File;
import java.io.IOException;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class ParentalService extends Service
{
#Override
public void onCreate()
{
//Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
//Toast.makeText(getApplicationContext(), "Subu's Monitoring sTARTED", Toast.LENGTH_SHORT).show();
startMonitor();
return START_STICKY_COMPATIBILITY;
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Binded", Toast.LENGTH_SHORT).show();
return null;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(getApplicationContext(), "Destroyed", Toast.LENGTH_SHORT).show();
}
public void startMonitor()
{
TelephonyManager mTelephonyMgr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(new TeleListener(), PhoneStateListener.LISTEN_CALL_STATE);
}
class TeleListener extends PhoneStateListener
{
boolean recording = false;
final MediaRecorder recorder = new MediaRecorder();
String inc_num="", fname;
public void onCallStateChanged(int state, String incomingNumber) throws IllegalStateException
{
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//CALL_STATE_IDLE;
Toast.makeText(getApplicationContext(), "CALL_STATE_IDLE : "+Boolean.toString(recording), Toast.LENGTH_SHORT).show();
if(recording==true)
{
recorder.stop();
recorder.reset();
recorder.release();
Toast.makeText(getApplicationContext(), "Released_idle", Toast.LENGTH_SHORT).show();
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Toast.makeText(getApplicationContext(), Boolean.toString(recording)+" : Offhook",Toast.LENGTH_SHORT).show();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
String file= Environment.getExternalStorageDirectory().toString();
String filepath= file+"/111111111111Aandroid_Subui";
File dir= new File(filepath);
dir.mkdirs();
if(inc_num.length()==0)
{
fname="outgoingNum";
}
filepath+="/"+fname+".3gp";
recorder.setOutputFile(filepath);
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start();
recording=true;
break;
case TelephonyManager.CALL_STATE_RINGING:
//CALL_STATE_RINGING
inc_num = incomingNumber;
Toast.makeText(getApplicationContext(), "CALL_STATE_RINGING : "+incomingNumber, Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getApplicationContext(), "Default reached", Toast.LENGTH_SHORT).show();
break;
}
}
}
}
Finally Got the Result... Now I can record both incoming and outgoing calls(2.2)..
Changed the whole structure..
Here is my CallRecordingService.java
Toasting will make you understood whats going arround... :)
package com.exampled.beta;
import java.io.File;
import java.io.IOException;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class CallRecordingService extends Service
{
final MediaRecorder recorder = new MediaRecorder();
boolean recording = false;
int i = 0;
String fname;
BroadcastReceiver CallRecorder = new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent intent)
{
// TODO Auto-generated method stub
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
i++;
if(TelephonyManager.EXTRA_STATE_OFFHOOK.equals(state))
{
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_LONG).show();
Toast.makeText(arg0, "Start CaLLED "+recording+fname, Toast.LENGTH_LONG).show();
startRecording();
}
if(TelephonyManager.EXTRA_STATE_IDLE.equals(state) && recording == true)
{
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_LONG).show();
Toast.makeText(arg0, "STOP CaLLED :"+recording, Toast.LENGTH_LONG).show();
stopRecording();
}
if(TelephonyManager.EXTRA_STATE_RINGING.equals(state))
{
fname = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(getApplicationContext(), state+" : "+fname, Toast.LENGTH_LONG).show();
}
}
};
BroadcastReceiver OutGoingNumDetector = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
fname=intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
};
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
IntentFilter RecFilter = new IntentFilter();
RecFilter.addAction("android.intent.action.PHONE_STATE");
registerReceiver(CallRecorder, RecFilter);
IntentFilter OutGoingNumFilter=new IntentFilter();
OutGoingNumFilter.addAction("android.intent.action.NEW_OUTGOING_CALL");
registerReceiver(OutGoingNumDetector, OutGoingNumFilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
// TODO Auto-generated method stub
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(CallRecorder);
unregisterReceiver(OutGoingNumDetector);
Toast.makeText(getApplicationContext(), "Destroyed", Toast.LENGTH_SHORT).show();
}
public void startRecording()
{
if(recording==false)
{
Toast.makeText(getApplicationContext(), "Recorder_Sarted"+fname, Toast.LENGTH_LONG).show();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
String file= Environment.getExternalStorageDirectory().toString();
String filepath= file+"/11111111111111";
File dir= new File(filepath);
dir.mkdirs();
filepath+="/"+fname+".3gp";
recorder.setOutputFile(filepath);
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start();
recording=true;
}
}
public void stopRecording()
{
if(recording==true)
{
Toast.makeText(getApplicationContext(), "Recorder_Relesed from "+recording, Toast.LENGTH_LONG).show();
recorder.stop();
recorder.reset();
recorder.release();
recording=false;
broadcastIntent();
}
}
public void broadcastIntent()
{
Intent intent = new Intent();
intent.setAction("com.exampled.beta.CUSTOM_INTENT");
sendBroadcast(intent);
Toast.makeText(getApplicationContext(), "BroadCaste", Toast.LENGTH_LONG).show();
}
}
ServiceCaller.java
package com.exampled.beta;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class ServiceCaller extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
// TODO Auto-generated method stub
arg0.stopService(new Intent(arg0,CallRecordingService.class));
Intent intent=new Intent(arg0, CallRecordingService.class);
arg0.startService(intent);
Toast.makeText(arg0, "Service Explicitely", Toast.LENGTH_SHORT).show();
}
}
MainActivity.java
package com.exampled.beta;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this,CallRecordingService.class);
startService(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is
// present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
PERMISSIONS
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
Instead of myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
use myAudioRecorder.setAudioSource(MediaRecorder.AudioSource.VOICE_CALL);
This particular option is described here> http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html Voice call uplink + downlink audio source That means the recording will contain both voices.
Be careful when you start recording. When the call is initiated or when the other-party answer the call.
I have a class which calls this service class to play the media player
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.s);// raw/s.mp3
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
I don't want it to load the raw file i want it to load a path which a string in the class that calls this service.
String path = "path is here"
private void playAudio(String url) throws Exception{
Intent music = new Intent(this,MusicService.class);
intent.putExtra("paths",path)
startService(music);
How would i go about doing this...
The music file comes from the sd card
Simply use this---------
MediaPlayer md=new MediaPlayer();
md.prepare();
md.setDataSource(path);
I don't know what are you doing in your activity but, If your are just passing a music file path in service and then want to start media player in service then I think you have to try something like this,
MediaPlayer mediaPlayer;
String musicFile;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
}
#Override
onStartCommand(Intent intent, int flags, int startId) {
musicFile=intent.getExtra("paths");
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(musicFile);
mediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!mediaPlayer.isPlaying())
{
mediaPlayer.start();
}
return START_STICKY;
}
I am trying to put background music in my app.I have created an intent service which creates a Media Player and starts the music.
Once my app is launched the music is played only for a second and after that I see the following warning in my logcat:-
09-13 20:12:54.082: WARN/TimedEventQueue(33): Event 4 was not found in the queue, already cancelled?
For every run of my App, the Event number changes.This time it was Event 5.
Here is my service class which implements media player:-
import android.app.IntentService;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnErrorListener;
import android.widget.Toast;
public class MusicService extends IntentService {
MediaPlayer mPlayer;
private OnErrorListener mErrorListener;
public MusicService() {
super("MusicService");
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
// Normally we would do some work here, like download a file.
}
///////////////////////////////////////////////////////////
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
mPlayer.setLooping(true);
mPlayer.start();
return super.onStartCommand(intent,flags,startId);
}
#Override
public void onCreate ()
{
super.onCreate();
// try{
mPlayer = MediaPlayer.create(this, R.raw.jingle);
//}catch (IllegalArgumentException e) {
//e.printStackTrace();
//}catch (IllegalStateException e ) {
//e.printStackTrace();
//}
if(mPlayer!= null)
{
mPlayer.setLooping(true); // Set looping
mPlayer.setVolume(100,100);
}
mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
onPlayError();
return true;
}
});
}
private void onPlayError() {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
}
I got the solution.The problem was that since I am using an Intent service, so after starting the service with an intent, the player started but immediately on Destroy was called where there is a code to release and stop the player.
After removing that code I could see the music playing continuously and moreover I did not see those timed queue warnings!!!
Wondering how next songs are played once app is closed as if playing an entire CD or playlist...
The media player only plays one audio track. What media players do, is listen on the onCompletion event and play the next track.
The MediaPlayer is bound to the process, not the activity, so it keeps playing as long as the process runs. The activity might be paused or destroyed, but that won't affect the internal thread that MediaPlayer uses.
I'm building an audio player to learn Android, you can see the service that plays audio files here
edit
regarding the first comment: The service keeps running on the background and keeps running after you "exit" the application, because the lifecycle of the service and Activities are different.
In order to play the next track, the service registers a callback on the MediaPlayer so the service is informed when an audio stream completed. When the audio completes, the service cleans up the resources used by the MediaPlayer, by calling MediaPlayer.release(), and then creates a fresh new media player with the next audio track to play and registers itself to be notified again when that audio track completes, ad infinitum :).
The MediaPlayer class doesn't understand playlists, so the service is responsible for playing a track after the previous track completes.
In the AudioPlayer service I've created, an activity queues tracks in the AudioPlayer and the AudioPlayer is responsible for playing them in order.
I hope it's clear and again, if you have some time, please check the code of AudioPlayer service I've put above. It's not pure beauty, but it does its job.
You can create a Service to keep the MediaPlayer playing after your app either exits or is paused. To get the MediaPlayer to play consecutive tracks you can register an onCompletionListener that will decide which track to play next. Here is a simple example service that does this:
package edu.gvsu.cis.muzak;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.IBinder;
import android.util.Log;
public class MuzakService extends Service {
private static final String DEBUG_TAG = "MuzakService";
private MediaPlayer mp;
private String[] tracks = {
"http://freedownloads.last.fm/download/288181172/Nocturne.mp3",
"http://freedownloads.last.fm/download/367924875/Behemoths%2BSternentanz.mp3",
"http://freedownloads.last.fm/download/185193341/Snowflake%2BImpromptu.mp3",
"http://freedownloads.last.fm/download/305596593/Prel%25C3%25BAdio.mp3",
"http://freedownloads.last.fm/download/142005075/Piano%2BSonata%2B22%2B-%2Bmovement%2B2%2B%2528Beethoven%2529.mp3",
"http://freedownloads.last.fm/download/106179902/Piano%2BSonata%2B%25231%2B-%2Bmovement%2B%25234%2B%2528Brahms%2529.mp3",
};
private int currentTrack = 0;
#Override
public void onCreate() {
super.onCreate();
Log.d(DEBUG_TAG, "In onCreate.");
try {
Uri file = Uri.parse(tracks[this.currentTrack]);
mp = new MediaPlayer();
mp.setDataSource(this, file);
mp.prepare();
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
currentTrack = (currentTrack + 1) % tracks.length;
Uri nextTrack = Uri.parse(tracks[currentTrack]);
try {
mp.setDataSource(MuzakService.this,nextTrack);
mp.prepare();
mp.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
} catch (Exception e) {
Log.e(DEBUG_TAG, "Player failed", e);
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.d(DEBUG_TAG, "In onDestroy.");
if(mp != null) {
mp.stop();
}
}
#Override
public int onStartCommand(Intent intent,int flags, int startId) {
super.onStart(intent, startId);
Log.d(DEBUG_TAG, "In onStart.");
mp.start();
return Service.START_STICKY_COMPATIBILITY;
}
#Override
public IBinder onBind(Intent intent) {
Log.d(DEBUG_TAG, "In onBind with intent=" + intent.getAction());
return null;
}
}
You can start this Service up in an Activity as follows:
Intent serv = new Intent(this,MuzakService.class);
startService(serv);
and stop it like this:
Intent serv = new Intent(this,MuzakService.class);
stopService(serv);
Please note that Service run in fore ground too.
Please see the official documentation. It explains with a sample code.
Using a Service with MediaPlayer:
http://developer.android.com/guide/topics/media/mediaplayer.html#mpandservices
Running as a foreground service
Services are often used for performing background tasks
But consider the case of a service that is playing music. Clearly this is a service that the user is actively aware of and the experience would be severely affected by any interruptions. Additionally, it's a service that the user will likely wish to interact with during its execution. In this case, the service should run as a "foreground service." A foreground service holds a higher level of importance within the system—the system will almost never kill the service, because it is of immediate importance to the user. When running in the foreground, the service also must provide a status bar notification to ensure that users are aware of the running service and allow them to open an activity that can interact with the service.
In order to turn your service into a foreground service, you must create a Notification for the status bar and call startForeground() from the Service
mediap player should run from the service, here i have passed the arraylist of songs from the activity to service and all the songs are run by reading the arraylist
public class MyService extends Service implements OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener{
Context context;
private static final String ACTION_PLAY = "PLAY";
private static final String TAG = "SONG SERVICE";
MediaPlayer mediaPlayer;
private int currentTrack = 0;
ArrayList<String> list;
public MyService() {
context=getBaseContext();
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
list = (ArrayList<String>)intent.getSerializableExtra("arraylist");
int count=0;
Log.d(TAG, "total count:"+list.size());
//playing song one by one
for (String string : list) {
//play(string);
count++;
Log.d(TAG, "count:"+list);
}
play(currentTrack);
Log.d(TAG, "count:"+count);
if(count==list.size()){
//stopSelf();
Log.d(TAG, "stoping service");
//mediaPlayer.setOnCompletionListener(this);
}else{
Log.d(TAG, "not stoping service");
}
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
Log.d(TAG, "oncommat");
}
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// Perform your long running operations here.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
Log.d("service", "destroyed");
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
private void play(int id) {
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
Log.d("*****begin*****", "playing");
stopPlaying();
Log.d("*****begin*****", "stoping");
} else{
Log.d("*****begin*****", "nothing");
}
Log.d("*****play count*****", "="+currentTrack);
Log.i("******playing", list.get(currentTrack));
Uri myUri1 = Uri.parse(list.get(id));
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setOnPreparedListener(this);
//mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
try {
mediaPlayer.setDataSource(context, myUri1);
Log.i("******playing", myUri1.getPath());
} catch (IllegalArgumentException e) {
Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (SecurityException e) {
Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IllegalStateException e) {
Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(context, "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
}
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
currentTrack=currentTrack+1;
play(currentTrack);
/* currentTrack = (currentTrack + 1) % list.size();
Uri nextTrack=Uri.parse(list.get(currentTrack));
try {
mediaPlayer.setDataSource(context,nextTrack);
mediaPlayer.prepare();
// mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}*/
}
});
mediaPlayer.start();
}
private void stopPlaying() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
The answer is Services in Android as described here: http://developer.android.com/guide/topics/fundamentals.html as
You are going to create a service and when you receive play command from your app, your app will send a message to background service to play the music. Services do not run in foreground, therefore even you put your screen to sleep, it plays the music.
Playing BG Music Across Activities in Android