FATAL EXCEPTION: main ; Error receiving broadcast Intent - android

My code seems fine but suddenly after cleaning up my code i started reviving a run time error please help :
Error Log :
05-04 02:13:13.556: E/MediaPlayer(16609): start called in state 4
05-04 02:13:13.556: E/MediaPlayer(16609): error (-38, 0)
05-04 02:13:13.556: E/MediaPlayer(16609): Error (-38,0)
05-04 02:13:13.558: D/AndroidRuntime(16609): Shutting down VM
05-04 02:13:13.558: W/dalvikvm(16609): threadid=1: thread exiting with uncaught exception (group=0x41c88d40)
05-04 02:13:13.564: E/AndroidRuntime(16609): FATAL EXCEPTION: main
05-04 02:13:13.564: E/AndroidRuntime(16609): Process: com.ayush.mymusicplayer, PID: 16609
05-04 02:13:13.564: E/AndroidRuntime(16609): java.lang.RuntimeException: Error receiving broadcast Intent { act=com.ayush.mymusicplayer.seekprogress flg=0x10 (has extras) } in com.ayush.mymusicplayer.MyMainActivity$1#42553a80
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:778)
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.os.Handler.handleCallback(Handler.java:733)
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.os.Handler.dispatchMessage(Handler.java:95)
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.os.Looper.loop(Looper.java:136)
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.app.ActivityThread.main(ActivityThread.java:5102)
05-04 02:13:13.564: E/AndroidRuntime(16609): at java.lang.reflect.Method.invokeNative(Native Method)
05-04 02:13:13.564: E/AndroidRuntime(16609): at java.lang.reflect.Method.invoke(Method.java:515)
05-04 02:13:13.564: E/AndroidRuntime(16609): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-04 02:13:13.564: E/AndroidRuntime(16609): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-04 02:13:13.564: E/AndroidRuntime(16609): at dalvik.system.NativeStart.main(Native Method)
05-04 02:13:13.564: E/AndroidRuntime(16609): Caused by: java.lang.NumberFormatException: Invalid int: "null"
05-04 02:13:13.564: E/AndroidRuntime(16609): at java.lang.Integer.invalidInt(Integer.java:137)
05-04 02:13:13.564: E/AndroidRuntime(16609): at java.lang.Integer.parseInt(Integer.java:354)
05-04 02:13:13.564: E/AndroidRuntime(16609): at java.lang.Integer.parseInt(Integer.java:331)
05-04 02:13:13.564: E/AndroidRuntime(16609): at com.ayush.mymusicplayer.MyMainActivity.updateUI(MyMainActivity.java:356)
05-04 02:13:13.564: E/AndroidRuntime(16609): at com.ayush.mymusicplayer.MyMainActivity.access$0(MyMainActivity.java:352)
05-04 02:13:13.564: E/AndroidRuntime(16609): at com.ayush.mymusicplayer.MyMainActivity$1.onReceive(MyMainActivity.java:348)
05-04 02:13:13.564: E/AndroidRuntime(16609): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:768)
05-04 02:13:13.564: E/AndroidRuntime(16609): ... 9 more
05-04 02:13:18.279: I/Process(16609): Sending signal. PID: 16609 SIG: 9
MyMainActivity : (Error seems to be pointing the reviver - "broadcastReceiver" in this class which receive the info for seekbar ! the error occurs when i start playSong() )
public class MyMainActivity extends Activity implements OnSeekBarChangeListener {
private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
private SeekBar songProgressBar;
private int seekMax;
private int seekProgress;
private static int songEnded = 0;
boolean mBroadcastIsRegistered;
private int seekPos;
private SongsManager songManager;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0;
private boolean isShuffle = false;
private boolean isRepeat = false;
private boolean startedPlaying = false;
private boolean paused = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
Intent serviceIntent;
// Broadcasting
Intent broadcastStateIntent;
public static final String BROADCASTING = "com.ayush.mymusicplayer.broadcasting";
// --Set up constant ID for broadcast of seekbar position--
public static final String BROADCAST_SEEKBAR = "com.ayush.mymusicplayer.sendseekbar";
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player);
try {
// All player buttons
btnPlay = (ImageButton) findViewById(R.id.btnPlay);
btnForward = (ImageButton) findViewById(R.id.btnForward);
btnBackward = (ImageButton) findViewById(R.id.btnBackward);
btnNext = (ImageButton) findViewById(R.id.btnNext);
btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
songTitleLabel = (TextView) findViewById(R.id.songTitle);
songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
songManager = new SongsManager();
utils = new Utilities();
// --- set up seekbar intent for broadcasting new position to
// service ---
intent = new Intent(BROADCAST_SEEKBAR);
broadcastStateIntent = new Intent(BROADCASTING);
serviceIntent = new Intent(this, myPlayService.class);
// Getting all songs list
songsList = songManager.getPlayList();
// set the starting title song
songTitleLabel.setText(songsList.get(0).get("songTitle"));
// Listeners
songProgressBar.setOnSeekBarChangeListener(this);
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check for already playing
if (startedPlaying == false && paused == false) {
// Changing button image to pause button
btnPlay.setImageResource(R.drawable.btn_pause);
playSong(currentSongIndex);
startedPlaying = true;
paused = false;
} else if (startedPlaying == false && paused == true) {
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_pause);
resumingBroadcast();
paused = false;
startedPlaying = true;
}
else if (startedPlaying == true && paused == false) {
// Changing button image to play button
btnPlay.setImageResource(R.drawable.btn_play);
pausingBroadcast();
paused = true;
startedPlaying = false;
}
}
});
/**
* Forward button click event Forwards song specified seconds
* */
btnForward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if seekForward time is lesser than song duration
if (seekProgress + seekForwardTime <= seekMax) {
// forward song
seekPos = seekProgress + seekForwardTime;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
} else {
// forward to end position
seekPos = seekMax;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
});
/**
* Backward button click event Backward song to specified seconds
* */
btnBackward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if seekBackward time is greater than 0 sec
if (seekProgress - seekBackwardTime >= 0) {
// forward song
seekPos = seekProgress + seekBackwardTime;
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
} else {
// backward to starting position
intent.putExtra("seekpos", 0);
sendBroadcast(intent);
}
}
});
/**
* Button Click event for Play list click event Launches list
* activity which displays list of songs
* */
btnPlaylist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(),
PlayListActivity.class);
startActivityForResult(i, 100);
}
});
/**
* Next button click event Plays next song by taking
* currentSongIndex + 1
* */
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// check if next song is there or not
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
});
/**
* Back button click event Plays previous song by currentSongIndex -
* 1
* */
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
if (currentSongIndex > 0) {
playSong(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
playSong(songsList.size() - 1);
currentSongIndex = songsList.size() - 1;
}
}
}
});
/**
* Button Click event for Repeat button Enables repeat flag to true
* */
btnRepeat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isRepeat) {
isRepeat = false;
Toast.makeText(getApplicationContext(),
"Repeat is OFF", Toast.LENGTH_SHORT).show();
btnRepeat.setImageResource(R.drawable.btn_repeat);
} else {
// make repeat to true
isRepeat = true;
Toast.makeText(getApplicationContext(), "Repeat is ON",
Toast.LENGTH_SHORT).show();
// make shuffle to false
isShuffle = false;
btnRepeat
.setImageResource(R.drawable.btn_repeat_focused);
btnShuffle.setImageResource(R.drawable.btn_shuffle);
}
}
});
/**
* Button Click event for Shuffle button Enables shuffle flag to
* true
* */
btnShuffle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (isShuffle) {
isShuffle = false;
Toast.makeText(getApplicationContext(),
"Shuffle is OFF", Toast.LENGTH_SHORT).show();
btnShuffle.setImageResource(R.drawable.btn_shuffle);
} else {
// make repeat to true
isShuffle = true;
Toast.makeText(getApplicationContext(),
"Shuffle is ON", Toast.LENGTH_SHORT).show();
// make shuffle to false
isRepeat = false;
btnShuffle
.setImageResource(R.drawable.btn_shuffle_focused);
btnRepeat.setImageResource(R.drawable.btn_repeat);
}
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
/**
* Receiving song index from playlist view and play the song
* */
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 100) {
currentSongIndex = data.getExtras().getInt("songIndex");
// play selected song
playSong(currentSongIndex);
}
}
// -- onPause, unregister broadcast receiver. To improve, also save screen data ---
#Override
protected void onPause() {
// Unregister broadcast receiver
if (mBroadcastIsRegistered) {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
}
super.onPause();
}
// -- onResume register broadcast receiver. To improve, retrieve saved screen data ---
#Override
protected void onResume() {
// Register broadcast receiver
if (!mBroadcastIsRegistered) {
registerReceiver(broadcastReceiver, new IntentFilter(
myPlayService.BROADCAST_ACTION));
mBroadcastIsRegistered = true;
}
super.onResume();
}
// -- Broadcast Receiver to update position of seekbar from service --
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent serviceIntent) {
updateUI(serviceIntent);
}
};
private void updateUI(Intent serviceIntent) {
String counter = serviceIntent.getStringExtra("counter");
String mediamax = serviceIntent.getStringExtra("mediamax");
String strSongEnded = serviceIntent.getStringExtra("song_ended");
seekProgress = Integer.parseInt(counter);
seekMax = Integer.parseInt(mediamax);
songEnded = Integer.parseInt(strSongEnded);
songProgressBar.setMax(seekMax);
songProgressBar.setProgress(seekProgress);
// Displaying Total Duration time
songTotalDurationLabel.setText("" + utils.milliSecondsToTimer(seekMax));
// Displaying time completed playing
songCurrentDurationLabel.setText(""
+ utils.milliSecondsToTimer(seekProgress));
if (songEnded == 1) {
// check for repeat is ON or OFF
if (isRepeat) {
// repeat is on play same song again
playSong(currentSongIndex);
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
playSong(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songsList.size() - 1)) {
playSong(currentSongIndex + 1);
currentSongIndex = currentSongIndex + 1;
} else {
// play first song
playSong(0);
currentSongIndex = 0;
}
}
}
}
// Send a message to Server to pause
private void pausingBroadcast() {
// Log.v(TAG, "BufferCompleteSent");
broadcastStateIntent.putExtra("Broadcasting", "0");
paused = true;
btnPlay.setImageResource(R.drawable.btn_play);
sendBroadcast(broadcastStateIntent);
}
// Send a message to Server to resume
private void resumingBroadcast() {
broadcastStateIntent.putExtra("Broadcasting", "1");
paused = false;
btnPlay.setImageResource(R.drawable.btn_pause);
sendBroadcast(broadcastStateIntent);
}
// Function to play a song
public void playSong(int songIndex) {
stopMyPlayService();
paused = false;
startedPlaying = true;
serviceIntent.putExtra("currentSongIndex", songIndex);
// -- Register receiver for seekbar--
registerReceiver(broadcastReceiver, new IntentFilter(
myPlayService.BROADCAST_ACTION));
mBroadcastIsRegistered = true;
try {
startService(serviceIntent);
// Displaying Song title
String songTitle = songsList.get(songIndex).get("songTitle");
songTitleLabel.setText(songTitle);
// Changing Button Image to pause image
btnPlay.setImageResource(R.drawable.btn_pause);
// set Progress bar values
songProgressBar.setProgress(0);
songProgressBar.setMax(100);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void stopMyPlayService() {
// --Unregister broadcastReceiver for seekbar
if (mBroadcastIsRegistered) {
try {
unregisterReceiver(broadcastReceiver);
mBroadcastIsRegistered = false;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(
getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
try {
stopService(serviceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
e.getClass().getName() + " " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
// --- When user manually moves seekbar, broadcast new position to service
#Override
public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
seekPos = sb.getProgress();
intent.putExtra("seekpos", seekPos);
sendBroadcast(intent);
}
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
}
myPlayService : (the class which is broadcasting messages)
public class myPlayService extends Service implements OnCompletionListener,
OnPreparedListener, OnSeekCompleteListener, OnErrorListener {
// Media Player
private MediaPlayer mp;
private int currentSongIndex;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
private SongsManager songManager;
// Pausing when phone call
private boolean isPausedInCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
// Declare headsetSwitch variable
private int headsetSwitch = 1;
// ---Variables for seekbar processing---
Intent seekIntent;
String sntSeekPos;
int intSeekPos;
int mediaPosition;
int mediaMax;
private final Handler handler = new Handler();
private int songEnded = 0;
public static final String BROADCAST_ACTION = "com.ayush.mymusicplayer.seekprogress";
public void onCreate() {
// ---Set up intent for seekbar broadcast ---
seekIntent = new Intent(BROADCAST_ACTION);
// Register headset receiver
registerReceiver(headsetReceiver, new IntentFilter(
Intent.ACTION_HEADSET_PLUG));
songManager = new SongsManager();
songsList = songManager.getPlayList();
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnSeekCompleteListener(this);
mp.setOnErrorListener(this);
mp.reset();
}
public int onStartCommand(Intent intent, int flags, int startId) {
// ---Set up receiver for State change ---
registerReceiver(broadcastActivityReceiver, new IntentFilter(
MyMainActivity.BROADCASTING));
// ---Set up receiver for seekbar change ---
registerReceiver(broadcastReceiver, new IntentFilter(
MyMainActivity.BROADCAST_SEEKBAR));
// Manage incoming phone calls during playback. Pause mp on incoming,
// resume on hangup.
// -----------------------------------------------------------------------------------
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mp != null) {
pauseMedia();
isPausedInCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mp != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
// Getting song Index from MyMainActivity
currentSongIndex = intent.getExtras().getInt("currentSongIndex");
mp.reset();
if (!mp.isPlaying()) {
try {
mp.setDataSource(songsList.get(currentSongIndex)
.get("songPath"));
mp.prepareAsync();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
// --- Set up seekbar handler ---
setupHandler();
return START_STICKY;
}
// If headset gets unplugged, stop music and service.
private BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
private boolean headsetConnected = false;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (intent.hasExtra("state")) {
if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
headsetConnected = false;
headsetSwitch = 0;
} else if (!headsetConnected
&& intent.getIntExtra("state", 0) == 1) {
headsetConnected = true;
headsetSwitch = 1;
}
}
switch (headsetSwitch) {
case (0):
pauseMedia();
break;
case (1):
playMedia();
break;
}
}
};
// ---Send seekbar info to activity----
private void setupHandler() {
handler.removeCallbacks(sendUpdatesToUI);
handler.postDelayed(sendUpdatesToUI, 250); // 0.25 second
}
private Runnable sendUpdatesToUI = new Runnable() {
public void run() {
LogMediaPosition();
handler.postDelayed(this, 250); // 0.25 seconds
}
};
private void LogMediaPosition() {
if (mp.isPlaying()) {
mediaPosition = mp.getCurrentPosition();
mediaMax = mp.getDuration();
seekIntent.putExtra("counter", String.valueOf(mediaPosition));
seekIntent.putExtra("mediamax", String.valueOf(mediaMax));
seekIntent.putExtra("song_ended", String.valueOf(songEnded));
sendBroadcast(seekIntent);
}
}
// --Receive seekbar position if it has been changed by the user in the
// activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateSeekPos(intent);
}
};
// Update seek position from Activity
public void updateSeekPos(Intent intent) {
int seekPos = intent.getIntExtra("seekpos", 0);
if (mp.isPlaying()) {
handler.removeCallbacks(sendUpdatesToUI);
mp.seekTo(seekPos);
setupHandler();
}
}
// Play Song After Complition !
#Override
public void onSeekComplete(MediaPlayer mp) {
if (!mp.isPlaying()) {
playMedia();
}
}
public void onPrepared(MediaPlayer arg0) {
// Send a message to activity to end progress dialogue
playMedia();
}
// Set up broadcast receiver
private BroadcastReceiver broadcastActivityReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent broadcastIntent) {
String broadcastValue = broadcastIntent
.getStringExtra("Broadcasting");
int broadcastIntValue = Integer.parseInt(broadcastValue);
switch (broadcastIntValue) {
case 0:
pauseMedia();
break;
case 1:
playMedia();
break;
}
}
};
public void pauseMedia() {
if (mp.isPlaying()) {
mp.pause();
}
}
public void playMedia() {
if (!mp.isPlaying()) {
mp.start();
}
}
#Override
public void onCompletion(MediaPlayer arg0) {
seekIntent.putExtra("song_ended", "1");
sendBroadcast(seekIntent);
stopSelf();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mp != null) {
if (mp.isPlaying()) {
mp.stop();
}
mp.reset();
mp.release();
}
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_NONE);
}
// Stop the seekbar handler from sending updates to UI
handler.removeCallbacks(sendUpdatesToUI);
unregisterReceiver(headsetReceiver);
// Unregister seekbar receiver
unregisterReceiver(broadcastReceiver);
unregisterReceiver(broadcastActivityReceiver);
stopSelf();
}
// ---Error processing ---
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Toast.makeText(this,
"MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Toast.makeText(this, "MEDIA ERROR SERVER DIED " + extra,
Toast.LENGTH_SHORT).show();
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Toast.makeText(this, "MEDIA ERROR UNKNOWN " + extra,
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
Thanks In Advance ! :)

