Recording calls in android why this not works - android

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.

Related

Android media sound Recorder Start failed

My application got crashed whenever i press start button. Logcat says its because of start method failed. I google the error but i didn't find anything. It is giving exception at the native method Start(v);
Here is my logcat :
08-22 18:44:23.420: E/MediaRecorder(3607): start failed: -2147483648
08-22 18:44:23.420: V/MediaRecorderJNI(3607): process_media_recorder_call
08-22 18:44:23.420: W/dalvikvm(3607): threadid=1: thread exiting with uncaught exception (group=0x41234438)
08-22 18:44:23.420: E/AndroidRuntime(3607): FATAL EXCEPTION: main
08-22 18:44:23.420: E/AndroidRuntime(3607): java.lang.RuntimeException: start failed.
Here is my Code :
import java.io.File;
import java.io.IOException;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private File outputFile = null;
private AudioTrack mAudioTrack;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private Spinner sp;
private TextView text;
public SoundPool spl;
public int explosion = 0;
private Button playMod;
private int sampleRate = 8000;
private Uri newUri;
AudioManager audioManager;
int counter;
float actVolume, maxVolume, volume;
boolean loaded = false;
private static final String TAG = "SoundRecordingActivity";
String [] singers = {"Atif Aslam" , "Arijit Singh" , "Shreya Goshal"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
sp = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> adp=new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,singers);
adp.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
sp.setAdapter(adp);
// store it to sd card
//outFile = Environment.getExternalStorageDirectory().
// getAbsolutePath() + "/AudioRecord.3gpp";
File sampleDir = Environment.getExternalStorageDirectory();
try {
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
} catch (IOException e) {
Toast.makeText(this, "No Memory Card Inserted", Toast.LENGTH_LONG).show();
Log.e(TAG, "sdcard access error");
return;
}
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile.getAbsolutePath());
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
playMod = (Button)findViewById(R.id.button1);
playMod.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
playModified(v);
}
});
}
public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
/////////////////////////////////////
// addRecordingToMediaLibrary();
//////////////////////////////////////
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile.getAbsolutePath());
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You save the temporary file as type, m4a:
outputFile = File.createTempFile("sound", ".m4a", sampleDir);
but you have the wrong output format (3gp):
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
Solution:
If you'd like to save the recorded file as a 3gp format, you'd have to save the file as:
outputFile = File.createTempFile("sound", ".3gp", sampleDir);
else, If you'd like to save as an m4a format, you'd have to change the output format as follows:
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
Here's a list of the available formats
I had the same problem. Because I also have MediaPlayer, I solve this problem by the code:
mediaPlayer.setAudioStreamType(AudioManager.ADJUST_LOWER);
this solve my problem.

Android music player as a Service and show the title track,album image on UI

