Android Music player not start automatically from onCreate - java

Hello i had implement code of Music service i want to create demo of music player but it not start automatically from onCreate() i want to start player automatically when activity open. here below i put code for Activity and service please help me any help will be appreciate.
public class MainActivity extends Activity {
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound = false;
private MusicController controller;
private boolean paused = false, playbackPaused = false;
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
songPicked();
}
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
public void songPicked() {
musicSrv.setSong(0);
musicSrv.playSong();
}
#Override
protected void onPause() {
super.onPause();
paused = true;
}
#Override
protected void onResume() {
super.onResume();
if (paused) {
paused = false;
}
}
#Override
protected void onStop() {
controller.hide();
super.onStop();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv = null;
super.onDestroy();
}
}
Here below i put service code also.
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private final IBinder musicBind = new MusicBinder();
private MediaPlayer player;
private ArrayList<Song> songs;
private int songPosn;
private String songTitle = "";
private Random rand;
public void onCreate() {
super.onCreate();
songPosn = 0;
rand = new Random();
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs) {
songs = theSongs;
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
Song playSong = songs.get(0);
songTitle = playSong.getTitle();
long currSong = playSong.getID();
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setSong(int songIndex) {
songPosn = songIndex;
}
#Override
public void onCompletion(MediaPlayer mp) {
if (player.getCurrentPosition() > 0) {
mp.reset();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
playSong();
}
#Override
public void onDestroy() {
stopForeground(true);
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
}
I just want to start player when application start automatically without any click. but it display unfortunately stopped with null object reference of Media player. I had never work with service also with music player.
Null pointer exception throws because music service object returns null so.

Finally solved as per #vladMatvienko answer thanks for your support man.
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
songPicked();
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};

Related

org.greenrobot.eventbus.EventBusException its super classes have no public methods with the #Subscribe annotation

I'm using EventBus to control status of mediaplayer , but I'm running into an error during execution.
Caused by: org.greenrobot.eventbus.EventBusException: Subscriber class
maa.MainActivity and its super classes have no public methods with the
#Subscribe annotation
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
#Override
protected void onDestroy() {
radioManager.unbind();
super.onDestroy();
if (radioManager.isPlaying()) {
radioManager.playOrPause(getPreference(getApplicationContext()));
} else {
radioManager.playOrPause(getPreference(getApplicationContext()));
}
}
#Override
protected void onResume() {
super.onResume();
radioManager.bind();
}
#Subscribe
public void onEvent(String status) {
switch (status) {
case PlaybackStatus.LOADING:
progressloading.setVisibility(View.VISIBLE);
trigger.setVisibility(View.GONE);
break;
case PlaybackStatus.ERROR:
Toast.makeText(this, R.string.no_stream, Toast.LENGTH_SHORT).show();
break;
}
if (status.equals(PlaybackStatus.PLAYING)) {
trigger.setVisibility(View.VISIBLE);
progressloading.setVisibility(View.GONE);
}
trigger.setImageResource(status.equals(PlaybackStatus.PLAYING)
? R.drawable.ic_pause_black
: R.drawable.ic_play_arrow_black);
}
RadioManager.java
public class RadioManager {
#SuppressLint("StaticFieldLeak")
private static RadioManager instance = null;
private static RadioService service;
private Context context;
private boolean serviceBound;
public RadioManager(Context context) {
this.context = context;
serviceBound = false;
}
public static RadioManager with(Context context) {
if (instance == null)
instance = new RadioManager(context);
return instance;
}
public static RadioService getService() {
return service;
}
public void playOrPause(String streamUrl) {
service.playOrPause(streamUrl);
}
public boolean isPlaying() {
if (service != null) {
return service.isPlaying();
}
return false;
}
public int getCurrentPosition() {
if (service != null) {
return service.getCurrentPosition();
}
return 0;
}
public void bind() {
Intent intent = new Intent(context, RadioService.class);
context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
if (service != null)
EventBus.getDefault().post(service.getStatus());
}
public void unbind() {
context.unbindService(serviceConnection);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
RadioService.LocalBinder rl = (RadioService.LocalBinder) binder;
service = rl.getService();
}
public void onServiceDisconnected(ComponentName arg0) {
serviceBound = false;
}
};
}
i've solved this issue ,my mistake was imports
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

java.lang.IllegalStateException with MediaPlayerService