See this part in the error message:
NumberFormatException: Invalid int: "null"
you seem to try to parse the String "null" to an int. This is not possible and will therefore throw NumberFormatException.

Related

How can i bind my media player activity with existing media player service?

I know similar kind of question has been asked before, but none of them are helping me. I am building a music player in which I want to connect my Music through my music player like play, pause etc. Currently, media player service is connected with playlist activity but I have custom designed my media player and I am not able to connect it to the service class.
my MusicPlayer Activity is like this:
public class MusicPlayer extends AppCompatActivity implements PlaylistFragment.OnFragmentInteractionListener{
public static final String Broadcast_PLAY_NEW_AUDIO = "com.example.anuj.musicmetest.PlayNewAudio";
ImageView buttonPlayToggle;
MediaPlayer mediaPlayer;
MediaPlayerService player;
boolean serviceBound = false;
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Music Player");
buttonPlayToggle = (ImageView) findViewById(R.id.button_play_toggle);
buttonPlayToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
updatePlayToggle(true);
mediaPlayer.pause();
} else {
updatePlayToggle(false);
mediaPlayer.start();
}
}
});
if (!serviceBound) {
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
public void updatePlayToggle(boolean play) {
buttonPlayToggle.setImageResource(play ? R.drawable.ic_pause : R.drawable.ic_play);
}
My ServicecClass is like this:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
public static final String ACTION_PLAY = "com.example.anuj.musicmetest.ACTION_PLAY";
public static final String ACTION_PAUSE = "com.example.anuj.musicmetest.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "com.example.anuj.musicmetest.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "com.example.anuj.musicmetest.ACTION_NEXT";
public static final String ACTION_STOP = "com.example.anuj.musicmetest.ACTION_STOP";
private MediaPlayer mediaPlayer;
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
private static final int NOTIFICATION_ID = 101;
//Used to pause/resume MediaPlayer
private int resumePosition;
//AudioFocus
private AudioManager audioManager;
// Binder given to clients
private final IBinder iBinder = new LocalBinder();
private ArrayList<Audio> audioList;
private int audioIndex = -1;
private Audio activeAudio; //an object on the currently playing audio
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
/**
* Service lifecycle methods
*/
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
callStateListener();
//ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
registerBecomingNoisyReceiver();
//Listen for new Audio to play -- BroadcastReceiver
register_playNewAudio();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Load data from SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
audioList = storage.loadAudio();
audioIndex = storage.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
//Request audio focus
if (!requestAudioFocus()) {
//Could not gain focus
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlaybackStatus.PLAYING);
}
//Handle Intent action from MediaSession.TransportControls
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
mediaSession.release();
removeNotification();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.release();
}
removeAudioFocus();
//Disable the PhoneStateListener
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
//unregister BroadcastReceivers
unregisterReceiver(becomingNoisyReceiver);
unregisterReceiver(playNewAudio);
//clear cached playlist
new StorageUtil(getApplicationContext()).clearCachedAudioPlaylist();
}
/**
* Service Binder
*/
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of LocalService so clients can call public methods
return MediaPlayerService.this;
}
}
/**
* MediaPlayer callback methods
*/
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
}
#Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
stopMedia();
removeNotification();
//stop the service
stopSelf();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public boolean onInfo(MediaPlayer mp, int what, int extra) {
//Invoked to communicate some info
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
playMedia();
}
#Override
public void onSeekComplete(MediaPlayer mp) {
//Invoked indicating the completion of a seek operation.
}
#Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* AudioFocus
*/
private boolean requestAudioFocus() {
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
//Focus gained
return true;
}
//Could not gain focus
return false;
}
private boolean removeAudioFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
audioManager.abandonAudioFocus(this);
}
/**
* MediaPlayer actions
*/
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();//new MediaPlayer instance
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// Set the data source to the mediaFile location
mediaPlayer.setDataSource(activeAudio.getLocalData());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
private void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
private void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
}
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
}
}
private void skipToNext() {
if (audioIndex == audioList.size() - 1) {
//if last in playlist
audioIndex = 0;
activeAudio = audioList.get(audioIndex);
} else {
//get next in playlist
activeAudio = audioList.get(++audioIndex);
}
//Update stored index
new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
//reset mediaPlayer
mediaPlayer.reset();
initMediaPlayer();
}
private void skipToPrevious() {
if (audioIndex == 0) {
//if first in playlist
//set index to the last of audioList
audioIndex = audioList.size() - 1;
activeAudio = audioList.get(audioIndex);
} else {
//get previous in playlist
activeAudio = audioList.get(--audioIndex);
}
//Update stored index
new StorageUtil(getApplicationContext()).storeAudioIndex(audioIndex);
stopMedia();
//reset mediaPlayer
mediaPlayer.reset();
initMediaPlayer();
}
/**
* ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs
*/
private BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//pause audio on ACTION_AUDIO_BECOMING_NOISY
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
};
private void registerBecomingNoisyReceiver() {
//register after getting audio focus
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(becomingNoisyReceiver, intentFilter);
}
/**
* Handle PhoneState changes
*/
private void callStateListener() {
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//Starting listening for PhoneState changes
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//if at least one call exists or the phone is ringing
//pause the MediaPlayer
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
ongoingCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (ongoingCall) {
ongoingCall = false;
resumeMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
// Listen for changes to the device call state.
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* MediaSession and Notification actions
*/
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
// Create a new MediaSession
mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
//Set mediaSession's MetaData
updateMetaData();
// Attach Callback to receive MediaSession updates
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
#Override
public void onSkipToNext() {
super.onSkipToNext();
skipToNext();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
skipToPrevious();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
#Override
public void onStop() {
super.onStop();
removeNotification();
//Stop the service
stopSelf();
}
#Override
public void onSeekTo(long position) {
super.onSeekTo(position);
}
});
}
private void updateMetaData() {
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, activeAudio.getLocalArtist())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getLocalAlbum())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getLocalTitle())
.build());
}
private void buildNotification(PlaybackStatus playbackStatus) {
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
PendingIntent play_pauseAction = null;
//Build a new notification according to the current state of the MediaPlayer
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
//create the pause action
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
//create the play action
play_pauseAction = playbackAction(0);
}
// Create a new Notification
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
// Hide the timestamp
.setShowWhen(false)
// Set the Notification style
.setStyle(new NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compat view
.setShowActionsInCompactView(0, 1, 2))
// Set the Notification color
.setColor(getResources().getColor(R.color.colorAccent))
// Set the large and small icons
.setSmallIcon(android.R.drawable.stat_sys_headset)
// Set Notification content information
.setContentText(activeAudio.getLocalArtist())
.setContentTitle(activeAudio.getLocalAlbum())
.setContentInfo(activeAudio.getLocalTitle())
// Add playback actions
.addAction(android.R.drawable.ic_media_previous, "previous", playbackAction(3))
.addAction(notificationAction, "pause", play_pauseAction)
.addAction(android.R.drawable.ic_media_next, "next", playbackAction(2));
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent playbackAction(int actionNumber) {
Intent playbackAction = new Intent(this, MediaPlayerService.class);
switch (actionNumber) {
case 0:
// Play
playbackAction.setAction(ACTION_PLAY);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 1:
// Pause
playbackAction.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 2:
// Next track
playbackAction.setAction(ACTION_NEXT);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 3:
// Previous track
playbackAction.setAction(ACTION_PREVIOUS);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
default:
break;
}
return null;
}
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
} else if (actionString.equalsIgnoreCase(ACTION_NEXT)) {
transportControls.skipToNext();
} else if (actionString.equalsIgnoreCase(ACTION_PREVIOUS)) {
transportControls.skipToPrevious();
} else if (actionString.equalsIgnoreCase(ACTION_STOP)) {
transportControls.stop();
}
}
/**
* Play new Audio
*/
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get the new media index form SharedPreferences
audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
//A PLAY_NEW_AUDIO action received
//reset mediaPlayer to play the new Audio
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void register_playNewAudio() {
//Register playNewMedia receiver
IntentFilter filter = new IntentFilter(FragmentRight.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
And my Playlist fragment is like this:
public class FragmentRight extends Fragment {
public static final String Broadcast_PLAY_NEW_AUDIO = "com.example.anuj.musicmetest.PlayNewAudio";
private OnFragmentInteractionListener mListener;
ArrayList<Audio> localList;
TextView nameView;
private MediaPlayerService mediaPlayer;
boolean serviceBound = false;
public FragmentRight() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_right, container, false);
nameView = (TextView) rootView.findViewById(R.id.name1);
loadAudio();
RecyclerView recyclerView1 = (RecyclerView) rootView.findViewById(R.id.recycler_view1);
LocalListAdapter localListAdapteradapter = new LocalListAdapter(getActivity().getApplication(), localList);
recyclerView1.setAdapter(localListAdapteradapter);
recyclerView1.setLayoutManager(new LinearLayoutManager(getActivity().getApplication()));
recyclerView1.addOnItemTouchListener(new CustomTouchListener(getActivity(), new onItemClickListener() {
#Override
public void onClick(View view, int index) {
playAudio(index);
Intent intent = new Intent(getActivity(), MusicPlayer.class);
startActivity(intent);
}
}));
return rootView;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
mediaPlayer = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
private void playAudio(int audioIndex) {
//Check is service is active
if (!serviceBound) {
//Store Serializable audioList to SharedPreferences
StorageUtil storage = new StorageUtil(getActivity().getApplicationContext());
storage.storeAudio(localList);
storage.storeAudioIndex(audioIndex);
Intent playerIntent = new Intent(getActivity(), MediaPlayerService.class);
getActivity().startService(playerIntent);
getActivity().bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Store the new audioIndex to SharedPreferences
StorageUtil storage = new StorageUtil(getActivity().getApplicationContext());
storage.storeAudioIndex(audioIndex);
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
getActivity().sendBroadcast(broadcastIntent);
}
}
private void loadAudio() {
ContentResolver contentResolver = getActivity().getContentResolver();
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
Cursor cursor = contentResolver.query(uri, null, selection, null, sortOrder);
if (cursor != null && cursor.getCount() > 0) {
localList = new ArrayList<>();
while (cursor.moveToNext()) {
String localData = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
String localTitle = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String localAlbum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String localArtist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
// Save to audioList
localList.add(new Audio(localData, localTitle, localAlbum, localArtist));
}
}
cursor.close();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
#Override
public void onDestroy() {
super.onDestroy();
if (serviceBound) {
getContext().unbindService(serviceConnection);
//service is active
mediaPlayer.stopSelf();
}
}

Null pointer exception on calling method of a service class from an activity class [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to invoke method of a service class i.e getDur() from an activity class method i.e startPlay() but I am getting Null Pointer Exception. Below is the code of the project. I have also added some Log statements but nothing gets printed on the logs too
Herre I am trying to bind service class with activity class, if there is any other way by which I can call method of service class from activity class then please tell me.
songPlay.java
Imports *
public class songPlay extends AppCompatActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private TextView songName = null;
private TextView songDurationCurrent = null;
private TextView songDurationTotal = null;
private TextView songArtistFile = null;
private SeekBar seekbar = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private Drawable clipArt = null;
private ImageView albumCover = null;
MusicService musicService;
boolean mBound = false;
private boolean isStarted = false;
private boolean isMoveingSeekBar = false;
String songId="", songTitle="", songArtist="", songPath="";
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onStart() {
super.onStart();
Log.v("Check", "OnStart");
Intent intent = new Intent(this, MusicService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song_play);
Intent intent = getIntent();
if (intent != null && intent.hasExtra("SONG_ID")) {
songId = intent.getStringExtra("SONG_ID");
songTitle = intent.getStringExtra("SONG_TITLE");
songArtist = intent.getStringExtra("SONG_ARTIST");
songPath = intent.getStringExtra("SONG_PATH");
songTitle = songTitle.replaceAll("\\s*\\([^\\)]*\\)\\s*", "");
songTitle = songTitle.replaceAll("\\[.*?\\]", "");
songArtist = songArtist.replaceAll("\\s*\\([^\\)]*\\)\\s*", "");
songName = (TextView) findViewById(R.id.selectedfile);
songName.setText(songTitle);
songArtistFile = (TextView) findViewById(R.id.selectedfile_artistname);
songArtistFile.setText(songArtist);
songDurationCurrent = (TextView) findViewById(R.id.duration_current);
songDurationTotal = (TextView) findViewById(R.id.duration_total);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
albumCover = (ImageView) findViewById(R.id.cover);
String selection = MediaStore.Audio.Media._ID + " = "+songId+"";
Cursor cursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[] {
MediaStore.Audio.Media._ID, MediaStore.Audio.Media.ALBUM_ID},
selection, null, null);
if (cursor.moveToFirst()) {
long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
try {
albumCover.setImageURI(albumArtUri);
}
catch (Exception e) {
Log.e("Check", "Not Found");
}
}
cursor.close();
seekbar.setOnSeekBarChangeListener(seekBarChanged);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
start();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
isStarted = false;
}
private void start() {
startService(new Intent(getApplicationContext(), MusicService.class).putExtra("songPath", songPath));
startPlay();
}
private void startPlay() {
isStarted = true;
seekbar.setProgress(0);
seekbar.setMax(musicService.getDur());
long millis = musicService.getDur();
long second = (millis / 1000) % 60;
long minute = (millis / (1000 * 60)) % 60;
long hour = (millis / (1000 * 60 * 60)) % 24;
String temp="",a="",b="",c="";
if(hour==0)
a = "00";
else if(hour<=9 && hour>0)
a = "0" + String.valueOf(hour);
else
a = String.valueOf(hour);
if(minute==0)
b = "00";
else if(minute<=9 && minute>0)
b = "0" + String.valueOf(minute);
else
b = String.valueOf(minute);
if(second==0)
c = "00";
else if(second<=9 && second>0)
c = "0" + String.valueOf(second);
else
c = String.valueOf(second);
temp = a + ":" + b + ":" + c;
songDurationTotal.setText(temp);
playButton.setImageResource(android.R.drawable.ic_media_pause);
isStarted = true;
updatePosition();
}
private void stopPlay() {
//musicService.stopPlay();
Intent intent = new Intent("songAction");
intent.putExtra("action", "stopPlay");
sendBroadcast(intent);
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(musicService.getCPos());
long millis = musicService.getCPos();
long second = (millis / 1000) % 60;
long minute = (millis / (1000 * 60)) % 60;
long hour = (millis / (1000 * 60 * 60)) % 24;
String temp="",a="",b="",c="";
if(hour==0)
a = "00";
else if(hour<=9 && hour>0)
a = "0" + String.valueOf(hour);
else
a = String.valueOf(hour);
if(minute==0)
b = "00";
else if(minute<=9 && minute>0)
b = "0" + String.valueOf(minute);
else
b = String.valueOf(minute);
if(second==0)
c = "00";
else if(second<=9 && second>0)
c = "0" + String.valueOf(second);
else
c = String.valueOf(second);
temp = a + ":" + b + ":" + c;
songDurationCurrent.setText(temp);
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (musicService.isPlay()) {
handler.removeCallbacks(updatePositionRunnable);
//musicService.pausePlay();
Intent intent = new Intent("songAction");
intent.putExtra("action", "pausePlay");
sendBroadcast(intent);
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
//musicService.startAgain();
Intent intent = new Intent("songAction");
intent.putExtra("action", "startAgain");
sendBroadcast(intent);
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
start();
}
}
break;
}
case R.id.next: {
int seekto = musicService.getCPos() + STEP_VALUE;
if (seekto > musicService.getDur())
seekto = musicService.getDur();
//musicService.pausePlay();
Intent intent = new Intent("songAction");
intent.putExtra("action", "seekTo");
intent.putExtra("value", String.valueOf(seekto));
sendBroadcast(intent);
//musicService.startAgain();
break;
}
case R.id.prev: {
int seekto = musicService.getCPos() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
//musicService.pausePlay();
/*
Intent intent = new Intent("songAction");
intent.putExtra("action", "pausePlay");
sendBroadcast(intent);
player.seekTo(seekto);
intent.putExtra("action", "startAgain");
sendBroadcast(intent);
//musicService.startAgain();
*/
Intent intent = new Intent("songAction");
intent.putExtra("action", "seekTo");
intent.putExtra("value", String.valueOf(seekto));
sendBroadcast(intent);
break;
}
}
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMoveingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMoveingSeekBar) {
// player.seekTo(progress);
Intent intent = new Intent("songAction");
intent.putExtra("action", "seekTo");
intent.putExtra("value", String.valueOf(progress));
sendBroadcast(intent);
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.v("Check", "Service Connected");
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}
MusicService.java
Imports*
public class MusicService extends Service {
String songPath = "", action = "";
MediaPlayer player = null;
private final IBinder mBinder = new LocalBinder();
private BroadcastReceiver yourReceiver;
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class LocalBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
public void onCreate() {
super.onCreate();
player = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, final int startId) {
Log.v("Check", "Service Started");
songPath = intent.getStringExtra("songPath");
final IntentFilter theFilter = new IntentFilter();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
player.stop();
player.reset();
try {
player.setDataSource(songPath);
player.prepare();
player.start();
}
catch (Exception e) {
}
this.yourReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("songAction")){
String state = intent.getExtras().getString("action");
if(state.equals("stopPlay")) {
stopPlay();
}
else if(state.equals("pausePlaye")) {
pausePlay();
}
else if(state.equals("startAgain")) {
startAgain();
}
else if(state.equals("seekTo")) {
int value = Integer.parseInt(intent.getExtras().getString("value"));
player.seekTo(value);
}
}
}
};
this.registerReceiver(this.yourReceiver, theFilter);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
player.reset();
player.release();
player = null;
}
void stopPlay() {
player.stop();
player.reset();
}
void pausePlay() {
player.pause();
}
void startAgain() {
player.start();
}
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
int getCPos() {
return player.getCurrentPosition();
}
int getDur() {
return player.getDuration();
}
boolean isPlay() {
return player.isPlaying();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.coderahul.player"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="24" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name="com.android.tools.fd.runtime.BootstrapApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.coderahul.player.MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.coderahul.beats.songPlay" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:enabled="true" android:process=":remote" android:name=".MusicService"/>
</application>
</manifest>
You are calling start() method from onCreate which is before your service is connected. Call start() method after your service has been binded or started so that you have instance of the service class.
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound = true;
//here
start();
}
bindService is asynchronous
put start() in onServiceConnected:
#Override
public void onServiceConnected(ComponentName className, IBinder service) {
Log.d("TAG", "Service Connected");
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound = true;
//here
start();
}
Log
output