I tried to write the music player code in android.I want to show the current title of the song,artist and album image.
The Activity is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.PlayMusicService.LocalBinder;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Audio;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GetMusic extends Activity implements OnGestureListener {
static Handler seekhandler=new Handler();
boolean isServiceConnected=false;
PlayMusicService playServ;
static TextView tv1,tv2,tv3;
Button previous,next;static ImageView img;static GestureDetector gDetector;
int pausePressed=1;static SeekBar sb;
int currentIndex=0;Cursor cursor;GenericSongClass GSC;
static MediaPlayer mediaPlayer;static int posofaudiotrack;
private ServiceConnection conn=new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
isServiceConnected=false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
LocalBinder binder=(LocalBinder)service;
playServ=binder.getService();
isServiceConnected=true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_get_music);
gDetector= new GestureDetector(this);
tv1=(TextView)findViewById(R.id.textView1);
tv2=(TextView)findViewById(R.id.textView2);
tv3=(TextView)findViewById(R.id.textView3);
getSongs();
img=(ImageView)findViewById(R.id.imageView1);
sb=(SeekBar)findViewById(R.id.seekBar1);
try{
Intent serv = new Intent(this,PlayMusicService.class);
bindService(serv, conn, Context.BIND_AUTO_CREATE);
System.out.println("in try calling service");
startService(serv);
}
catch(Exception e){
System.out.println("Exception is"+e);
}
System.out.println("after binding");
/*
try {
playSong(0);
}
catch(Exception e){
System.out.println("Exception is"+e);
}*/
//PlayMusic p=new PlayMusic();
// p.execute();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (isServiceConnected) {
unbindService(conn);
isServiceConnected = false;
}
}
public static void mediaPlayerPause()
{
if(mediaPlayer!=null)
{
mediaPlayer.pause();
posofaudiotrack=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mediaPlayer!=null&&!mediaPlayer.isPlaying())
{
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
}
public class PlayMusic extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
getSongs();
return null;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
}
public static ArrayList<GenericSongClass> songs = null;
public void getSongs() {
Toast.makeText(getApplicationContext(), "in BindAllSongs()", Toast.LENGTH_SHORT).show();
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
final String[] projection = new String[] {
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.COMPOSER,MediaStore.Audio.Media.TITLE,MediaStore.Audio.Media.ALBUM
};
final String sortOrder = MediaStore.Audio.AudioColumns.TITLE
+ " COLLATE LOCALIZED ASC";
try {
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
cursor = getBaseContext().getContentResolver().query(uri,
projection, selection, null, sortOrder);
/* int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String s=cursor.getString(column_index);*/
// Toast.makeText(getApplicationContext(), "path is"+s, Toast.LENGTH_SHORT).show();
// System.out.println("path is"+s);
if (null == cursor) {
Log.e("error","cursor is null");
// If the Cursor is empty, the provider found no matches
} else if (cursor.getCount() < 1) {
Log.i("info","cursor count<1");
} else {
songs = new ArrayList<GenericSongClass>(cursor.getCount());
cursor.moveToFirst();
int colIndex=cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
String path = cursor.getString(colIndex);
// Toast.makeText(getApplicationContext(), "PATH IS"+path, Toast.LENGTH_SHORT).show();
System.out.println("PATH IS"+path);
while (!cursor.isAfterLast()) {
GSC = new GenericSongClass();
GSC.songTitle = cursor.getString(0);
GSC.songArtist = cursor.getString(1);
GSC.songData = cursor.getString(2);
GSC.songComposer=cursor.getString(3);
GSC.title=cursor.getString(4);
GSC.album=cursor.getString(5);
songs.add(GSC);
cursor.moveToNext();
}
// Toast.makeText(getApplicationContext(), "songs first is"+songs.get(0).songTitle, Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(), "songs length is"+songs.size(), Toast.LENGTH_SHORT).show();
mediaPlayer=new MediaPlayer();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
Log.e("I", "Media player has been loaded to memory !");
}
});
/*for(int i=0;i<songs.size();i++){
if(mediaPlayer.isPlaying())
mediaPlayer.reset();
String p=songs.get(i).songData;
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);*/
}
}
catch (Exception ex) {
Toast.makeText(getApplicationContext(), "exception is"+ex, Toast.LENGTH_SHORT).show();
Log.i("ex is",ex.toString());
} finally {
if (cursor != null) {
cursor.close();
}}
}
protected void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
protected void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
private void playSong(int index) {
// TODO Auto-generated method stub
try{
mediaPlayer.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
tv1.setText(songs.get(index).title);
tv2.setText(songs.get(index).album);
tv3.setText(songs.get(index).songArtist);
// tv3.append(songs.get(index).album);
mediaPlayer.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mediaPlayer.start();
sb.setMax(mediaPlayer.getDuration());
seekUpdation();
sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
mediaPlayer.seekTo(seekBar.getProgress());
seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
playServ.getNextSong();
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
sb.setProgress(mediaPlayer.getCurrentPosition());
seekhandler.postDelayed(run, 1000);
}
public class GenericSongClass {
String songTitle = "";
String songArtist = "";
String songData = "";
String songComposer="";
String title="";
String album="";
String isChecked = "false";
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.get_music, menu);
return true;
}
#Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onTouchEvent(MotionEvent me) {
return gDetector.onTouchEvent(me);
}
#Override
public boolean onFling(MotionEvent start, MotionEvent finish, float velocityX,
float velocityY) {
pausePressed=1;//int x=playServ.getCurrentIndex();
// TODO Auto-generated method stub
if(start.getRawX() < finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "chanegd", Toast.LENGTH_SHORT).show();
if(playServ!=null){
/* if(x==0)
x=songs.size()-1;
else{
x=currentIndex-1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getPreviousSong();}
else
System.out.println("ms null");
}
else if(start.getRawX()>finish.getRawX())
{
//Toast.makeText(getApplicationContext(), "changed on other", Toast.LENGTH_SHORT).show();
Log.d("onFLing","in onFling");
if(playServ!=null){
/*
if(x == songs.size()-1){
x=0;
}
else
{
x=x+1;
}
tv1.setText(songs.get(x).title);
tv2.setText(songs.get(x).album);
tv3.setText(songs.get(x).songArtist);
tv3.append(songs.get(x).album);*/
playServ.getNextSong();
}
else
System.out.println("ms null");
}
return true;
}
#Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
#Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
System.out.println("PAUSEPRESSED"+pausePressed);
if(pausePressed==1){
pausePressed=0;
playServ.mediaPlayerPause();
}else if(pausePressed==0){
pausePressed=1;
//mediaPlayer.seekTo(posofaudiotrack);
playServ.mediaPlayerResume();
}
return true;
}
}
and the Service is:
package com.example.getmusic;
import java.io.IOException;
import java.util.ArrayList;
import com.example.getmusic.GetMusic.GenericSongClass;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class PlayMusicService extends Service{
MediaPlayer mp;int currentIndex=0;
ArrayList<GenericSongClass> songs=GetMusic.songs;int pausePressed=1;
IBinder servbind=new LocalBinder();
public class LocalBinder extends Binder{
PlayMusicService getService()
{
return PlayMusicService.this;
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return servbind;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
mp=new MediaPlayer();
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer arg0) {
// TODO Auto-generated method stub
System.out.println("in onPrepared");
}
});
mp.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
// TODO Auto-generated method stub
pausePressed=1;
getNextSong();
}
});
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try{
System.out.println("in try");
playSong(0);
}
catch(Exception e){
System.out.println("in catch and exception is "+e.getMessage());
}
}
public void playSong(int index){
// TODO Auto-generated method stub
try{
System.out.println("in playsong");
mp.reset();
String p=songs.get(index).songData;
System.out.println("Song title is"+songs.get(1).songTitle+"artist"+songs.get(1).songArtist+"composer is"+songs.get(1).songComposer.valueOf(0)+"title is"+songs.get(1).title);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
GetMusic.tv1.setText(songs.get(index).title);
GetMusic.tv2.setText(songs.get(index).album);
GetMusic.tv3.setText(songs.get(index).songArtist);
GetMusic.tv3.append(songs.get(index).album);
mp.setDataSource(p);
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
byte[] rawArt;
Bitmap art = null;
BitmapFactory.Options bfo=new BitmapFactory.Options();
mmr.setDataSource(p);
rawArt = mmr.getEmbeddedPicture();
if (null != rawArt)
art = BitmapFactory.decodeByteArray(rawArt, 0, rawArt.length, bfo);
GetMusic.img.setImageBitmap(art);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();;
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "exception is"+e.toString(), Toast.LENGTH_SHORT).show();
Log.d("exc","exception is"+e.toString());
System.out.println("exception is"+e.toString());
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(), "prepate exception is"+e.toString(), Toast.LENGTH_SHORT).show();
System.out.println("exception is"+e.toString());
}
mp.start();
GetMusic.sb.setMax(mp.getDuration());
seekUpdation();
GetMusic.sb.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
mp.seekTo(seekBar.getProgress());
GetMusic.seekhandler.postDelayed(run, 1000);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
GetMusic.seekhandler.removeCallbacks(run);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
});
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
GetMusic.sb.setProgress(mp.getCurrentPosition());
GetMusic.seekhandler.postDelayed(run, 1000);
}
public int getCurrentIndex(){
return currentIndex;
}
public void mediaPlayerPause()
{
if(mp!=null)
{
mp.pause();
//pos=mediaPlayer.getCurrentPosition();
}
}
public void mediaPlayerResume()
{
if(mp!=null&&!mp.isPlaying())
{
mp.seekTo(mp.getCurrentPosition());
mp.start();
}
}
public void getPreviousSong()
{
if(currentIndex==0)
currentIndex=songs.size()-1;
else{
currentIndex=currentIndex-1;
}
playSong(currentIndex);
}
public void getNextSong() {
// TODO Auto-generated method stub
if(currentIndex == songs.size()-1){
currentIndex=0;
}
else
{
currentIndex=currentIndex+1;
}
playSong(currentIndex);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mp.start();
return 0;
}
#Override
public void onDestroy()
{
mp.release();
super.onDestroy();
}
}
The issue is it's playing good sometimes and sometimes it's stopping when we press back button or swiping other apps on home screen.I want to show the title track,image on UI.But with this code it's showing wrong images for some songs and for some it's even not showing the image even if the image exists.And after back screen pressed and so when we use other apps and get back to this It's showing simply TextView and normal android image.Is recreation of activity needed?Can we call Activity method from Service?How to solve the issues?Please help me.
You need background music service and communicate with Activity with message or bond activity to service, not call Activity method from service, that will cause cross process problem.
I actually opensource a Music Player with Background service, Lyric, from a business project I have wrote, you check this out:https://github.com/Wangchao0721/MusicPlayer
But I haven't got time to fill Readme for it, just check MediaPlayerActivity.java in activity package, you gonna know how to use this.

