Get argument in service passed by activity.Media player.Android - android

please help me.I have an activity class and service class.Activity contain many buttons,so when user click it shows corresponding to button xml,and it must play corresponding sound.So i pass argument to service via putExtra,but i can't get it in service class.I get it in onStartCommand(),but it doesn't create or play it(so i don't know).How to solve this problem? Thank you.Here my code.
Activity.java
public void onClick(View arg0) {
if(arg0.getId()==R.id.Button01){
id=arg0.getId();
service = new Intent(this, MyService.class);
service.putExtra("ButtonA", id);
startService(service);
setContentView(R.layout.button_a);
}
....
Service.java
public void onCreate() {}
public int onStartCommand(Intent intent,int flags,int startId){
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
onHandleCommand(intent);
return START_STICKY;
}
private void onHandleCommand(Intent intent) {
if(button.equals(intent.getStringExtra("ButtonA"))){
player = MediaPlayer.create(this, R.raw.alma);
player.setLooping(false);
} else if(button.equals(intent.getStringExtra("ButtonAE"))){
player = MediaPlayer.create(this, R.raw.azhe);
player.setLooping(false);
}
}

Sorry I missed the point,onHandleCommand is your own method and you cannot override it.
Looks like your problem is here :
if(button.equals(intent.getStringExtra("ButtonA")))
What you passing as an extra to intent here?
What you are trying to compare?A Button and a String?

Related

Service in android 5.0+

I intended to work like this:
user switches on a feature: let say weather.
now weather data will come from server every 6 hours and will be shown to widget(remoteview), Now user switches off the feature. then widget should not show the weather or even refresh the data every 6 hours.
there are also 3-4 more features like that.
Now i had created a service to get all required data and than i have passed them to remoteview. For starting service i had used this in TimeOut Activity:
i = new Intent(TimeOut.this, TimeService.class);
i.setAction("com.example.Weather.Idle");
startService(i);
same for stopping service in switch off code:
stopService(i)
This code was working fine in API <=19. But in Lollipop it crashes at starting or stoping service.
I searched a lot in SO and also tried code for Binding or unbinding service but didn't help any.
Please help me with some code rather than just links...
Thanks in advance :)
Starting a service from any activity class
Intent intent = new Intent(MainActivity.this, BackgroundService.class);
startService(intent);
Here is service class code
public class BackgroundService extends Service{
public static Context appContext = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if (appContext == null) {
appContext = getBaseContext();
}
Toast.makeText(appContext, "Services Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
Add your logic here. You can do some work here using a thread. You can stop service whenever you want and i hope you will not find any crash.
I have faced similar issue with Service in 5.0. This is probably not the correct answer, but it works. You could try. I use EventBus to communicate with my services. So when I want to stop the service I'd send,
EventBus.getDefault().post(new ServiceEvent(ServiceEvent.STOP_SERVICE));
In the service,
public void onEvent(ServiceEvent event) {
if (event.getEvent() == ServiceEvent.STOP_SERVICE) {
methodToStopService();
}
}
private void methodToStopService() {
// do some stuff
stopSelf();
}
Make sure you register your service for events.
private void registerEventBus() {
EventBus eventBus = EventBus.getDefault();
if (!eventBus.isRegistered(this)) {
eventBus.register(this);
}
}
ServiceEvent class - It's my own class which I use with EventBus.
public class ServiceEvent {
private int event;
public static final int STOP_SERVICE = -1;
public ServiceEvent(int event) {
this.event = event;
}
public int getEvent() {
return event;
}
}

Android service not working

I'm trying to call a service class to update the value of a variable from my widget but it doesn't ever seem to get to the service class. I've had a look at some examples and I can't figure out what I'm doing wrong, and I don't really know very much about services yet. All help appreciated.
Service class
public class toggleMonitoringService extends Service{
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
Log.d("Me","creating service");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int startId, int something) {
// TODO Auto-generated method stub
String toggle = intent.getExtras().getString("Toggle");
Log.d("Me","Toggle : " + toggle);
if (toggle.equals("app1"))
{
UpdateWidgetService.monitorApp1 = !UpdateWidgetService.monitorApp1;
}
else if (toggle.equals("app2"))
{
UpdateWidgetService.monitorApp2 = !UpdateWidgetService.monitorApp2;
}
super.onStartCommand(intent, startId, something);
return 0;
}
}
Where I set up the intent and pending intent to handle the button click from the widget
Intent monitor1toggle = new Intent(this.getApplicationContext(),toggleMonitoringService.class);
monitor1toggle.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
monitor1toggle.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds);
monitor1toggle.putExtra("Toggle","app1");
PendingIntent monitor1 = PendingIntent.getService(getApplicationContext(), 0 , monitor1toggle,0);
remoteViews.setOnClickPendingIntent(R.id.firstappstatus, monitor1);
Try start service manually, wihtout using PendingIntent.
Better way is not to start service each time you need to do something, but to start it once, bind to it and use common method calls when you need something from the service.
For your example even a simple Thread would be more appropriate.

How to change the button text in an Activity when the activity receives broadcast?

I have a button in activity, now I want the button text change when a file finished decompress.I have done it like the following, and register the broadcast within the activity. My problem is how the get the activity instance in onReceive() method.
BroadcastReceiver receiveDecompressionNotification = new BroadcastReceiver(){
#Override
public void onReceive(Context c, Intent in) {
// TODO Auto-generated method stub
}
};
If you haven't found the solution by now, this might help you out, since it's about pretty much the same thing:
In my case I wanted to change a button's text, when my service has stopped playing a sound. So after playback following will be executed:
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp)
{
Intent i = new Intent("CHANGE_BUTTONSTATE");
i.putExtra("state", "play");
sendBroadcast(i);
}});
Like you I registred my BroadcastReceiver within the activity, which is doing the request. The corresponding onReceive() looks like this:
#Override
public void onReceive(Context context, Intent intent)
{
String state = intent.getExtras().getString("state");
playButton.setText(state);
}};
Where playButton has been declared in the activity's onCreate():
Button playButton = (Button) findViewById(R.id.playButton);
This approach might not be the best, since I'm a beginner - So any improvements and suggestions are appreciated.

