I have a Service which takes in an audio file and plays it with MediaPlayer. This is how I call my Service:
private void playAudio(String url) throws Exception {
Intent music = new Intent(this,MusicService.class);
music.putExtra("paths", path);
startService(music);
}
This is my Service class:
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle e = intent.getExtras();
musicFile= e.getString("paths");
try {
mediaPlayer.prepare();
mediaPlayer.setDataSource(musicFile);
} catch (IllegalArgumentException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IllegalStateException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IOException i) {
// TODO Auto-generated catch block
i.printStackTrace();
}
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
The Service is never getting executed, the Toast is never shown, and the MediaPlayer does not play.
I declare my it in my manifest like this:
<service android:name=".MusicService" android:enabled="true"></service>
I get a force close error, and this IllegalAccessException in my logs:
java.lang.RuntimeException: Unable to instantiate service unjustentertainment.com.MusicService:
java.lang.IllegalAccessException: access to class not allowed
The exception you get is because the system could not init your service (call its constructor) because its not accessible.
As it says here:
...Make sure the class is
declared public...
The class you posted is not public, so make it public.
You need to make your class public.
i.e.
public class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
Related
I have a Service which takes in an audio file and plays it with MediaPlayer. This is how I call my Service:
private void playAudio(String url) throws Exception {
Intent music = new Intent(this,MusicService.class);
music.putExtra("paths", path);
startService(music);
}
This is my Service class:
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle e = intent.getExtras();
musicFile= e.getString("paths");
try {
mediaPlayer.prepare();
mediaPlayer.setDataSource(musicFile);
} catch (IllegalArgumentException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IllegalStateException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IOException i) {
// TODO Auto-generated catch block
i.printStackTrace();
}
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
return START_STICKY;
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
The Service is never getting executed, the Toast is never shown, and the MediaPlayer does not play.
I declare my it in my manifest like this:
<service android:name=".MusicService" android:enabled="true"></service>
I get a force close error, and this IllegalAccessException in my logs:
java.lang.RuntimeException: Unable to instantiate service unjustentertainment.com.MusicService:
java.lang.IllegalAccessException: access to class not allowed
The exception you get is because the system could not init your service (call its constructor) because its not accessible.
As it says here:
...Make sure the class is
declared public...
The class you posted is not public, so make it public.
You need to make your class public.
i.e.
public class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.
To play an audio file from an SD card I'm passing a file called path to a service to start a mediaplayer playing path.
This is passing it
private void playAudio(String url) throws Exception{
Intent music = new Intent(this,MusicService.class);
music.putExtra("paths", url);
startService(music);
}
This is my service class receiving the intent.
class MusicService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
String musicFile;
#Override
public void onCreate() {
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Bundle e = intent.getExtras();
musicFile= e.getString("paths");
try {
mediaPlayer.prepare();
mediaPlayer.setDataSource(musicFile);
} catch (IllegalArgumentException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IllegalStateException i) {
// TODO Auto-generated catch block
i.printStackTrace();
} catch (IOException i) {
// TODO Auto-generated catch block
i.printStackTrace();
}
if (!mediaPlayer.isPlaying())
{
mediaPlayer.start();
}
return START_STICKY;
}
My problem is the mediaplayer isn't playing the path. I'm not sure if it's not receiving the file from the SD or not starting for some reason.
To help you debug, add some Toasts here and there in your service:
Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
Putting it strategically, this will help you see if the service is started correctly, if the service launches its methods, etc. Pinpointing errors is even more important than fixing them.
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!!!
public class PlayAudio extends BroadcastReceiver{
private Context mContext;
MediaPlayer mp;
#Override
public void onReceive(Context context, Intent intent) {
mContext = context;
mIntent = intent;
playSound("sound.mp3");
}
private void playSound(String file){
mp = MediaPlayer.create(mContext, Uri.parse("file://"+file));
if (mp.isPlaying())
{
mp.stop();
}
mp.setLooping(true);
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
I am getting an error when i check if mp is playing. How can i check if MediaPlayer(mp) is playing so that i can stop it?
First a bit of confusion in the above code
In the above code new instance of media player will get created each time you call playsound() what you need to do is instantiate mp only once in oncreate() of playaudio class and use it repeatedly.
Also if you use create to instantiate mediaplayer you prepare gets called internally you should not call it again.http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, android.net.Uri)
Check if mp is null after you do create to verify if mediaplayer instance was created successfully.