How to stop the Background running service in android?

Intent svc=new Intent(BeapSoundActivity.this, BackgroundService.class);
pendingIntent = PendingIntent.getService(BeapSoundActivity.this, 0, svc, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
I am using the above code to start my service in mt onCreate(),
I just want to stop this service when I click a Button to change my Activity
I used this line in my Button Click
stopService(new Intent(BeapSoundActivity.this, BackgroundService.class));
But it didnt worked for me
Here is my BackGroundService class
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
public class BackgroundService extends Service{
// private static final String TAG = null;
// MediaPlayer player;
MediaPlayer mMediaPlayer;
String strResponse;
int i=0;
static {
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
mMediaPlayer = new MediaPlayer();
Log.e("Oncreate","oncreate");
}
public int onStartCommand(Intent intent, int flags, int startId) {
// player.start();
Log.e("Onstartcommand","onstartcommand");
pendingCount();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
// super.onStart(intent,startId);
Log.e("Onstart","onstart");
// pendingCount();
}
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() {
}
public void playSound(Context context) throws IllegalArgumentException, SecurityException, IllegalStateException,
IOException {
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
// mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(context, soundUri);
final AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
}
public void pendingCount(){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://mybusinessapp2.testshell.net/api/Orders");
post.addHeader("UserName", "info#mybusinessapp.com");
post.addHeader("Password", "c7d7cdf598be88a21a477842ebfa5ca5");
ResponseHandler<String> resHandler = new BasicResponseHandler();
String post_response = null;
try {
post_response = httpClient.execute(post,resHandler);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("resp",post_response);
try{
JSONObject jobject=new JSONObject(post_response);
strResponse= jobject.getString("Count");
}
catch(Exception e){
e.printStackTrace();
}
Log.e("tv",""+BeapSoundActivity. pending_number);
try{
BeapSoundActivity. pending_number.setText(strResponse);
// int pending=Integer.parseInt(BeapSoundActivity.pending_number.getText().toString());
// Log.e("counter",""+pending);
}
catch(NullPointerException e){
e.printStackTrace();
}
int pending=Integer.parseInt( strResponse);
if(pending==0){
mMediaPlayer.stop();
mMediaPlayer = new MediaPlayer();
}
if(pending>0){
try {
playSound(BackgroundService.this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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();
}
}
}
}
Please help me in solving this issue
Thanks in advance
you created an alarm that start your service every 10 seconds. did you canceled it before stopping the service? (if not, use (AlarmManager)getSystemService(Context.ALARM_SERVICE).cancel)

send audio file to server after recording in android

Thanks in advance for spent Ur time on my app...
I have an application in which I require to create an audio file after clicking ona button named "RECORD" and send this file to server. The audio file must be send in any android supported audio format.
How can I achieve this...
Code For Recording in Android
main.java:
package com.example.audiosend;
import android.os.Bundle;
import android.app.Activity;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private MediaRecorder myRecorder;
private MediaPlayer myPlayer;
private String outputFile = null;
private Button startBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
// store it to sd card
outputFile = Environment.getExternalStorageDirectory().
getAbsolutePath() + "/MyAppRecording.3gpp"; //this is the folder in which your Audio file willl save
myRecorder = new MediaRecorder();
myRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
myRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
myRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
myRecorder.setOutputFile(outputFile);
startBtn = (Button)findViewById(R.id.start);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
start(v);
}
});
stopBtn = (Button)findViewById(R.id.stop);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stop(v);
}
});
playBtn = (Button)findViewById(R.id.play);
playBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
play(v);
}
});
stopPlayBtn = (Button)findViewById(R.id.stopPlay);
stopPlayBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopPlay(v);
}
});
}
public void start(View view){
try {
myRecorder.prepare();
myRecorder.start();
} catch (IllegalStateException e) {
// start:it is called before prepare()
// prepare: it is called after start() or before setOutputFormat()
e.printStackTrace();
} catch (IOException e) {
// prepare() fails
e.printStackTrace();
}
text.setText("Recording Point: Recording");
startBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
myRecorder.stop();
myRecorder.release();
myRecorder = null;
stopBtn.setEnabled(false);
playBtn.setEnabled(true);
text.setText("Recording Point: Stop recording");
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
// it is called before start()
e.printStackTrace();
} catch (RuntimeException e) {
// no valid audio/video data has been received
e.printStackTrace();
}
}
public void play(View view) {
try{
myPlayer = new MediaPlayer();
myPlayer.setDataSource(outputFile);
myPlayer.prepare();
myPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
text.setText("Recording Point: Playing");
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (myPlayer != null) {
myPlayer.stop();
myPlayer.release();
myPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
text.setText("Recording Point: Stop playing");
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

WARN/AudioFlinger(33): write blocked for 76 msecs, 7773 delayed writes, thread 0xb3f0

I have created an intent service to start the music for my app in the background.
It is working, but my log-cat is flooded with the messages:
09-14 16:46:30.117: WARN/AudioFlinger(33): write blocked for 76 msecs, 7773 delayed writes, thread 0xb3f0
and nothing else is getting Logged.
Here is my IntentService:
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;
}
}
}
Permissions are needed. Put these in AndroidManifest.xml:
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
I tested it under android emulator 2.2 so my minSdkVersion is 8.

Categories

Resources