Reputation: 164
Using Service for achieving the Question purpose.
code :
inside manifest :
<service
android:name=".MyService"
android:enabled="true" />
service class :
public class MyService extends Service {
private MediaPlayer media;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
media = MediaPlayer.create(this, Settings.System.DEFAULT_RINGTONE_URI);
media.setLooping(true);
media.start();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
media.stop();
}
My Java class :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startMethod(View v) {
startService(new Intent(this, MyService.class));
}
public void stopMethod(View v) {
stopService(new Intent(this, MyService.class));
}
So, the issue is that, When I am killing the app, media player stops the playing music or my default ringtone. since, i am using START_STICKY, it should run in background.
What might be the issue ? I need to play the music even if app killed using service in android. Please, guide if there something wrong. Thanks.
EDIT
The above issue is working fine for lower version devices. For higher version we can use JobService.
Now, the Question is What if I want to check the specific time in background service, and at particular time I have to display a toast message. So far, I have done it inside onStartCommand() method and comparing time with .equals method. But, I think there's another way to do so..
my code inside onStartCommand():
if(currentTime.equals("Thu Mar 29 06:18:00 GMT 2018")){
Toast.makeText(this, ""+currentTime, Toast.LENGTH_SHORT).show();
}
if(currentTime.equals("Thu Mar 29 06:20:00 GMT 2018")){
Toast.makeText(this, ""+currentTime, Toast.LENGTH_SHORT).show();
}
if(currentTime.equals("Thu Mar 29 06:21:00 GMT 2018")){
Toast.makeText(this, ""+currentTime, Toast.LENGTH_SHORT).show();
}
Toast not displaying at these particular times. because it display only when the onStartCommand() method calls. So, how can I achieve this ?
Upvotes: 0
Views: 225
Reputation: 1763
If this is working in lower version android devices, then you can try and use a JobService for higher android version devices.
Follow the links below & become a pro at JobScheduling:
https://github.com/evernote/android-job
https://github.com/firebase/firebase-jobdispatcher-android http://blog.teamtreehouse.com/scheduling-work-jobscheduler
https://blog.klinkerapps.com/android-o-background-services/
Upvotes: 1