This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
i'm tring to implement In App Billing into my application. I wrote this code.
public class Settings extends PreferenceFragment {
ServiceConnection mServiceConn;
IInAppBillingService mService;
PendingIntent pending;
Intent intent;
Bundle bundle;
#Override
public void onDestroy() {
super.onDestroy();
if (mService != null) {
getActivity().unbindService(mServiceConn);
}
}
#Override
public void onCreate(Bundle savedIstanceState) {
super.onCreate(savedIstanceState);
addPreferencesFromResource(R.xml.settings);
getActivity().getActionBar().setTitle(getString(R.string.settings));
mServiceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
// TODO Auto-generated method stub
mService = IInAppBillingService.Stub.asInterface(arg1);
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mService = null;
}
};
intent = new Intent("com.android.vending.billing.InAppBillingService.BIND").setPackage("com.android.vending");
getActivity().bindService(intent, mServiceConn, Context.BIND_AUTO_CREATE);
try {
bundle = mService.getBuyIntent(3, getActivity().getPackageName(), "pro_version", "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
pending = bundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pending.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When i launch the application and open this Fragment the app crash with this error:
01-31 19:59:30.969: E/AndroidRuntime(11546): java.lang.NullPointerException: Attempt to invoke interface method 'android.os.Bundle com.android.vending.billing.IInAppBillingService.getBuyIntent(int, java.lang.String, java.lang.String, java.lang.String, java.lang.String)' on a null object reference
In the AndroidManifest obviously i've these permissions:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="com.android.vending.BILLING"/>
Your try block is called before onServiceConnected is, that's why mService is null. Move the try block inside the onServiceConnected and after the assignment like so:
mServiceConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mService = IInAppBillingService.Stub.asInterface(arg1);
try {
bundle = mService.getBuyIntent(3, getActivity().getPackageName(), "pro_version", "inapp", "bGoa+V7g/yqDXvKRqq+JTFn4uQZbPiQJo4pf9RzJ");
pending = bundle.getParcelable("BUY_INTENT");
getActivity().startIntentSenderForResult(pending.getIntentSender(), 1001, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SendIntentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mService = null;
}
};
Related
E/MediaPlayer: EventHandler handleMessage thread id is 1
E/MediaPlayer: EventHandler handleMessage thread id is 1
E/MediaPlayer: currentThread is 1, handleMessage mTimeProvider hashcode is 1112571032, mTimeProvider is android.media.MediaPlayer$TimeProvider#42507c98, msg is { when=-19ms what=7 target=android.media.MediaPlayer$EventHandler }
I get the above error when trying to play audio, any ideas why I get this error, the same code works in some places, I'm calling the static function from a fragment?
Global.playAudio("sounds/add_comment.mp3",context);
public static void playAudio(String aud, Context context) {
final MediaPlayer mp;
try {
AssetFileDescriptor fileDescriptor =
context.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepare();
mp.start();
} catch (IllegalArgumentException 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();
}
}
Let me know if this helped -
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener,AudioManager.OnAudioFocusChangeListener{
MediaPlayer mp;
AudioManager mAudioManager ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//got audio focus
playAudio("bell.mp3",this);
}
}
private void playAudio(String aud, Context context) {
try {
AssetFileDescriptor fileDescriptor =
context.getAssets().openFd(aud);
mp = new MediaPlayer();
mp.setDataSource(fileDescriptor.getFileDescriptor(),
fileDescriptor.getStartOffset(),
fileDescriptor.getLength());
fileDescriptor.close();
mp.prepareAsync();
mp.setOnPreparedListener(this);
} catch (IllegalArgumentException 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();
}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mp.start();
}
#Override
public void onAudioFocusChange(int i) {
}
}
Here, I am first trying to get the audio focus and then letting the mediaplayer do the task asynchronously.
I tried to user localbroadcastreceivers in my android service class. But when ever it runs, the onReceive method in the main activity is not getting called. I have had look at several examples and tutorials, but couldn't find the problem.
Main Activity
BroadcastReceiver receiver;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
LocalBroadcastManager.getInstance(this).registerReceiver((receiver),
new IntentFilter(TestService.COPA_MESSAGE)
);
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
super.onStop();
}
onCreate Method
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String s = intent.getStringExtra(TestService.COPA_MESSAGE);
Toast.makeText(getApplicationContext(),"Result - " + s, Toast.LENGTH_LONG).show();
System.out.println("Result - " + s);
// do something here.
}
};
Test Service Class
LocalBroadcastManager broadcaster;
static final public String COPA_RESULT = "com.controlj.copame.backend.COPAService.REQUEST_PROCESSED";
static final public String COPA_MESSAGE = "com.controlj.copame.backend.COPAService.COPA_MSG";
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Created", 1).show();
broadcaster = LocalBroadcastManager.getInstance(this);
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
super.onDestroy();
}
public void sendResult(String message) {
Intent intent = new Intent(COPA_RESULT);
if(message != null)
intent.putExtra(COPA_MESSAGE, message);
broadcaster.sendBroadcast(intent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
class HttpAsync extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String result = null;
MyDefaultHttpClient client = MyDefaultHttpClient.getInstance();
HttpPost httpPost = new HttpPost("url");
try {
List<NameValuePair> data = new ArrayList<NameValuePair>();
data.add(new BasicNameValuePair("mob_no", "0112888788"));
httpPost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse responce = client.execute(httpPost);
InputStream in = responce.getEntity().getContent();
BufferedReader br = new BufferedReader(
new InputStreamReader(in));
StringBuilder responceStr = new StringBuilder();
String responceLineStr = null;
while ((responceLineStr = br.readLine()) != null) {
responceStr.append(responceLineStr);
}
br.close();
in.close();
result = responceStr.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if ((result != null) || (result != "")){
System.out.println("Myresult"+ result);
try {
sendResult("My Test");
PushNotification(getApplicationContext());
String recData[] = result.split("#");
System.out.println("Moblile "+ recData[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
HttpAsync a = new HttpAsync();
a.execute();
return super.onStartCommand(intent, flags, startId);
}
I have an App that is receiving a video file from another App that is working as a Server. While the App is saving the file received on the socket, the video stream starts playing the file (which is under construction). In the code sample, after I press the btnStream, I press the btnPlay and App runs successfully. However, if the playing rate is greater than the download rate, an error will occur. I want to avoid this case. So I need to have a listener on the Video Playing that will pause the videoview when it predicts that this error will occur. I know a solution where if I know the video size, I can counter the bytes received and monitor how many seconds have been buffered and see if the videoview should pause or not. However, is it possible to do it without knowing the video file size? Or having two threads that depends on each other? Thanks.
Note: the VideoView used is a custom one where it can play FileDescriptor.
btnStream.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = etURL.getText().toString();
String ip = "10.0.0.24";
int port = 7878;
mct= new VideoDownloadTask(ip,port);
mct.execute();
}});
final MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(mVideoView);
Button btnPlay = (Button) findViewById(R.id.button2);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mVideoView.setVideoFD((new FileInputStream(new File("/sdcard/tempVideo.mp4")).getFD()));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mVideoView.seekTo(0);
mVideoView.start();
}
});
}
public class VideoDownloadTask extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
Socket socket=null;
VideoDownloadTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket(InetAddress.getByName(dstAddress), dstPort);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
if(socket!=null)socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
File f = new File("/sdcard/tempVideo.mp4");
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataInputStream in=null;
try {
in = new DataInputStream (socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FileOutputStream videoFile = null;
try {
videoFile = new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int len;
byte buffer[] = new byte[8192];
try {
while((len = in.read(buffer)) != -1) {
videoFile.write(buffer, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
videoFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "Done Downloading File",
Toast.LENGTH_LONG).show();
super.onPostExecute(result);
}
}
}
I applied a simple solution that resolved the problem. I am sharing it if anyone is having the same problem. The solution was simply to add an error listener to the videoView that will block the error popups and pauses the video.
mVideoView.setOnErrorListener(new OnErrorListener(){
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
statusText.setText("ERROR PLAYING VIDEO");
mVideoView.pause();
return true;
}
});
pDialog = new ProgressDialog(PlayVideoActivity.this);
pDialog.setTitle("Gajacharitra");
pDialog.setMessage("Buffering video...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
try {
// Start the MediaController
mediacontroller.setAnchorView(mVideoView);
// Get the URL from String VideoURL
Uri video = Uri.parse(mVideoURL);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(video);
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
mVideoView.pause();
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
return true;
}
});
} catch (Exception e) {
/*Log.e("Error", e.getMessage());
e.printStackTrace();*/
pDialog.dismiss();
Toast.makeText(PlayVideoActivity.this, "Can't play this video.", Toast.LENGTH_LONG).show();
finish();
}
As I can refresh the content of an activity?, for example, I have a menu and a button send me an application content that displays information online, but to go back and return again, the information is not updated.
This is my Activity.
public class Bovalpo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bovalpo);
Button buttonExit = (Button)this.findViewById(R.id.cerrar);
buttonExit.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
System.exit(0);
}
}
);
TextView myListView = (TextView) findViewById(R.id.tv);
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getPage() throws MalformedURLException, IOException {
HttpURLConnection con = (HttpURLConnection) new URL("http://www.bovalpo.com/cgi-local/xml_bcv.pl?URL=1").openConnection();
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}
private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append("Mercado: " + line + "\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
public void lanzar(View view){
Intent i = new Intent(this, xml7009.class);
startActivity(i);
}
public void lanzar3(View view){
Intent i = new Intent(this, tabla7009.class);
startActivity(i);
}
public void lanzar4(View view){
Intent i = new Intent(this, xml6503.class);
startActivity(i);
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
finish();
}
}
put your code here
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
// make your work to data bind
}
The code that fetches your data and sets list view color should be put in onResume() instead of onCreate if you want it to run each time your Activity is shown.
Simply you can put your update code in the onResume() method of the activity. OnResume() method will be called when ever you return from the other activity.
But onResume() method is often called when your activity is resume for example. If you open and dismiss the dialog then your activity will be Resume. SO if you are calling some network call in onResume then it will consume the process and Network speed.
The alternate solution is use startActivityForResult() method to receive the result from the next activity and bases of the activity result you can call your web API or any work. You can get the result of the next activity in onActivityResult() method.
But before using the startActivityForResult method ensure that the next activity will set the result by calling setResult() method.
If you want to update your data every time you came to activity, you need to set your updated values in onResume
like below
#Override
protected void onResume() {
super.onResume();
try {
myListView.setText(getPage());
if(getPage().contains("Abierto")){
myListView.setTextColor(Color.parseColor("#008000"));
}else{
myListView.setTextColor(Color.parseColor("#FF0000"));
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am looking to start a Service to keep music playing from my app when the user closes it. I have done a lot of searching around and all I am really looking for is a simple example that will allow me to start the service and music when the user presses a button. And when the user comes back to the app at some other point and presses another button then I want to bind to the service and stop the music playback. I have done a lot of searching around and I was hoping that someone could give me a clear explanation of how this all works and maybe even a code example.
to play song in Sd card using this snippet code:
public void playSong(int songIndex) {
// Play song
try {
mp.reset();
mp.setDataSource(songsListingSD.get(songIndex).get("songPath"));
mp.prepare();
mp.start();
// Displaying Song title
String songTitle = songsListingSD.get(songIndex).get("songTitle");
songTitleLabel.get().setText(songTitle);
// Changing Button Image to pause image
btnPlay.get().setImageResource(R.drawable.ic_media_pause);
// set Progress bar values
songProgressBar.get().setProgress(0);
songProgressBar.get().setMax(100);
// Updating progress bar
updateProgressBar();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
more example code for android mediaplayer run in service,you can make reference to this tutorial.
I have implemented this musi cservcie class which is working fine
public class MusicSrvice extends Service implements MediaPlayer.OnErrorListener,MediaPlayer.OnCompletionListener, MediaPlayer.OnInfoListener{
public static final String ACTION_STOP="com.example.music4u.ACTION_STOP";
public static final String ACTION_PLAY="com.example.music4u.ACTION_PLAY";
public static final String ACTION_PAUSE="com.example.music4u.ACTION_PAUSE";
private final IBinder mBinder = new ServiceBinder();
MediaPlayer mPlayer;
String path="";
private int length = 0;
private boolean isPlaying = false;
private static final int NOTIFICATION_ID = 1;
public MusicSrvice() { }
public class ServiceBinder extends Binder {
MusicSrvice getService()
{
return MusicSrvice.this;
}
}
#Override
public IBinder onBind(Intent arg0){return mBinder;}
#Override
public void onCreate (){
super.onCreate();
AudioManager amanager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
int maxVolume = amanager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
amanager.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
mPlayer=new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
// mPlayer = MediaPlayer.create(this, R.raw.jingle);
mPlayer.setOnErrorListener(this);
if(mPlayer!= null)
{
mPlayer.setLooping(true);
//mPlayer.setVolume(100,100);
}
/* mPlayer.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int
extra){
onError(mPlayer, what, extra);
return true;
}
});*/
}
#Override
public int onStartCommand (Intent intent, int flags, int startId)
{
if(intent.getExtras()!=null){
path =intent.getExtras().getString("path");
}
Context c = getApplicationContext();
if (intent != null) {
String action = intent.getAction();
if(action!=null){
// if (!TextUtils.isEmpty(action)) {
if (action.equals(ACTION_STOP)) {
pauseMusic(path);
}}
}
//}
/// path = intent.getStringExtra(EXTRA_FILENAME);
if (path == null) {
Log.w("logtag", "PlayService::onStart recording == null, returning");
//return;
}
Log.i("", "PlayService will play " + path);
try {
if(mPlayer!=null){
mPlayer.reset();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDataSource(path);
mPlayer.setLooping(false);
mPlayer.prepare();
Log.d("logtag", "PlayService player.prepare() returned");
mPlayer.start();
CustomNotification();
isPlaying = true;
Log.i("logtag", "player.start() returned");}
else
{
Log.i("logtag", "mediaplayer null");
}
//updateNotification(true);
} catch (java.io.IOException e) {
Log.e("", "PlayService::onStart() IOException attempting player.prepare()\n");
Toast t = Toast.makeText(getApplicationContext(), "PlayService was unable to start playing recording: " + e, Toast.LENGTH_LONG);
t.show();
// return;
} catch (java.lang.Exception e) {
Toast t = Toast.makeText(getApplicationContext(), "MusicPlayer was unable to start playing recording: " + e, Toast.LENGTH_LONG);
t.show();
Log.e("", "PlayService::onStart caught unexpected exception", e);
}
return START_STICKY;
}
public void pauseMusic(String path)
{
if(mPlayer.isPlaying())
{
mPlayer.pause();
length=mPlayer.getCurrentPosition();
}
else{
mPlayer.reset();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(path);
} 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();
}
mPlayer.setLooping(false);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("logtag", "PlayService player.prepare() returned");
mPlayer.start(); }
}
public void playNextSong(String path)
{
mPlayer.stop();
mPlayer.reset();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mPlayer.setDataSource(path);
} 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();
}
mPlayer.setLooping(false);
try {
mPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("logtag", "PlayService player.prepare() returned");
mPlayer.start();
}
public boolean isplaying(){
if(mPlayer!= null)
{
return mPlayer.isPlaying();}
return false;
}
public void seekto(int duration){
if(mPlayer!= null)
{
mPlayer.seekTo(duration);}
}
public int getCurrentPosition(){
if(mPlayer!= null)
{
return mPlayer.getCurrentPosition();}
return 0;
}
public int getDuration(){
if(mPlayer!= null)
{
return mPlayer.getDuration();}
return 0;
}
public void resumeMusic()
{
if(mPlayer.isPlaying()==false)
{
mPlayer.seekTo(length);
mPlayer.start();
}
}
public void stopMusic()
{
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
#Override
public void onDestroy ()
{
super.onDestroy();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
}
#Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
String message = "Sorry your system has low memory";
Notification notification = new Notification(android.R.drawable.ic_dialog_alert, message, System.currentTimeMillis());
notificationManager.notify(1, notification);
stopSelf();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(mPlayer != null)
{
try{
mPlayer.stop();
mPlayer.release();
}finally {
mPlayer = null;
}
}
return false;
}
#Override
public boolean onInfo(MediaPlayer arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onCompletion(MediaPlayer arg0) {
// TODO Auto-generated method stub
}
public void release(){
mPlayer.release();
}