Running two independent events simultaneously in android - android

I am new to android and stuck up at some point in the app i am currently developing. In my onCreate method I have two independent tasks : First is playing sounds in an array using for loop and Second is an onClickListener to an image that makes it animate on click. The sound starts perfectly as soon as I start the app, My problem is when I click the image, it animates as required but it stops the sound. How can I play sound and animation independent of each other? Any help/idea would be appreciated.

Use AsyncTask in android it will update the ui too in method updateProgress in android

You can use service for playing music.Services are designed to continually running in the background.
public class MyService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MediaPlayer player = MediaPlayer.create(this, R.raw.audio);
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setVolume(1f, 1f);
player.start();

Related

How to handle services that run as foreground when an app is cleared from recent?

My Android app is playing audio while the app runs in the background with a service that runs as foreground, similar to many other apps such as Google Play Music, Spotify, and other music players / podcast player apps.
Most apps I checked, including Google Play Music, will leave the service running even when the app is cleared from recent. On the other hand, some will stop the audio and close the service (I only found Spotify doing that).
I am wondering what is the right way to handle this? Although most apps leave the service open, it seems that users will expect the audio to stop and the notification to disappear from the status bar together with the app.
Is there a right way here?
You can check this link to see what happens to the process when app is removed from
recents list.
Even if onTaskRemoved() is called, the app is not killed in this case. The service continues to exist. It can be proven by going to the hidden developer menu to check running processes.
You can execute some codes in this callback method, and get the desired behaviour.
Since it's a question of opinion, I'm going to give my own as a developer but also a power smartphone user (well, who isn't nowadays):
tl;dr: leave it running
===============================
longer version
The point of using your phone as a music player, is providing you with audio while you're doing other activities, like running, browsing, texting, or even playing music for others connected through a speaker, being the "dj" of your group. You would rarely use a music player as a primary task and I would expect to do that when you're doing something like trying to figure out the lyrics, or watch the videoclip (and hence, you would use YouTube). Thus, it is my belief that your music player should have a separate lifecycle than the rest of your phone activities. Imagine the nightmare of playing music for others and music suddenly stops while you're messing with unrelated stuff on your phone.
However, you have a point when mentioning that "it seems that users will expect the audio to stop and the notification to disappear from the status bar together with the app". I wouldn't get the whole statement as true, rather extract the gist: users want to stop their music app easily.
In that sense, you should make it as easy as possible to stop playback to optimize your user experience. Out of the top of my head, I would imagine the best way of doing that would be a nice "X" button in your notification extended (or even when compact) version. The user then can stop the playback right from the status bar and not have to go through bringing the app to the front.
If you do want to go a step further, you could have an option in your settings to either use a foreground or background service -to make it easier for the user to understand, you could use wording like "stop music when recent apps are cleared", hence delegating the choice to your user, according to their needs. That, of course, would add complexity and too much power to your users so it's up to you to figure out if you need it.
Leave it running, with a notification.
It's all in the name.
According to Android Developers,
"The Recents screen (also referred to as the Overview screen, recent
task list, or recent apps) is a system-level UI that lists recently
accessed activities and tasks."
Swiping the task away from this list just removes it from the list, not from execution.
Notifications (Certainly under Oreo) are where you let your user know that you still have service(s) running. Use the notification to allow them to re-open the task, and then terminate the service as they see fit.
You are making like music player application, so most of the time user expected that music will be played even if the application is closed from the recent task. Now you are using foreground service so notification will be shown, in this notification you provide STOP button, so the user can stop music from there.
But if you want that your app's background service is stopped after removing from recent task then,
public class CustomService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
//stop service
stopService(new Intent(this, CustomService.class));
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("CustomService", "Service Destroyed");
}
}
Now declare service in AndroidMenifest.xml
<service android:name=".CustomService" android:stopWithTask="false" />
android:stopWithTask="false" will give callback on onTaskRemoved(), so handle stop service over there.
leave the service running when the app is cleared from recent ,user can stop completely the audio and the service in the notification with a button just like this :
Here is a picture -> QQ Music
public class OnClearFromRecentService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("ClearFromRecentService", "Service Started");
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("ClearFromRecentService", "Service Destroyed");
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Log.e("ClearFromRecentService", "END");
//Code here
stopSelf();
}
}
Register this service in Manifest.xml like this
<service android:name="com.example.OnClearFromRecentService" android:stopWithTask="false" />
Then start this service on your activity
startService(new Intent(getBaseContext(), OnClearFromRecentService.class));
And now whenever you will clear your app from android recent Then this method onTaskRemoved() will execute.

Service or Activity for playing music in MediaPlayer App

I would like to develop a media player for Android on my own but I have a conception issue : should I use a Service or an Activity just for the player?
I have Fragments in my App and I would like to play a song when I click on one of the items within my music lists but I don't really know which of those 2 technologies I should use to allow music to keep playing even during navigation or outside the app.
Does it better to start a new Activity when a song is played and then keep the Activity running or launch a Service waiting for some events?
Thanks in advance.
The best solution for your app may be
i) Visualize your app with frontend ( like selecting music to play, pause, forward and other features )
ii) start service that runs in background which continues the activity process in background even if the activity is closed ..
You can accomplish this by implementing following ->
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = ... // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}
I think this is somehow helpful to you ..
If you want music playing in background, you should definitely use Service. Use activity only for UI-related operations. Since playing music is not UI-related operation, it should be done in Service. Please take a look here: http://developer.android.com/guide/topics/media/mediaplayer.html

MediaPlayer Service Android

