Pausing a service - android

i am writing a music player example using services.i am able to start and stop the service by using the activity which is in other application.but now i need to pause the player.how can i do this because their are no onpause method in services

Media Player
utilise : pause();
to restart: prepare()
start()
**LocalService.java** public class LocalService extends Service {
private NotificationManager mNM;
MediaPlayer mMediaPlayer;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public void onDestroy() {
mNM.cancel(R.string.local_service_started);
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
public void startMp3Player() {
mMediaPlayer = MediaPlayer.create(getApplicationContext(),
R.raw.abc);
mMediaPlayer.start();
}
public void mp3Stop() {
mMediaPlayer.stop();
mMediaPlayer.release();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
}
**LocalServiceBinding.JAVA** public class LocalServiceBinding extends Activity {
private boolean mIsBound;
private LocalService mBoundService;
Button mPlayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_binding);
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
mPlayButton = (Button)findViewById(R.id.play);
mPlayButton.setOnClickListener(mPlayListener);
mPlayButton.setText("Play");
mPlayButton.setEnabled(false);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((LocalService.LocalBinder)service).getService();
Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
Toast.makeText(LocalServiceBinding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
bindService(new Intent(LocalServiceBinding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
mPlayButton.setEnabled(true);
}
};
private OnClickListener mPlayListener = new OnClickListener() {
public void onClick(View v) {
if(mPlayButton.getText() == "Play")
{
mBoundService.startMp3Player();
mPlayButton.setText("Stop");
}
else
{
mBoundService.mp3Stop();
mPlayButton.setText("Play");
}
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
if (mIsBound) {
unbindService(mConnection);
mIsBound = false;
mPlayButton.setEnabled(false);
}
}
};
}

Related

Android MediaPlayer to play video stream in Service screen rotation

I would like to create Activity with video player to play online stream using MediaPlayer class and SurfaceView to display. I'm creating MediaPlayer in separate Service so after screen rotation player don't have to be created again and don't have to connect to stream. My problem is that I don't know how to write Activity so my service wouldn't start every time after screen rotation.
My code below, in onStart() I start service but I don't know how to change it so it didn't start every time.
public class VideoPlayerActivity extends Activity implements SurfaceHolder.Callback {
private String path;
private SurfaceHolder vidHolder;
private SurfaceView vidSurface;
private VideoService videoService;
private Intent playIntent;
private boolean videoBound = false;
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
VideoService.VideoBinder binder = (VideoService.VideoBinder) service;
videoService = binder.getService();
videoService.setUrl(path);
videoBound = true;
if (vidHolder != null && videoService.getMediaPlayer() != null) {
videoService.getMediaPlayer().setDisplay(vidHolder);
videoService.playVideo();
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
videoBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
path = "https://archive.org/download/ksnn_compilation_master_the_internet/ksnn_compilation_master_the_internet_512kb.mp4"; //TODO tmp
playIntent = new Intent(this, VideoService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
vidSurface = (SurfaceView) findViewById(R.id.surfView);
vidHolder = vidSurface.getHolder();
vidHolder.addCallback(VideoPlayerActivity.this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
if (videoService != null && videoService.getMediaPlayer() != null) {
videoService.getMediaPlayer().setDisplay(vidHolder);
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
Log.d("ServiceConnection", "surfaceChanged " + i + " " + i1 + " " + i2);
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
Log.d("ServiceConnection", "surfaceDestroyed");
}
#Override
protected void onDestroy() {
super.onDestroy();
unbindService(musicConnection);
stopService(playIntent);
videoService = null;
}
}
Service class:
public class VideoService extends Service implements OnPreparedListener {
private MediaPlayer player;
private String path;
private final IBinder musicBind = new VideoBinder();
#Override
public void onCreate() {
Log.d("VideoService", "onCreate");
super.onCreate();
player = new MediaPlayer();
initMusicPlayer();
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
public void initMusicPlayer() {
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
}
public void playVideo() {
try {
player.setDataSource(path);
player.prepareAsync();
} catch (IOException e) {}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
public void setUrl(String url) {
path = url;
}
public MediaPlayer getMediaPlayer() {
return player;
}
public class VideoBinder extends Binder {
public VideoService getService() {
return VideoService.this;
}
}
}
You could either check for savedInstanceState being null to only start the service if the Activity is freshly created
if (savedInstanceState == null) {
startService...
}
or handle screen rotation yourself by adding
android:configChanges="orientation|keyboardHidden|screenSize"
to your Activity in manifest. Like this onCreate will not be called on rotation any more.

MediaPlayer.isPlaying throws an IllegalStateException Exception when screen goes off

AudioService initializes a MediaPlayer in the constructor, and exposes it to Activity.
public class AudioService extends Service implements MediaPlayer.OnPreparedListener {
private static final String TAG = "AudioService";
MediaPlayer mMediaPlayer = new MediaPlayer();
private final IBinder mBinder = new AudioBinder();
public void onCreate () {
mMediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mMediaPlayer.setOnPreparedListener(this);
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
public AudioService() {}
public boolean initPlayer(final String section){
try {
AssetFileDescriptor afd = getAssets().openFd("records/"+section+".mp3");
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mMediaPlayer.prepareAsync();
return true;
}catch (IOException e){
e.printStackTrace();
return false;
}
}
public MediaPlayer getPlayer(){
return mMediaPlayer;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onDestroy() {
if (mMediaPlayer != null) mMediaPlayer.release();
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
}
I don't know if it is OK to manipulate MediaPlayer directly from Activity.
public class PageActivity extends FragmentActivity {
String TAG = "PageActivity";
MediaPlayer player;
Handler handler = new Handler();
Button toggle;
boolean isSeekBarDragging = false;
String section;
AudioService audioService;
public ServiceConnection myConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className, IBinder binder) {
audioService = ((AudioService.AudioBinder)binder).getService();
if(audioService.initPlayer(section)){
player = audioService.getPlayer();
}else {
seekBar.setEnabled(false);
}
}
#Override
public void onServiceDisconnected(ComponentName className) {
audioService = null;
player = null;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
//bind service
bindService(new Intent(this, AudioService.class), myConnection, Context.BIND_AUTO_CREATE);
}
private void initButtons() {
toggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//!!! Exception is thrown here.
if(player.isPlaying()){
player.pause();
}else {
player.start();
}
}
});
}
#Override
protected void onStop(){
if(player.isPlaying()) player.stop();
handler.removeCallbacks(updater);
super.onStop();
}
}

How to Stop Service of Music Background?

I need a background music which is continuously playing through Activities. I want to stop my background music when clicking on the Home Button.
This is my Service Code.
public class BackgroundSoundService extends Service
{
private static final String TAG = null;
MediaPlayer player;
Context context;
private int length = 0;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.haha);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
#Override
public void onStart(Intent intent, int startId) {
player.start();
}
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {
player.stop();
player.release();
player = null;
}
public void onPause() {
player.pause();
}
public void onHomePressed(){
player.stop();
}
public void pauseMusic()
{
if(player.isPlaying())
{
player.pause();
length=player.getCurrentPosition();
}
}
public void resumeMusic()
{
if(player.isPlaying()==false)
{
player.seekTo(length);
player.start();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
}
#Override
public void onLowMemory() {
}
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(this, "music player failed", Toast.LENGTH_SHORT).show();
if(player != null)
{
try{
player.stop();
player.release();
}finally {
player = null;
}
}
return false;
}
}
This is my 1st Activity Class
public class AdventureTime extends Activity implements OnClickListener {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.story);
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
View story1 = this.findViewById(R.id.button1);
story1.setOnClickListener(this);
View story2 = this.findViewById(R.id.button2);
story2.setOnClickListener(this);
View story3 = this.findViewById(R.id.button3);
story3.setOnClickListener(this);
View back= this.findViewById(R.id.buttonback);
back.setOnClickListener(this);
}
#Override
public void onBackPressed(){
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
public void onClick(View v) {
switch(v.getId()){
case R.id.button1:
Intent button1 = new Intent(this, Story1.class);
startActivity(button1);
break;
case R.id.button2:
Intent button2 = new Intent(this, Story2.class);
startActivity(button2);
break;
case R.id.button3:
Intent button3 = new Intent(this, Story3.class);
startActivity(button3);
break;
case R.id.buttonback:
Intent buttonback = new Intent(this, MainActivity.class);
startActivity(buttonback);
break;
}
}
}
Add this in the Activity AdventureTime :
...
#Override
public void onPause(){
stopService(svc);
super.onPause();
}
...
if you want to pause music without stopping your service
try this
add this class in your service
public class LocalBinder extends Binder {
BackgroundSoundService getService() {
return BackgroundSoundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
and add this in your activity
private BackgroundSoundService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mBoundService = ((BackgroundSoundService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
replace
startService(svc)
with
bindService(svc, mConnection, Context.BIND_AUTO_CREATE);
and call the pause method in service whenever u need it
mBoundService.pauseMusic();
Why don't you try to listen to a dispatchKeyEvent instead? You could write:
#Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {
stopService(svc)
return true;
}
else
return super.dispatchKeyEvent(event);
}
on each of your activities.
on you mainActivity class add this.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_HOME) {
// pause or stop ung Background music here.
return true;
}
return false;
}

Null pointer exception when trying to play game background music with MediaPlayer

I have tried to copy:
[http://stackoverflow.com/questions/11490236/android-comprehensive-failproof-music-service-across-multiple-activites][1]
However, I am getting a null pointer exception on: StartupActivity.getService().musicStart(); Any ideas why this might be null? Here is my version of the (abridged) main java:
public class homescreenfruit extends Activity {
// bounded service
private static MusicService mBoundService;
// whetere service is bounded or not
private boolean mIsBound;
SharedPreferences myPrefs;
SharedPreferences.Editor prefsEditor;
boolean snd1 = true;
boolean snd2 = true;
boolean snd3 = true;
Handler myHandler = new Handler();
// int lastsongplayed=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homescreen);
doBindService();
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
final SharedPreferences.Editor prefsEditor = myPrefs.edit();
SoundManager.getInstance();
SoundManager.initSounds(this);
SoundManager.loadSounds();
{ // audio settings setup and run
snd3 = myPrefs.getBoolean("snd3return", true);
// ********************FIALS BELOW*********************
if (snd3==true){
homescreenfruit.getService().musicStart(); // FAILS HERE WITH NPE
}
ImageButton ibs3 = (ImageButton) findViewById(R.id.sound3); // this is the music
ibs3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.e("sound3 start : ", " yep");
ImageButton ibs3 = (ImageButton) findViewById(R.id.sound3);
if (snd3==true){
homescreenfruit.getService().musicStop();
prefsEditor.putBoolean("snd3return", false); snd3=false;
ibs3.setBackgroundResource(R.drawable.noteoff);
}
else if (snd3==false){
prefsEditor.putBoolean("snd3return", true); snd3=true;
ibs3.setBackgroundResource(R.drawable.noteon);
homescreenfruit.getService().musicStart();
// restart playing the music - add programming
homescreenfruit.getService().musicStart();
}
prefsEditor.commit();
}
});
final Runnable playmusic = new Runnable() //
{
public void run() {
if (snd3==true){
homescreenfruit.getService().musicStart();}
}
};
public void onBackPressed() {
if (snd3=true)
SoundManager.playSound(96, 1);
Log.e("onBack pressed", "onBack pressed");
finish();
}
public void onPause() {
super.onPause();
if (snd3=true)
{
homescreenfruit.getService().musicPause();
}
Log.e("onPause", "onPause");
}
public void onStop() {
super.onStop();
if (snd3=true){
homescreenfruit.getService().musicStop();
}
}
public void onResume() {
super.onResume();
if (snd3==true){
homescreenfruit.getService().musicStart();
}
}
public void onDestroy() {
super.onDestroy();
doUnbindService();
}
private final ServiceConnection mServiceConnection = new ServiceConnection() {
// removed override
public void onServiceConnected(ComponentName className, IBinder service) {
setService(((MusicService.LocalBinder) service).getService());
}
// removed override
public void onServiceDisconnected(ComponentName className) {
setService(null);
}
};
private void doBindService() {
Intent service = new Intent(getBaseContext(), MusicService.class);
// start service and bound it
startService(service);
bindService(new Intent(this, MusicService.class), mServiceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private void doUnbindService() {
if (mIsBound) {
// Detach existing connection.
unbindService(mServiceConnection);
mIsBound = false;
}
}
public static MusicService getService() {
return mBoundService;
}
private static void setService(MusicService mBoundService) {
homescreenfruit.mBoundService = mBoundService;
}
}
I have implemented CarefulMediaPlayer and Music Service both as well as per the link. Is that correct?

Android - Using method from a Service in an Activity?

I have the folowing method in a Service in my appplication:
public void switchSpeaker(boolean speakerFlag){
if(speakerFlag){
audio_service.setSpeakerphoneOn(false);
}
else{
audio_service.setSpeakerphoneOn(true);
}
}
So my question is whats the best and most effective way to be able to use this method in an Activity like follows
final Button speaker_Button = (Button) findViewById(R.id.widget36);
speaker_Button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
switchSpeaker(true); //method from Service
}
});
Do I have to do an AIDL or is there a simpler way?
There are 3 ways to binding service with your activity.
IBinder Implementation
Using Messanger
Using AIDL
Among these IBinder Implementation is the best suit in your case
Example of IBinder class
1. Server.java Service
public class Server extends Service{
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public Server getServerInstance() {
return Server.this;
}
}
public void switchSpeaker(boolean speakerFlag){
if(speakerFlag){
audio_service.setSpeakerphoneOn(false);
}
else{
audio_service.setSpeakerphoneOn(true);
}
}
}
2. Client.java Activity
public class Client extends Activity {
boolean mBounded;
Server mServer;
TextView text;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mServer.switchSpeaker(true);
}
});
}
#Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, Server.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(Client.this, "Service is disconnected", 1000).show();
mBounded = false;
mServer = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(Client.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder)service;
mServer = mLocalBinder.getServerInstance();
}
};
#Override
protected void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
}
Example of Messanger class
1. Server.java service
public class Server extends Service{
Messenger messenger = new Messenger(new LocalHandler());
Messenger clientMessenger;
static final int SysterTime = 0;
static final int AddHandler = 1;
List<Handler> mHandlers;
#Override
public void onCreate() {
super.onCreate();
mHandlers = new ArrayList<Handler>();
}
#Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
public class LocalHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SysterTime:
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
clientMessenger.send(Message.obtain(null, SysterTime, mDateFormat.format(new Date())));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case AddHandler:
clientMessenger = new Messenger((Handler) msg.obj);
try {
clientMessenger.send(Message.obtain(null, AddHandler, "Registed messanger"));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
super.handleMessage(msg);
}
}
}
2. Client.java Activity
public class Client extends Activity {
Messenger messenger;
boolean mBounded;
TextView text;
Button button;
Button register;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Message message = Message.obtain(null, Server.SysterTime, null);
try {
messenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
register = (Button) findViewById(R.id.register);
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Message message = Message.obtain(null, Server.AddHandler, new ClientHandle());
try {
messenger.send(message);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public class ClientHandle extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Server.SysterTime:
text.setText(msg.obj.toString());
break;
case Server.AddHandler:
text.setText(msg.obj.toString());
break;
default:
break;
}
super.handleMessage(msg);
}
}
#Override
protected void onStart() {
super.onStart();
bindService(new Intent(this, Server.class), mConnection, BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if(mBounded) {
unbindService(mConnection);
}
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
messenger = null;
}
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(Client.this, "Service is connected", 1000).show();
messenger = new Messenger(service);
mBounded = true;
}
};
}
Example of AIDL
1. IRemoteService.aidl
package com.example.bindservice.aidl;
interface IRemoteService {
String getMessage(String msg);
}
2. Server.java Service
public class Server extends Service{
#Override
public IBinder onBind(Intent intent) {
return mStub;
}
IRemoteService.Stub mStub = new IRemoteService.Stub() {
public String getMessage(String msg) throws RemoteException {
return msg;
}
};
}
3. Client.java Activity
public class Client extends Activity {
Button button;
TextView text;
boolean mBound;
IRemoteService mIRemoteService;
EditText etMsg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
etMsg = (EditText)findViewById(R.id.etMsg);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(mBound) {
try {
text.setText(mIRemoteService.getMessage(etMsg.getText().toString()));
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
});
}
#Override
protected void onStart() {
super.onStart();
bindService(new Intent(Client.this, Server.class), mConnection, BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
if(mBound) {
unbindService(mConnection);
mBound = false;
}
}
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mIRemoteService = null;
mBound = false;
}
public void onServiceConnected(ComponentName name, IBinder service) {
mIRemoteService = IRemoteService.Stub.asInterface(service);
mBound = true;
}
};
}
For more study you can refer this document
You have to expose service`s switchSpeaker method for clients. Define your .aidl file. Than bind to that service from your activity and simply call switchSpeaker.
See documentation
No other simple way to call this method, only if it static)
It's public, right :)
You can call bindService(Intent) method. Tale a look at ApiDemos, the class LocalServiceBinding.
In the callback method onServiceConnected, you can see:
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(LocalServiceBinding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
Now, use the service object (mBoundService) to call the method.
That's all :)

Categories

Resources