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?
Related
I recently worked in the project for making screen dimmer app but I stuck with one problem. In my app, there is MaterialAnimatedSwitch it works fine but when the app goes to the backhand, the switch is automatically off but the working of the app is perfectly continued. I want that the switch remains active or on whenever the user come back to the app interface.I use MaterialAnimatedSwitch so how to do this task.
i want the switch to be active or ON whenever the app resumes.
public class MainActivity extends AppCompatActivity {
int b1 = 40;
int b2 = 90;
DiscreteSeekBar bSeekBar;
ChatHeadService binder=null;
boolean isOn = false;
boolean mBounded;
public boolean isRunning=false;
ServiceConnection mConnection = new ServiceConnection() {
public void onServiceDisconnected(ComponentName name) {
mBounded = false;
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder) service;
mService = mLocalBinder.getServerInstance();
int brightness = mService.getBrightness();
int brightness2 = mService.getBrightness2();
seekBar.setProgress(brightness);
bSeekBar.setProgress(brightness2);
}
};
ChatHeadService mService;
RadioGroup radioGroup;
DiscreteSeekBar seekBar;
MaterialAnimatedSwitch aSwitch;
SharedPreferences sharedPrefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Fabric.with(this, new Kit[]{new Crashlytics()});
setContentView(R.layout.activity_main);
initInstances();
if (isOn && !isMyServiceRunning(ChatHeadService.class)) {
startService(new Intent(this, ChatHeadService.class));
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
for (RunningServiceInfo service : ((ActivityManager) getSystemService(Context.ACTIVITY_SERVICE)).getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
private void initInstances() {
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
seekBar = (DiscreteSeekBar) findViewById(R.id.seekBar);
bSeekBar = (DiscreteSeekBar) findViewById(R.id.brightnessSeekBar);
int b = sharedPrefs.getInt("b", 40);
int bb = sharedPrefs.getInt("bb", 90);
seekBar.setProgress(b);
bSeekBar.setProgress(bb);
aSwitch=(MaterialAnimatedSwitch)findViewById(R.id.switch1);
aSwitch.setClickable(sharedPrefs.getBoolean("isOn",false));
aSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(boolean b) {
if(b){
sharedPrefs.edit().putBoolean("isOn", true).apply();
isOn = true;
isRunning=aSwitch.isChecked();
startService(new Intent(MainActivity.this, ChatHeadService.class));
bindService();
}
else{
sharedPrefs.edit().putBoolean("isOn", false).apply();
isOn = false;
unBindService();
stopService(new Intent(MainActivity.this, ChatHeadService.class)); }
}
});
seekBar.setOnProgressChangeListener(new OnProgressChangeListener() {
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
b1 = value;
if (mService != null) {
mService.setBrightness(value, b2);
}
sharedPrefs.edit().putInt("b", value).apply();
}
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
});
bSeekBar.setOnProgressChangeListener(new OnProgressChangeListener() {
public void onProgressChanged(DiscreteSeekBar seekBar, int value, boolean fromUser) {
b2 = value;
if (mService != null) {
mService.setBrightness(b1, value);
}
sharedPrefs.edit().putInt("bb", value).apply();
}
public void onStartTrackingTouch(DiscreteSeekBar seekBar) {
}
public void onStopTrackingTouch(DiscreteSeekBar seekBar) {
}
});
}
#Override
protected void onStart() {
super.onStart();
if (isOn) {
bindService();
}
}
public void bindService() {
bindService(new Intent(this, ChatHeadService.class), mConnection,Context.BIND_AUTO_CREATE);
}
public void unBindService() {
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
}
#Override
protected void onPause() {
super.onPause();
isRunning=aSwitch.isPressed();
}
#Override
protected void onResume() {
super.onResume();
if(!isOn == aSwitch.isPressed()){
aSwitch.toggle();
}
}
}
Thanks in advance!
This is the screenshot when app is just open
This is the screenshot when night mode is ON
But When the going to backhand and then open the switch state changed
You are saving switch state in Shared preferences but not using it.
just add the following line above aswitch.setOnCheckedChangeListener
line, it will apply the state you saved in preferences
aSwitch.setChecked(sharedPrefs.getBoolean("isOn", false)); //false default
I suggest store value of your switch in one of your global variable and at time resume set it with the switch again like below:
public boolean isRunning = false;
#Override
protected void onPause() {
super.onPause();
isRunning = switchAler.isChecked();
}
#Override
protected void onResume() {
super.onResume();
binding.switchAler.setChecked(isRunning);
if(!isRunning == switchAler.isChecked()){
switchAler.toggle();
}
}
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;
}
I have spend all day dealing with this problem, I can't solve it. I am exhausted ,have no ideas what to do with it. Please help.
I want to create service that plays music in background.But receiving always null instead of service. Sometimes onServiceConnected is called, sometimes not
public class SoundService extends Service {
private IBinder myBinder = new MyLocalBinder() ;
private static boolean isSoundOn = false;
private static boolean isBgMusicOn = false;
private static int[] soundPoolIds = null;
private Context appContext = null;
private static SoundPlayer instance = null;
private MediaPlayer mp = null;
private SoundPool sndPool = null;
public class MyLocalBinder extends Binder {
public SoundService getService() {
return SoundService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return myBinder;
}
#Override
public void onCreate() {
super.onCreate();
// initSoundPools();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
// TODO Auto-generated method stub
super.onRebind(intent);
}
public long getCurrentTime() {
Time time = new Time();
time.setToNow();
return time.toMillis(false);
}
#SuppressLint("NewApi")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
private void initBackground() {
//Some magic code here
}
private void playMusic(MediaPlayer mp) {
//Some magic code here
}
private boolean musicIsPlaying(MediaPlayer mp) {
//Some magic code here
}
return false;
}
public void stopPlayingBackground() {
//Some magic code here
}
private void stopPlaying(MediaPlayer mp,boolean release) {
//Some magic code here
}
private int randInt(int min, int max) {
//Some magic code here
}
private void initSoundPools() {
//Some magic code here
}
public void turnSoundOn(boolean on) {
isSoundOn = on;
}
public void turnMusicOn(boolean on) {
isBgMusicOn = on;
}
public void playBackgroundMusic() {
//Some magic code here
}
public void playSoundFx(int id) {
//Some magic code here
}
}
}
Here is Class that extends another that in turn extends Activity
public class MainActivity extends LGame {
p
private static final String TAG = "DEBUG";
private static SoundService soundService;
private static boolean isBound = false;
private Thread serviceThread;
private ServiceConnection myConnection;
#Override
public void onGamePaused() {
}
#Override
public void onGameResumed() {
// TODO Auto-generated method stub
}
#Override
protected void onDestroy() {
}
if (soundService!=null) {
soundService.stopSelf();
}
super.onDestroy();
}
public static SoundService getSoundService() {
return soundService;
}
#Override
public void onMain() {
LTexture.ALL_LINEAR = true;
LSetting setting = new LSetting();
setting.width = 800;
setting.height = 480;
setting.fps = 30;
setting.landscape = true;
setting.showFPS = false;
myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
soundService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
serviceThread = new Thread(){
public void run(){
Intent intent = new Intent(getApplicationContext(), SoundService.class);
getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}
};
serviceThread.start();
register(setting, MainGame.class);
}
Firstly I tried to start service in main thread but nothing changed in both cases.
Of course I've declared service in manifest.
I hope someone can help me with this.
Thx for help in advance.
EDIT
I have mentioned that I have already tried to start it like in your post but nothing changed
HELP !! I have tried almost everything
You should never bind a service in different thread, if you want to do async tasks you should create the threads inside the service itself.
#Override
public void onMain() {
LTexture.ALL_LINEAR = true;
LSetting setting = new LSetting();
setting.width = 800;
setting.height = 480;
setting.fps = 30;
setting.landscape = true;
setting.showFPS = false;
myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
MyLocalBinder binder = (MyLocalBinder) service;
soundService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
Intent intent = new Intent(getApplicationContext(), SoundService.class);
getApplicationContext().bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
register(setting, MainGame.class);
}
From Android documentation :
The bindService() method returns immediately without a value.
So binding your service in the UI thread will not cause any delaying nor UI freezing.
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);
}
}
};
}
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 :)