I am new to Android. I am creating service for Media Player so that it can continue to play song even if i close the application. I have created activity for Media Player and it is having all the functionality like play , pause , next , previous , seekbar and also includes oncompletionlistener . All works excellent. But Now i want that all should be managed by service.
I have Created MyService Class :
public class MyService extends Service {
public static MediaPlayer mp;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
mp = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
But in my player activity i have created ArrayList for Songlist from which i am taking currentsongIndex and through it i am maintaining all the functionality like next , previous and all.. Now in service how do i get songlist which is also required in my activity ?? Where should i create MediaPlayer object mean in service or activity ??
for MediaPlayer I have reffered http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ . For my media player code you can refer this site. Thanks.
Pleaze clear my doubt. I am so confused. Reply me soon..
You are on the right track. I have adapted from the SDK Samples; this is how I do it and it works great.
From your ArrayList (in your activity NOT from the Service) call
onListItemClick
and start an intent that starts the music service:
startService(new Intent(MusicService.ACTION_PLAY));
In your manifest you will need to add:
<intent-filter>
<action android:name="com.blah.blah.action.PLAY" />
<xxx xxx>
</intent-filter>
And of course in your Music Service you need to receive the Intent:
public int onStartCommand(Intent intent, int flags, int startId) {
String action = intent.getAction();
if (action.equals(ACTION_PLAY))
processPlayRequest();
}
Be sure to add Intents for skip, rewind, stop etc.
Let me know if this helps.
Getting the app to run in background should be taken care of by the 'Service' itself.
Try following this example http://www.vogella.com/articles/AndroidServices/article.html
A service is designed to work in the background.
I went through exactly the same thing! It's a long haul to develop even a really great mp3 player app. The answer is long.
Here are a few resources that really helped me. Android has a article on this very thing in their developer docs:
http://developer.android.com/guide/components/services.html
Pay attention to what it says at the bottom of this long article about bound services and running in the foreground.
Additionally, managing player state is what caused me the most headaches.
You'll also want to take a look at threading because spawning that new service will still execute everything on the Main UI Thread, sounds crazy but true. Take a look at the ExecutorService for managing thread pools. I wish I could tell you it was easier.
Unfortunately most of my formal training from all over the web but with android services comes from a paid site:
http://www.pluralsight.com/training/Courses/TableOfContents/android-services
It is a good resource for all programmers I think but has great sections about many aspects of android programming that are only covered briefly at other tutorial sites.
The resources at Vogella are good also, mentioned above.

Music service stops when the activity is stopped/closed?

I've created a music service for my application (a music player), and after making some tests I'm observing a behaviour that's causing me a headache as I don't know how to solve it.
For testing purposes, I've modified the service so, as soon as it's started, it plays a specific mp3 file from my sd card. Also, I've modified the application so the first activity is started, it starts the service, and then it calls "finish()".
Ok, so... I launch the application, and the first activity starts, my service starts and plays the music, the activity finishes and the application is closed and... the music is stopped and after some seconds the service is restarted (I'm using the START_STICKY flag, so I suppose that's normal).
I don't want the music to be stopped when I close the application, or in another words, I don't want the service to be stopped (and then restarted because it's been stopped) when my application is closed.
Right now, to control the music service, I start the service and then I bind to it so I can call the service functions I've defined in an interface.
Any ideas?
Thanks!
EDIT:
This is an example of what my application and service do (in the tests I'm doing).
Activity:
public class FirstActivity extends SherlockFragmentActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(this, MyService.class));
...
// Here is a postDelayed that will run after 2 seconds and call finish()
}
}
Service:
public class MyService extends Service {
private MediaPlayer mPlayer;
#Override
public void onCreate() {
mPlayer = new MusicPlayer(this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Here is the code that plays the music using MediaPlayer
return START_STICKY;
}
}
do not forget to put that the service is remote in your manifest application tag:
<service
android:name="somepackage.PlayerService"
android:label="Player Service"
android:process=":remote"/>
Note, that the remote name can be something else, so you can have more than one services that are not bound to the main application process

How to check something at regular intervals?

Beginner here, I have a simple question.
In Android what would be the best what to check for something at regular intervals?
Please bear with me, I'll try to explain the best I can --
For example my audio app is very simple, a main activity and a service. The main activity has a UI with two buttons, start and stop audio. I press start and the audio service starts. Likewise when I click Stop the service stops and the audio ends. If isLooping() is hard-coded to true there is no issue because the audio never ends unless I hit stop button, which stops the audio service and also resets the button states.
This is an issue now because I set isLooping() to false so the audio doesn't loop. So the audio will stop playing but the service is still running.
I want to be able to detect when the audio stops so I can set the states of the UI buttons. So I need something that is always checking whether audio is playing (i.e. check player.isPlaying() so I can end the service and set the enable/disable state of the buttons.
I figured out binding to the service so I can access the MediaPlayer controls via my main activity so I know the code to check if it's playing, but WHERE do I put this code so it's checked all the time?
Am I making sense? I know this is probably very simple. Thanks for any help.
You can repeat it with the TimerTask and Timer. Code below:
public final void RepeatSoundFunction(){
t = new Timer();
tt = new TimerTask() {
#Override
public void run() {
mp.seekTo(0); //Reset sound to beginning position
mp.start(); //Start the sound
t.purge(); //Purge the sound
}
};
t.schedule(tt, 10*1000); //Schedule to run tt (TimerTask) again after 10 seconds
}
then you set a MediaPlayer onCompletionListener and in there you put this.
Inside the run-code you can check for other things than
music, I just show an example with the audio.

Categories

Resources