Streaming Audio Using Service

Please take a look at my simple three-methods Service class that streams audio and play it directly.
public class StreamService extends Service {
private static final String TAG = "MyService";
String url;
MediaPlayer mp;
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
mp.stop();
}
#Override
public int onStartCommand(Intent intent, int flags, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
url = intent.getExtras().getString("url");
try {
mp.setDataSource(url);
mp.prepare();
mp.start();
} catch(Exception e){}
return START_STICKY;
}
}
In my activity, I have two buttons to play/stop the media file:
The playButton execute this:
Intent i = new Intent(this, StreamService.class);
i.putExtra("my_mp3_url_string");
startService(i);
The stopButton execute this:
stopService(new Intent(this, StreamService.class));
Now, I have some questions:
how I can implement the pauseButton? I want to pause the media running in the Service
Does my way of playing/stopping the media/Service correct ? Is there any better way?
How I can (periodically) update my Activity's UI from my Service? do I need to add something?
I would recommend not using the lifetime of the Service as a way to start and stop playback. Using that approach will mean that every time you want to start a new stream, the code will be slowed down even more by having to bring up a new Service. You can save some time by just having the same Service play everything. Though that doesn't mean it should remain running all the time.
To accomplish that (and to be able to pause), you'll need to bind to the Service after it is started. With the bound Service, you'll be able to make calls to it - such as pause, play, stop, etc.
Here are some links that should help you with what you're looking for:
Using a Service with MediaPlayer
Binding to a Service

Stopping Background Service Music

package com.falling.inairproandmark;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
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.bgmusic);
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
I don't understand coding much...
But what I'm trying to do is play the music thru-out the activities.
Let's say I have 10 activities... I want the music to play while i go through them and when I get a call or exit the application by pressing Home key... Music stops or at least pauses... how do i do that?
Thanks
Wahid
You need to launch separate service (different intent filter in the Manifest for the same serivce) in onStartCommand() you'll check the action of the intent i.e if the action has the same value as the one you specified for intent action in the manifest file and if the action matches the intent filter action name then just stop the service.
Example from one of my projects:
In the manifest file:
<service android:name=".MyPlayerService" android:permission="android.permission.MODIFY_AUDIO_SETTINGS">
<intent-filter >
.... some other filters
<action android:name="com.my.player.EXIT"/>
....
</intent-filter>
</service>
In the onStartCommand():
Here we can see the need of specifying action name, which is used to distinguish numerous actions within the same service.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("ON START COMMAND", "Huston, we have a lift off!");
if(intent.getAction().equals("com.my.player.EXIT")
{ // means that you have envoked action that will has to stop the service
MyPlayerService.this.stopSelf(); // See the note below
}else if(//some other actions that has to be done on the service)
}
Note:
Note that here you can simply stop the MediaPlayer from playing or pause it using .stop() or .pause(),or just terminate the service as I provided above.
Now back to the activity. Catching Home button is not good idea. But this you can do in the onDestroy() method, where the activity is not in the stack i.e just before it is destroyed. Here you just launch intent that will signal the service to stop working.
Example:
Intent exit = new Intent("com.my.player.EXIT"); //intent filter has to be specified with the action name for the intent
this.startService(exit);
Read more on Android Dev about stopSelf()
If you are trying this approach starting the MediaPlayer good practice will be to make the playing has its own action name in the intent filter, and do the same checking in the onStartCommand()

Categories

Resources