Play background music in all activities of Android app

I spend about 20 hours until now and my problem there still is .
I am creating an android application that has several Activities (mainMenu , aboutUs,setting).
I followed the best answered of below link and that was O.K .
Music played using asyncTask isn't stopping by using cancel
When i run my app,(my code is in mainActivity ), the music begin and it does not stop when navigate to other Activities . This is GOOD .
But i put a ToggleButton in my setting_activity Activity that i hope this Button starts and stops this music. NOW my question is how can i stop and/or start music again from setting_activity ?
in another solution :
I create a class MusicManager and i call it`s start and stop .
But this was several problems too :
Music started in mainMenu_activity but only play for about 15 seconds and then stopped.
I could not stop the music from another activities.At this time i play music in mainMenua_ctivity as this line codes :
MusicManager mm = new MusicManager(this, R.raw.background_sound);
mm.play();
How can i stop playing that ?
3. The music stopped when i navigate to other activities .
public class MusicManager implements OnPreparedListener {
static MediaPlayer mPlayer;
Context context;
private int mySoundId;
public MusicManager(Context ctx, int musicID) {
context = ctx;
mySoundId = musicID;
mPlayer = MediaPlayer.create(context, mySoundId);
mPlayer.setOnPreparedListener(this);
}
public void play() {
mPlayer = MediaPlayer.create(context, mySoundId);
}
public void stop() {
mPlayer.stop();
mPlayer.release();
}
#Override
public void onPrepared(MediaPlayer player) {
player.start();
mPlayer.setLooping(true);
mPlayer.setVolume(25, 25);
}
}
Finally i want to play a background music in all activities without stop/start music .
How can i do it ?
You could put the music player in a service. This would make it independent from the Activities and you would still be able to control the playback through intents.
Here are some code example about it: https://stackoverflow.com/a/8209975/2804473
The code below is written by Synxmax here at StackOverflow, and covered in the link above:
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
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() {
}
}
#Override
public void onCreate (){
super.onCreate();
Player = 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;
}
});
}
public class serv extends Service{
MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate()
{
mp = MediaPlayer.create(this, R.raw.b);
mp.setLooping(false);
}
public void onDestroy()
{
mp.stop();
}
public void onStart(Intent intent,int startid){
Log.d(tag, "On start");
mp.start();
}
}
The top answer is correct, however you have to add the service to the manifest file.
<service android:enabled="true" android:name="BackgroundSoundService" />
Simon's answer above is correct. I had similar problem where I have fragments which had music player and I needed to go back to that UI on click of a button. Your case is similar but instead of going back to UI, you want to control playback. Here is what I did for my application. This takes care of playback of audio list including shuffle and repeat functionality. This takes care of showing media controls in notification bar too.
Create a service MusicPlayerService with following code:
public class MediaPlayerService extends Service implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnSeekCompleteListener,
MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener,
AudioManager.OnAudioFocusChangeListener {
public static final String ACTION_PLAY = "pkg_name.ACTION_PLAY";
public static final String ACTION_PAUSE = "pkg_name.ACTION_PAUSE";
public static final String ACTION_PREVIOUS = "pkg_name.ACTION_PREVIOUS";
public static final String ACTION_NEXT = "pkg_name.ACTION_NEXT";
public static final String ACTION_STOP = "pkg_name.ACTION_STOP";
private MediaPlayer mediaPlayer;
//MediaSession
private MediaSessionManager mediaSessionManager;
private MediaSessionCompat mediaSession;
private MediaControllerCompat.TransportControls transportControls;
//AudioPlayer notification ID
private static final int NOTIFICATION_ID = 101;
//Used to pause/resume MediaPlayer
private int resumePosition;
// Binder given to clients
private final IBinder iBinder = new LocalBinder();
//List of available Audio files
private ArrayList<PlayableTrack> audioList;
private int audioIndex = -1;
//Handle incoming phone calls
private boolean ongoingCall = false;
private PhoneStateListener phoneStateListener;
private TelephonyManager telephonyManager;
private Bitmap albumArtBitmap;
private boolean shuffle = false;
private boolean repeat = false;
private Random rand;
/**
* Service lifecycle methods
*/
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public void onCreate() {
super.onCreate();
// Perform one-time setup procedures
// Manage incoming phone calls during playback.
// Pause MediaPlayer on incoming call,
// Resume on hangup.
callStateListener();
//ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs -- BroadcastReceiver
registerBecomingNoisyReceiver();
//Listen for new Audio to play -- BroadcastReceiver
register_playNewAudio();
rand = new Random();
StorageUtil storage = new StorageUtil(getApplicationContext());
shuffle = storage.loadShuffleRepeat("Shuffle");
repeat = storage.loadShuffleRepeat("Repeat");
}
//The system calls this method when an activity, requests the service be started
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
//Load data from SharedPreferences
StorageUtil storage = new StorageUtil(getApplicationContext());
audioList = storage.loadAudio();
audioIndex = storage.loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
} catch (NullPointerException e) {
stopSelf();
}
if (mediaSessionManager == null) {
try {
initMediaSession();
initMediaPlayer();
} catch (RemoteException e) {
e.printStackTrace();
stopSelf();
}
buildNotification(PlaybackStatus.PLAYING);
}
//Handle Intent action from MediaSession.TransportControls
handleIncomingActions(intent);
return super.onStartCommand(intent, flags, startId);
}
#Override
public boolean onUnbind(Intent intent) {
mediaSession.release();
removeNotification();
return super.onUnbind(intent);
}
#Override
public void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
stopMedia();
mediaPlayer.reset();
}
//Disable the PhoneStateListener
if (phoneStateListener != null) {
telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
}
removeNotification();
//unregister BroadcastReceivers
unregisterReceiver(becomingNoisyReceiver);
unregisterReceiver(playNewAudio);
Picasso.get().cancelRequest(target);
}
/**
* Service Binder
*/
public class LocalBinder extends Binder {
public MediaPlayerService getService() {
// Return this instance of LocalService so clients can call public methods
return MediaPlayerService.this;
}
}
/**
* MediaPlayer callback methods
*/
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
//Invoked indicating buffering status of
//a media resource being streamed over the network.
}
#Override
public void onCompletion(MediaPlayer mp) {
//Invoked when playback of a media source has completed.
stopMedia();
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
//Invoked when there has been an error during an asynchronous operation
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
Log.d("MediaPlayer Error", "MEDIA ERROR NOT VALID FOR PROGRESSIVE PLAYBACK " + extra);
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
Log.d("MediaPlayer Error", "MEDIA ERROR SERVER DIED " + extra);
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
Log.d("MediaPlayer Error", "MEDIA ERROR UNKNOWN " + extra);
break;
}
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//Invoked when the media source is ready for playback.
playMedia();
}
#Override
public void onAudioFocusChange(int focusState) {
//Invoked when the audio focus of the system is updated.
switch (focusState) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mediaPlayer == null) initMediaPlayer();
else if (!mediaPlayer.isPlaying()) mediaPlayer.start();
mediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mediaPlayer.isPlaying()) mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer = null;
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (mediaPlayer.isPlaying()) mediaPlayer.pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mediaPlayer.isPlaying()) mediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
/**
* MediaPlayer actions
*/
private void initMediaPlayer() {
if (mediaPlayer == null)
mediaPlayer = new MediaPlayer();//new MediaPlayer instance
//Set up MediaPlayer event listeners
mediaPlayer.setOnCompletionListener(this);
mediaPlayer.setOnErrorListener(this);
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnSeekCompleteListener(this);
mediaPlayer.setOnInfoListener(this);
//Reset so that the MediaPlayer is not pointing to another data source
mediaPlayer.reset();
mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
try {
// Set the data source to the mediaFile location
mediaPlayer.setDataSource(activeAudio.getFileLocation());
} catch (IOException e) {
e.printStackTrace();
stopSelf();
}
mediaPlayer.prepareAsync();
}
public void playMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void stopMedia() {
if (mediaPlayer == null) return;
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
public void pauseMedia() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
resumePosition = mediaPlayer.getCurrentPosition();
}
buildNotification(PlaybackStatus.PAUSED);
Intent intent = new Intent("PLAYBACK_PAUSED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
private void resumeMedia() {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(resumePosition);
mediaPlayer.start();
buildNotification(PlaybackStatus.PLAYING);
Intent intent = new Intent("PLAYBACK_STARTED");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
/**
* ACTION_AUDIO_BECOMING_NOISY -- change in audio outputs
*/
private BroadcastReceiver becomingNoisyReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//pause audio on ACTION_AUDIO_BECOMING_NOISY
pauseMedia();
buildNotification(PlaybackStatus.PAUSED);
}
};
private void registerBecomingNoisyReceiver() {
//register after getting audio focus
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
registerReceiver(becomingNoisyReceiver, intentFilter);
}
/**
* Handle PhoneState changes
*/
private void callStateListener() {
// Get the telephony manager
telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
//Starting listening for PhoneState changes
phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
//if at least one call exists or the phone is ringing
//pause the MediaPlayer
case TelephonyManager.CALL_STATE_OFFHOOK:
case TelephonyManager.CALL_STATE_RINGING:
if (mediaPlayer != null) {
pauseMedia();
ongoingCall = true;
}
break;
case TelephonyManager.CALL_STATE_IDLE:
// Phone idle. Start playing.
if (mediaPlayer != null) {
if (ongoingCall) {
ongoingCall = false;
resumeMedia();
}
}
break;
}
}
};
// Register the listener with the telephony manager
// Listen for changes to the device call state.
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/**
* MediaSession and Notification actions
*/
private void initMediaSession() throws RemoteException {
if (mediaSessionManager != null) return; //mediaSessionManager exists
mediaSessionManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
// Create a new MediaSession
mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer");
//Get MediaSessions transport controls
transportControls = mediaSession.getController().getTransportControls();
//set MediaSession -> ready to receive media commands
mediaSession.setActive(true);
//indicate that the MediaSession handles transport control commands
// through its MediaSessionCompat.Callback.
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
//Set mediaSession's MetaData
updateMetaData();
// Attach Callback to receive MediaSession updates
mediaSession.setCallback(new MediaSessionCompat.Callback() {
// Implement callbacks
#Override
public void onPlay() {
super.onPlay();
resumeMedia();
}
#Override
public void onPause() {
super.onPause();
pauseMedia();
}
});
}
private void updateMetaData() {
fetchBitmapOfAlbum();
// Update the current metadata
mediaSession.setMetadata(new MediaMetadataCompat.Builder()
.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArtBitmap)
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, "")
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, activeAudio.getAlbumName())
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, activeAudio.getTrackName())
.build());
}
private Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
albumArtBitmap = bitmap;
}
#Override
public void onBitmapFailed(Exception e, Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
private void fetchBitmapOfAlbum() {
Picasso.get().load(activeAudio.getAlbumArt())
.placeholder(R.drawable.rotate_animation)
.error(R.drawable.ic_blank)
.into(target);
}
private void buildNotification(PlaybackStatus playbackStatus) {
int notificationAction = android.R.drawable.ic_media_pause;//needs to be initialized
PendingIntent play_pauseAction = null;
//Build a new notification according to the current state of the MediaPlayer
if (playbackStatus == PlaybackStatus.PLAYING) {
notificationAction = android.R.drawable.ic_media_pause;
//create the pause action
play_pauseAction = playbackAction(1);
} else if (playbackStatus == PlaybackStatus.PAUSED) {
notificationAction = android.R.drawable.ic_media_play;
//create the play action
play_pauseAction = playbackAction(0);
}
fetchBitmapOfAlbum(); //replace with your own image
String channelId = "";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
channelId = "APP_MUSIC";
}
// Create a new Notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, channelId)
// Hide the timestamp
.setShowWhen(false)
// Set the Notification style
.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
// Attach our MediaSession token
.setMediaSession(mediaSession.getSessionToken())
// Show our playback controls in the compat view
.setShowActionsInCompactView(0, 1, 2))
// Set the Notification color
.setColor(ContextCompat.getColor(this.getApplicationContext(), R.color.colorAccent))
// Set the large and small icons
.setLargeIcon(albumArtBitmap)
.setSmallIcon(R.drawable.ic_stat_notifications)
// Set Notification content information
.setContentText(activeAudio.getTrackName())
.setTicker(activeAudio.getAlbumName() + "-" + activeAudio.getTrackName())
.setOngoing(true)
.setContentTitle(activeAudio.getAlbumName())
.setContentInfo(activeAudio.getTrackName())
// Add playback actions
.addAction(notificationAction, "pause", play_pauseAction)
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(NOTIFICATION_ID, notificationBuilder.build());
}
private PendingIntent playbackAction(int actionNumber) {
Intent playbackAction = new Intent(this, MediaPlayerService.class);
switch (actionNumber) {
case 0:
// Play
playbackAction.setAction(ACTION_PLAY);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
case 1:
// Pause
playbackAction.setAction(ACTION_PAUSE);
return PendingIntent.getService(this, actionNumber, playbackAction, 0);
default:
break;
}
return null;
}
private void removeNotification() {
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(NOTIFICATION_ID);
}
private void handleIncomingActions(Intent playbackAction) {
if (playbackAction == null || playbackAction.getAction() == null) return;
String actionString = playbackAction.getAction();
if (actionString.equalsIgnoreCase(ACTION_PLAY)) {
transportControls.play();
} else if (actionString.equalsIgnoreCase(ACTION_PAUSE)) {
transportControls.pause();
}
}
/**
* Play new Audio
*/
private BroadcastReceiver playNewAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Get the new media index form SharedPreferences
audioIndex = new StorageUtil(getApplicationContext()).loadAudioIndex();
if (audioIndex != -1 && audioIndex < audioList.size()) {
//index is in a valid range
activeAudio = audioList.get(audioIndex);
} else {
stopSelf();
}
//A PLAY_NEW_AUDIO action received
//reset mediaPlayer to play the new Audio
stopMedia();
mediaPlayer.reset();
initMediaPlayer();
updateMetaData();
buildNotification(PlaybackStatus.PLAYING);
}
};
private void register_playNewAudio() {
//Register playNewMedia receiver
IntentFilter filter = new IntentFilter(MainActivity.Broadcast_PLAY_NEW_AUDIO);
registerReceiver(playNewAudio, filter);
}
public boolean isPlaying(){
return mediaPlayer.isPlaying();
}
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Shuffle", shuffle);
}
public void setRepeat(){
if(repeat) repeat=false;
else repeat=true;
StorageUtil storage = new StorageUtil(getApplicationContext());
storage.storeShuffleRepeat("Repeat", repeat);
}
}
Add the service to your manifest
<service android:name=".service.MediaPlayerService" />
Bind the service in MainActivity and declare methods to call the service
public class MainActivity {
private MediaPlayerService player;
boolean serviceBound = false;
public static final String Broadcast_PLAY_NEW_AUDIO = "pkg_name.PlayNewAudio";
//Binding this Client to the AudioPlayer Service
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MediaPlayerService.LocalBinder binder = (MediaPlayerService.LocalBinder) service;
player = binder.getService();
serviceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
serviceBound = false;
}
};
// Call this method to play track
public void playAudio(int audioIndex, ArrayList<PlayableTrack> updatedList) {
//Check is service is active
audioList = updatedList;
if (!serviceBound) {
Intent playerIntent = new Intent(this, MediaPlayerService.class);
startService(playerIntent);
bindService(playerIntent, serviceConnection, Context.BIND_AUTO_CREATE);
} else {
//Service is active
//Send a broadcast to the service -> PLAY_NEW_AUDIO
Intent broadcastIntent = new Intent(Broadcast_PLAY_NEW_AUDIO);
sendBroadcast(broadcastIntent);
}
}
// Additional methods for control
public void start() {
player.playMedia();
}
public void pause() {
player.pauseMedia();
}
public boolean isPlaying() {
if (player != null && serviceBound) {
return player.isPlaying();
}
return false;
}
}
This is my solution:
1- first add a music file in raw folder (in my case coffee.mp3)
2- create a class named BackgroundSoundService that extends Service:
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.coffee);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getAction().equals("PLAY")) {
if(mediaPlayer.isPlaying() == false) {
mediaPlayer.start();
Toast.makeText(getApplicationContext(), "Music Is Playing", Toast.LENGTH_SHORT).show();
}
}
if (intent.getAction().equals("STOP")) {
this.stopService(intent);
Toast.makeText(getApplicationContext(), "Music Stopped", Toast.LENGTH_SHORT).show();
}
return startId;
}
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
do not forget to define this service in application tag of android manifest.xml:
<service android:name=".BackgroundSoundService" />
3- for play button in your activity use this code:
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "PLAY";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
3- for stop button in your activity use this code:
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String action = "STOP";
Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
myService.setAction(action);
startService(myService);
}
});
I have created a simple android app with two activity which play music in background service, the app will pause the music if app is not visible to the user (for example user pressed home button).
you can see it in my github for more details.

foreground Service recursively calls new activity and cant be stopped

I am working on Integrating a Quickblox based video chat into my app.
Here i am running a listener in foreground service which listens to the video call initiated by opponent. here in switch statement, at call accept state i am calling a new activity which is nothing but a dialler screen with accept and disconnect button. accept button connects the call but disconnect cuts the call and closes the activity, but again the same activity (dialler screen) opens repeatedly after multiple times, My question is how to make service to call once and ignore the rest calls if its disconnected. (Am sending reject signal to opponent thus call drops from opponent but here service calls activity repeatedly though call is dropped from opponent)
Here is the code
VchatListener service with OnQBVideoChatListener with switch statement has a accept call state which calls new activity
public class VChatListener extends Service {
private VideoChatConfig videoChatConfig;
private CallState state;
QBUser a=DataHolder.getInstance().getCurrentQbUser();
/* private AlertDialog alertDialog;*/
private static final int notif_id=1;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
this.startForeground();
}
private void startForeground() {
startForeground(notif_id, getMyActivityNotification(""));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
//startForeground(FOREGROUND_ID, notification);
Runnable runnable = new Runnable() {
#Override
public void run() {
try {
Log.i("******Service Call user Here","now*******");
if(a!=null){
Log.i("******Service testing",""+a);
}else{
Log.i("******Service testing user","nothing");
}
Log.i("***Still","running****");
QBVideoChatController.getInstance().setQBVideoChatListener(a, qbVideoChatListener);
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (XMPPException e) {
e.printStackTrace();
}
};
};
new Thread(runnable).start();
return Service.START_REDELIVER_INTENT;
private OnQBVideoChatListener qbVideoChatListener = new OnQBVideoChatListener() {
#Override
public void onVideoChatStateChange(CallState state, VideoChatConfig receivedVideoChatConfig) {
Debugger.logConnection("onVideoChatStateChange: " + state);
videoChatConfig = receivedVideoChatConfig;
/*if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}*/
Log.i("service state",""+state.toString());
switch (state) {
case ACCEPT:
Intent intent = new Intent(VChatListener.this, CallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(VideoChatConfig.class.getCanonicalName(), videoChatConfig);
startActivity(intent);
// showCallDialog();
Log.i("service state 1",""+state.toString());
break;
case ON_ACCEPT_BY_USER:
Log.i("service state 2",""+state.toString());
/* QBVideoChatController.getInstance().onAcceptFriendCall(videoChatConfig, null);*/
//startVideoChatActivity();
break;
case ON_REJECTED_BY_USER:
Log.i("service state 3",""+state.toString());
/*Toast.makeText(VChatListener.this, "Rejected by user", Toast.LENGTH_SHORT).show();*/
break;
case ON_DID_NOT_ANSWERED:
Log.i("service state 4",""+state.toString());
/* Toast.makeText(VChatListener.this, "User did not answer", Toast.LENGTH_SHORT).show();*/
break;
case ON_CANCELED_CALL:
videoChatConfig = null;
Log.i("service state 5","nothing");
/*if (alertDialog != null && alertDialog.isShowing()){
alertDialog.dismiss();
}
autoCancelHandler.removeCallbacks(autoCancelTask);*/
break;
}
}
};
public void onDestroyed(){
super.onDestroy();
}
private Notification getMyActivityNotification(String text){
// The PendingIntent to launch our activity if the user selects
// this notification
CharSequence title = getText(R.string.title_activity);
/* PendingIntent contentIntent = PendingIntent.getActivity(this,0, new Intent(this,Appointment.class), 0);*/
return new Notification.Builder(this)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher)
.getNotification();
}
}
Here is the activity which will be called by service the end button associated with function end, disconnects the call.
public class CallActivity extends Activity {
private ProgressDialog progressDialog;
private VideoChatConfig videoChatConfig;
private VChatListener vChatListener;
QBUser qbuser;
MediaPlayer mMediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageButton b1 = (ImageButton) findViewById(R.id.button1);
ImageButton b2 = (ImageButton) findViewById(R.id.button2);
playRingtone();
/*while(!b1.isPressed() || !b2.isPressed()){
playRingtone();
}*/
progressDialog = new ProgressDialog(this);
progressDialog.setMessage(getString(R.string.please_wait));
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO add stopCalling here, send Cancel message if
// need
// XMPPSender.sendCancelCallMsg(videoChatConfig);
// QBVideoChatController.getInstance().stopCalling();
}
});
qbuser = DataHolder.getInstance().getCurrentQbUser();
videoChatConfig = getIntent().getParcelableExtra(
VideoChatConfig.class.getCanonicalName());
;
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onAcceptCallClick();
mMediaPlayer.stop();
}
private void onAcceptCallClick() {
//mMediaPlayer.stop();
QBVideoChatController.getInstance().acceptCallByFriend(
videoChatConfig, null);
startVideoChatActivity();
}
private void startVideoChatActivity() {
if (videoChatConfig.getCallType() == CallType.VIDEO_AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityVideoChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
} else if(videoChatConfig.getCallType() == CallType.AUDIO) {
Intent intent = new Intent(getBaseContext(),
ActivityAudioChat.class);
intent.putExtra(VideoChatConfig.class.getCanonicalName(),
videoChatConfig);
startActivity(intent);
}
}
});
}
public void end(View view)
{
mMediaPlayer.stop();
QBVideoChatController.getInstance().finishVideoChat(videoChatConfig);
XMPPSender.sendCancelCallMsg(videoChatConfig);
QBVideoChatController.getInstance().stopCalling();
super.onDestroy();
finish();
}
public void playRingtone() {
try {
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_RING) != 0) {
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
} catch(Exception e) {
e.printStackTrace();
}
/* try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}*/
}
}
to limit the service to call activity once i included in manifest launch mode = "singleTask" which launches activity once, but when activity get closed by disconnect it is called again and doesnt stop.
<activity
android:name="com.yugays.videochatsample.ui.CallActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="landscape" >
</activity>
How to stop activity getting created after call is disconnected and activity is closed.

Can't get song duration in onCreate , but can get it on button pressed

I have a custom media service and an audio player class which communicates with it but is not bound to the service.
When I create an object of MyService and write the code :-
myService.player.getDuration() in onCreate I get the null pointer exception on this line.
But if I write this code on click of some button listener on the same screen then I get the exact duration.
I have tried every possible syntax to solve this but m still not able to resolve the problem.
** The code of my service is :-**
private static final String TAG = "MyService";
public static MediaPlayer player;
String song_uri,url;
Bundle b;
private IBinder myBinder;
private boolean isplaying;
public static final String Song_uri="song_uri";
public static final String EXTRA_SHUFFLE="EXTRA_SHUFFLE";
#Override
public IBinder onBind(Intent intent) {
return null;
}
public class MyBinder extends Binder{
MyService getService()
{
return MyService.this;
}
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate "+song_uri);
}
#Override
public void onDestroy() {
//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setCurrentPosition(0);
Log.d(TAG, "onDestroy");
player.stop();
//player.release();
}
public void onPause()
{
player.pause();
}
public double duration()
{
return player.getDuration();
}
public void onStart(Intent intent, int startid) {
DataManager.getInstance().setWantsToPlaySong(true);
Bundle b=intent.getExtras();
song_uri=b.getString("song_uri");
Uri path=Uri.parse(song_uri);
player = MediaPlayer.create(this,path );
player.setLooping(false); // Set looping
//Toast.makeText(this, "My Service Started"+" Duration = "+(player.getDuration()/1000)/60, Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart"+song_uri);
player.start();
}
The code of Audio Player is :-
uri = this.getIntent().getExtras().getString("song_uri");
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStop = (Button) findViewById(R.id.buttonStop);
buttonPause = (Button) findViewById(R.id.buttonPause);
tracks = dbManager.getAllSongs(AudioPlayer2.this);
buttonForward = (Button) findViewById(R.id.buttonforward);
buttonBackward = (Button) findViewById(R.id.buttonbackward);
//=========================================================================================
sArtworkUri = Uri.parse("content://media/external/audio/albumart");
//myservice=new MyService();
Uri path = Uri.parse(uri);
current_song=this.getIntent().getExtras().getInt("current_song");
albumArtUri = this.getIntent().getExtras().getString("album_art");
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
album_id = Long.parseLong(this.getIntent().getStringExtra("album_id"));
int id = Integer.parseInt(this.getIntent().getStringExtra("album_id"));
albumImageUri = ContentUris.withAppendedId(sArtworkUri, album_id);
ivAlbumArt = (ImageView) findViewById(R.id.album_art);
songName = this.getIntent().getStringExtra("song_name");
albumName = this.getIntent().getStringExtra("album_name");
tvName = (TextView) findViewById(R.id.tv_name);
tvAlbum = (TextView) findViewById(R.id.tv_album);
if (songName != null) {
tvName.setText(songName);
}
if (albumName != null) {
tvAlbum.setText(albumName);
}
// buttonStart.performClick();
if (DataManager.getInstance().getOnPausedSong()=="y"){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
if(DataManager.getInstance().getPausedSongName()==songName){
//Toast.makeText(AudioPlayer2.this, "stage 1", Toast.LENGTH_SHORT).show();
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
}
}
FetchImage fetchImage = new FetchImage();
fetchImage.execute();
/*if(DataManager.getInstance().getSong_uri()!=null)
{
stopService(new Intent(this, MyService.class));
}*/
// if(myService.player.isPlaying())
//{
stopService(new Intent(this, MyService.class));
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
myService.player.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
}
});
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// Toast.makeText(this, "Duration: "+myService.player.getDuration(), Toast.LENGTH_LONG).show();
/*//}//DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
*/ //buttonStart.setPressed(true);
//=======================================================================================
buttonStart.setOnClickListener(this);
buttonPause.setOnClickListener(this);
buttonForward.setOnClickListener(this);
buttonBackward.setOnClickListener(this);
buttonStop.setOnClickListener(this);
// buttonPause.performClick();
/* new Thread(myThread).start();
*/ }
// Thread for seekbar
// song starts playing
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonStart:
if(DataManager.getInstance().getSongPause()=="y"){
myService.player.start();
DataManager.getInstance().setSongPause("n");
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
// DataManager.getInstance().setWantsToPlaySong(true);
//DataManager.getInstance().setOnPausedSong("n");
//DataManager.getInstance().setOnPausedSong("y");
}else{
stopService(new Intent(this, MyService.class));
DataManager.getInstance().setSong_uri(uri);
Intent intent = new Intent(this,MyService.class);
Bundle b = new Bundle();
b.putString("song_uri",uri );
intent.putExtras(b);
startService(intent);
buttonStart.setVisibility(View.GONE);
buttonPause.setVisibility(View.VISIBLE);
DataManager.getInstance().setOnPausedSong("y");
DataManager.getInstance().setPausedSongName(songName);
}
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
break;
case R.id.buttonStop:
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
break;
case R.id.buttonforward:
stopService(new Intent(this, MyService.class));
current_song++;
FetchAllMusic fetchAllMusic = new FetchAllMusic();
fetchAllMusic.execute();
//new Thread(myThread).start();
break;
case R.id.buttonbackward:
Log.d(TAG, "onClick: stopping service");
stopService(new Intent(this, MyService.class));
if(current_song>0){
current_song--;
}
FetchAllMusic fetchAllMusic2 = new FetchAllMusic();
fetchAllMusic2.execute();
break;
case R.id.buttonPause:
buttonStart.setVisibility(View.VISIBLE);
buttonPause.setVisibility(View.GONE);
/* MyService myservice=new MyService();
myservice.onPause();*/
myService.player.pause();
DataManager.getInstance().setSongPause("y");
DataManager.getInstance().setWantsToPlaySong(false);
DataManager.getInstance().setOnPausedSong("n");
DataManager.getInstance().setPausedSongName(songName);
//duration=myService.player.getDuration();
// Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show();
}
}
public void onBackPressed() {
try {
//addvideo.removeView(DBManager.getInstance().getVideo());
DataManager.getInstance().setSong_uri(uri);
DataManager.getInstance().setAlbum_id(""+album_id);
DataManager.getInstance().setAlbumName(albumName);
DataManager.getInstance().setSongName(songName);
DataManager.getInstance().setAlbumArtUri(albumArtUri);
DataManager.getInstance().setCurrent_song(current_song);
DataManager.getInstance().setWantsToPlaySong(false);
} catch (Exception e) {
e.printStackTrace();
}
super.onBackPressed();
}
private Runnable myThread = new Runnable(){
#Override
public void run() {
Log.d(TAG, "Thread Starts");
// TODO Auto-generated method stub
while (myProgress<100){
try{
Log.d(TAG, "Thread Starts");
myHandle.sendMessage(myHandle.obtainMessage());
Thread.sleep(3000);
}
catch(Throwable t){
}
}
}
Handler myHandle = new Handler(){
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
myProgress++;
seekbar.setProgress(myProgress);
}
};
};
It's not a syntax problem; it's a variable initialization problem. Either myService or myService.player is null when that line executes in onCreate(). Check your code for where you are initializing these and make sure that you don't reference them before they are set.

Categories

Resources