When I come back after click the back button and I try to play music I have error 'java.lang.IllegalStateException' - but why..? I noticed that others method like player.isPlaying() or player.reset() didn't work too. If somebody had already this problem - please help. Nice day :)
java.lang.IllegalStateException
at android.media.MediaPlayer.prepareAsync(Native Method)
Activity class:
#Override
protected void onStart() {
super.onStart();
playIntent = new Intent(this, MediaPlayerService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
#Override
protected void onDestroy() {
super.onDestroy();
if(musicConnection!=null){
unbindService(musicConnection);
}
}
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MediaPlayerService.LocalBinder musicBinder = (MediaPlayerService.LocalBinder) service;
musicService = musicBinder.getService();
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
MusicService class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return iBinder;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.reset();
player.release();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
#Override
public void onCreate() {
super.onCreate();
setSong(0);
player = new MediaPlayer();
initMediaPlayer();
}
public void initMediaPlayer(){
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void playSong(){
try{
player.reset();
Song playSong = songList.get(songPos);
long currSong = playSong.getId();
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
player.setDataSource(getApplicationContext(), trackUri);
}catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
I had to change the onDestroy method on:
#Override
protected void onDestroy() {
stopService(playIntent);
musicService = null;
super.onDestroy();
}

Android Media Player Null Pointer Exception

I know what a null pointer exception is i have tried using
MediaPlayer mp = new MediaPlayer();
and
public int check()
{
if(mp!=null)
{
return 1;
}
else
{
return 2;
}
}
doesn't helps.
This is the error im getting-
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.openaisearch.www.musicplayer/com.openaisearch.www.musicplayer.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'boolean com.openaisearch.www.musicplayer.Music.check()' on a null
object reference
public class MainActivity extends AppCompatActivity {
ArrayList<String> mSongsList = new ArrayList<>() ;
ArrayList<Long> SongsPath = new ArrayList<>() ;
Button btnPlay;
Music mService;
SeekBar seekBar;
ListView lv;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
Music.LocalBinder binder = (Music.LocalBinder) service;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, Music.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
startService(intent);
btnPlay = (Button) findViewById(R.id.buttonPlay);
seekBar = (SeekBar) findViewById(R.id.seekBar);
lv = (ListView) findViewById(R.id.list);
getAudioList();
ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,mSongsList);
lv.setAdapter(arrayAdapter);
onSongClick();
setSeekBar();
check();
}
#Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
public void getAudioList() {
String orderBy = MediaStore.Audio.Media.TITLE ;
String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";
Cursor mCursor = getContentResolver().query(
MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media._ID }, selection, null, orderBy);
int count = mCursor.getCount();
while (mCursor.moveToNext()) {
mSongsList.add(mCursor.getString(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)));
SongsPath.add(mCursor.getLong(mCursor
.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)));
}
mCursor.close();
}
public void onSongClick()
{
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mService.playSong(SongsPath.get(position));
if(btnPlay.getText() == "Play")
{
btnPlay.setText("Pause");
}
}
});
}
public void onButtonClick(View view) {
int a = mService.stopMusic();
if(a == 1)
{
btnPlay.setText("Play");
}
else if (a ==2)
{
btnPlay.setText("Pause");
}
}
public void check()
{
boolean check = mService.check();
}
public void setSeekBar()
{
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser )
{
mService.setProg(progress*1000);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
}
Service-
public class Music extends Service {
Long b;
MediaPlayer mp;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
Music getService() {
return Music.this;
}
}
public void playSong(Long a) {
if (a!= b)
{ if(mp!=null)
{
mp.stop();
mp.release();
mp=null;
}
b =a;
Uri contentUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, a);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), contentUri);
mp.prepare();
mp.setLooping(true);
mp.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public int stopMusic()
{
if(mp.isPlaying())
{
mp.pause();
return 1;
}
else if (mp!=null)
{
mp.start();
return 2;
}
else
{
return 0;
}
}
public void setProg(int a)
{ if(mp!=null)
{
mp.seekTo(a);
}
}
public boolean check()
{
if(mp!=null)
{
return true;
}
else
{
return false;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
You are not checking if the service has been connected to the activity or not using mbound in ur function.
public void check()
{
i f(mBound)
{
boolean check = mService.check();
}
}
You're probably getting the NPE from this line: boolean check = mService.check(); So it's mService that is null, not mp
I think you trying to bind service that is not started yet. Try to call startService(intent); before bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
Your service class should follow this format; overwrite the onCreate() method
you are getting NPE because mService is null in line: mService.check();
public class MyService extends Service {
private Binder binder;
#Override
public void onCreate() {
super.onCreate();
binder = new Binder();
}
#Override
public IBinder onBind(Intent intent) {
return binder;
}
public class Binder extends android.os.Binder {
public MyService getService() {
return MyService.this; // return instance
}
}
}

How to make a background service?

I need to execute some tasks when my application is closed.
I have made a service for do this and tried many things, but i don't have the good result.
If someone have a tutorial or some path to follow, it would be great
This is my service:
public class TrackersImporter extends Service {
private static TrackersImporter instance;
private static long refreshDelay = 1; // Minutes
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private boolean isInit = false;
public ArrayList<Tracker> trackers = new ArrayList<>();
public static TrackersImporter getInstance(){
if (instance == null)
instance = new TrackersImporter();
return instance;
}
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("TrackersImporter",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
Message message = mServiceHandler.obtainMessage();
message.arg1 = startId;
mServiceHandler.sendMessage(message);
} catch (Exception e) {
Log.w("TrackersImporter", e.getMessage());
}
return START_STICKY;
}
public void addTracker(Tracker tracker) {
trackers.add(tracker);
}
protected void showToast(final String msg){
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
});
}
// Object responsible for
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
addTracker(Runkeeper.getInstance(MainActivity.getActivity()));
addTracker(Strava.getInstance(MainActivity.getActivity()));
startImport(MainActivity.getActivity().getBaseContext(), MainActivity.getActivity().getAppUser(), trackers);
stopSelf(msg.arg1);
}
/**
* Perform data imports.
* Imports are performed only 1 time.
* Additional calls to this method are equivalent to no-op.
* Call init() then performImport() for each TrackerImportable
* #param user user receiving the datas
*/
public void startImport(Context context, User user, ArrayList<Tracker> trackers) {
Context ctx = MainActivity.getActivity().getApplicationContext();
LocalDateTime now = new LocalDateTime();
if (Preferences.getPref(ctx, "tracker_import_date") == "")
Preferences.setPref(ctx, "tracker_import_date", now.toString());
LocalDateTime past = LocalDateTime.parse(Preferences.getPref(ctx, "tracker_import_date"));
long duration = new Duration(past.toDateTime(), now.toDateTime()).getStandardMinutes();
if (isInit)
return;
if (duration > refreshDelay) {
Preferences.setPref(ctx, "tracker_import_date", now.toString());
for (Tracker tracker : trackers) {
if (tracker.isEnabled() && Tracker.isUserEnabled(context, tracker.getName())) {
tracker.init();
tracker.performImport(user);
}
}
}
isInit = true;
}
}
}
This is my mainActivity
public class MainActivity extends BaseActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (ConnectivityUtil.isConnected(this.getApplicationContext())) {
initGoogleFit();
initTrackers(appUser);
}
}
private void initTrackers(User user) {
Intent trackersIntentService = new Intent(this, TrackersImporter.class);
trackersIntentService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startService(trackersIntentService);
}
#Override
protected void onResume() {
...
if (ConnectivityUtil.isConnected(this.getApplicationContext())) {
initTrackers(appUser);
}
}
}
First Create one launcher Activity which is like your Main Activity.
In Activity "onCreate" Method you need to start Service and Do Some thing if you wont in Service "onStartCommand" Method.
public class MainActivity extends Activity {
ArrayList<Integer> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this,TrackersImporter.class);
}
public class TrackersImporter extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do something
Log.v(TAG ,"Service is started");
}
}
And also Register this Service at manifest.xml like this.
<service android:name=".TrackersImporter"></service>
if you like stop service
stopService(new Intent(MainActivity.this,TrackersImporter.class);

Android AIDL StartProcess not working

I have an activity in which I call Service on background, I am quite new to AIDL
my codes are as follows:
on Activity
//declaration
private Intent mIntentInvenueService;
private IInvenueService mIInvenueService;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIntentInvenueService = new Intent(this, InvenueService.class);
startService(mIntentInvenueService);
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mIInvenueService = IInvenueService.Stub.asInterface(service);
try {
mIInvenueService.registerCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
mIInvenueService = null;
try {
mIInvenueService.unregisterCallback(mCallback);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
private final IInvenueServiceCallback.Stub mCallback = new IInvenueServiceCallback.Stub() {
#Override
public void onReceiveResponse() throws RemoteException {
runOnUiThread(new Runnable() {
public void run() {
if (flagChanged){
}
else
{
cAdapter.notifyDataSetChanged();
}
}
});
}
};
public void onResume() {
super.onResume();
bindService(mIntentInvenueService, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
unregisterReceiver(mBroadcastReceiver);
}
ON MY SERVICE:
private final RemoteCallbackList<IInvenueServiceCallback> mCallbacks = new RemoteCallbackList<IInvenueServiceCallback>();
private boolean isUpdated = false;
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IInvenueService.Stub mBinder = new IInvenueService.Stub() {
#Override
public void startProcess() throws RemoteException {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Toast.makeText(......).show()// Toast Here
}
}, 60000, 60000);
}
#Override
public void unregisterCallback(IInvenueServiceCallback callback)
throws RemoteException {
mCallbacks.unregister(callback);
}
#Override
public void registerCallback(IInvenueServiceCallback callback)
throws RemoteException {
mCallbacks.register(callback);
}
};
My AIDL:
interface IInvenueService {
void startProcess();
void registerCallback(IInvenueServiceCallback callback);
void unregisterCallback(IInvenueServiceCallback callback);
}
My Question is why is that the Toast not showing? Am I missing something that start process isnt working?
Any Help?
You should show Toasts from the UIThread, using a TimerTask will cause it to run on a seperate thread.
Try posting a runnable with the Toast to a Handler.

Categories