I'm developing a GPS tracking software on android. I need IPC to control the service from different activities. So I decide to develop a remote service with AIDL. This wasn't a big problem but now it's always running into the methods of the interface and not into those of my service class. Maybe someone could help me?
Here my AIDL file:
package test.de.android.tracker
interface ITrackingServiceRemote {
void startTracking(in long trackId);
void stopTracking();
void pauseTracking();
void resumeTracking(in long trackId);
long trackingState();
}
And the here a short version of my service class:
public class TrackingService extends Service implements LocationListener{
private LocationManager mLocationManager;
private TrackDb db;
private long trackId;
private boolean isTracking = false;
#Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
db = new TrackDb(this.getApplicationContext());
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onDestroy(){
//TODO
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent){
return this.mBinder;
}
private IBinder mBinder = new ITrackingServiceRemote.Stub() {
public void startTracking(long trackId) throws RemoteException {
TrackingService.this.startTracking(trackId);
}
public void pauseTracking() throws RemoteException {
TrackingService.this.pauseTracking();
}
public void resumeTracking(long trackId) throws RemoteException {
TrackingService.this.resumeTracking(trackId);
}
public void stopTracking() throws RemoteException {
TrackingService.this.stopTracking();
}
public long trackingState() throws RemoteException {
long state = TrackingService.this.trackingState();
return state;
}
};
public synchronized void startTracking(long trackId) {
// request updates every 250 meters or 0 sec
this.trackId = trackId;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 250, this);
isTracking = true;
}
public synchronized long trackingState() {
if(isTracking){
return trackId;
} else
return -1;
}
public synchronized void stopTracking() {
if(isTracking){
mLocationManager.removeUpdates(this);
isTracking = false;
} else
Log.i(TAG, "Could not stop because service is not tracking at the moment");
}
public synchronized void resumeTracking(long trackId) {
if(!isTracking){
this.trackId = trackId;
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 250, this);
isTracking = true;
} else
Log.i(TAG, "Could not resume because service is tracking already track " + this.trackId);
}
public synchronized void pauseTracking() {
if(isTracking){
mLocationManager.removeUpdates(this);
isTracking = false;
} else
Log.i(TAG, "Could not pause because service is not tracking at the moment");
}
public void onLocationChanged(Location location) {
//TODO
}
For easier access from the client I wrote a ServiceManager class which sets up the ServiceConnection and you can call the service methods. Here my code for this:
public class TrackingServiceManager{
private static final String TAG = "TrackingServiceManager";
private ITrackingServiceRemote mService = null;
private Context mContext;
private Boolean isBound = false;
private ServiceConnection mServiceConnection;
public TrackingServiceManager(Context ctx){
this.mContext = ctx;
}
public void start(long trackId) {
if (isBound && mService != null) {
try {
mService.startTracking(trackId);
} catch (RemoteException e) {
Log.e(TAG, "Could not start tracking!",e);
}
} else
Log.i(TAG, "No Service bound! 1");
}
public void stop(){
if (isBound && mService != null) {
try {
mService.stopTracking();
} catch (RemoteException e) {
Log.e(TAG, "Could not stop tracking!",e);
}
} else
Log.i(TAG, "No Service bound!");
}
public void pause(){
if (isBound && mService != null) {
try {
mService.pauseTracking();
} catch (RemoteException e) {
Log.e(TAG, "Could not pause tracking!",e);
}
} else
Log.i(TAG, "No Service bound!");
}
public void resume(long trackId){
if (isBound && mService != null) {
try {
mService.resumeTracking(trackId);
} catch (RemoteException e) {
Log.e(TAG, "Could not resume tracking!",e);
}
} else
Log.i(TAG, "No Service bound!");
}
public float state(){
if (isBound && mService != null) {
try {
return mService.trackingState();
} catch (RemoteException e) {
Log.e(TAG, "Could not resume tracking!",e);
return -1;
}
} else
Log.i(TAG, "No Service bound!");
return -1;
}
/**
* Method for binding the Service with client
*/
public boolean connectService(){
mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
TrackingServiceManager.this.mService = ITrackingServiceRemote.Stub.asInterface(service);
}
}
#Override
public void onServiceDisconnected(ComponentName name) {
if (mService != null) {
mService = null;
}
}
};
Intent mIntent = new Intent("test.de.android.tracker.action.intent.TrackingService");
this.isBound = this.mContext.bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
return this.isBound;
}
public void disconnectService(){
this.mContext.unbindService(mServiceConnection);
this.isBound = false;
}
}
If i now try to call a method from an activity for example start(trackId) nothing happens. The binding is OK. When debugging it always runs into the startTracking() in the generated ITrackingServiceRemote.java file and not into my TrackingService class. Where is the problem? I can't find anything wrong.
Thanks in advance!
Tobias
I need IPC to control the service from
different activities. So I decide to
develop a remote service with AIDL.
You do not need IPC to control the service from different activities. You may need IPC to control the service from different applications (i.e., separate APKs).
When debugging it always runs into the
startTracking() in the generated
ITrackingServiceRemote.java file and
not into my TrackingService class.
Your activity has a client-side proxy representing the service interface. The service itself is supposed to be running in a completely separate process from a completely separate APK.
I recommend that you get rid of the AIDL and switch back to the local binding pattern, at least long enough to get your activity and service working. Then, and only then, should you pull them apart into separate APKs, if that is indeed the desired end.
Related
i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?
I am developing an app that connects to a Chromecast, everything works fine when I do it from one activity, the problem is, that I want that activity to be fullscreen with no action bar, and no soft buttons. I am achiving that, hiding them when the users connects to the Chromecast, but it would be better if the users connect from the first activity (with action bar) and then goes to the second activity and the magic occurs there. But I can't pass the session between the activities. I have follow this tutorial to make the communication with the chromecast but tried to change a little to make the 2 acitivites communication.
Of course I have tested it and it returns a NullPointerException.
ConnectionFailedListener.java
public class ConnectionFailedListener implements GoogleApiClient.OnConnectionFailedListener {
private String TAG;
private MyConnectionCallbacks myConnectionCB;
public ConnectionFailedListener(String _TAG)
{
this.TAG=_TAG;
}
private void setMyConnectionCallBack(MyConnectionCallbacks _ConnectionCallbacks)
{
this.myConnectionCB = _ConnectionCallbacks;
}
#Override
public void onConnectionFailed(ConnectionResult result)
{
Log.e(TAG, "onConnectionFailed ");
myConnectionCB.teardown();
}
}
Channel.java
public class EventChannel implements Cast.MessageReceivedCallback
{
private Context myContext;
private String TAG;
/**
* #return custom namespace
*/
public EventChannel(Context _context, String _TAG)
{
this.myContext = _context;
this.TAG = _TAG;
}
public String getNamespace()
{
return myContext.getString(R.string.namespace);
}
/*
* Receive message from the receiver app
*/
#Override
public void onMessageReceived(CastDevice castDevice, String namespace,String message)
{
Log.d(TAG, "onMessageReceived: " + message);
}
}
ConnectionCallbacks.java
public class MyConnectionCallbacks implements GoogleApiClient.ConnectionCallbacks
{
private String TAG;
private Context myContext;
public CastDevice mSelectedDevice;
private GoogleApiClient mApiClient;
private boolean mWaitingForReconnect;
private EventChannel mEventChannel;
private String mSessionId;
private boolean mApplicationStarted;
private EventChannel myChannel;
public MyConnectionCallbacks(Context _context, String _TAG)
{
this.myContext=_context;
this.TAG = _TAG;
}
public void setApiClient(GoogleApiClient _newApiClient)
{
this.mApiClient = _newApiClient;
}
#Override
public void onConnected(Bundle connectionHint)
{
Log.d(TAG, "onConnected");
if (mApiClient == null)
{
// We got disconnected while this runnable was pending execution.
return;
}
try
{
if (mWaitingForReconnect)
{
mWaitingForReconnect = false;
// Check if the receiver app is still running
if ((connectionHint != null) && connectionHint.getBoolean(Cast.EXTRA_APP_NO_LONGER_RUNNING))
{
Log.d(TAG, "App is no longer running");
teardown();
}
else
{// Re-create the custom message channel
try
{
Cast.CastApi.setMessageReceivedCallbacks(mApiClient,mEventChannel.getNamespace(),mEventChannel);
}
catch (IOException e)
{
Log.e(TAG, "Exception while creating channel", e);
}
}
}
else
{// Launch the receiver app because is connected
Cast.CastApi.launchApplication(mApiClient,myContext.getString(R.string.app_id), false).setResultCallback(
new ResultCallback<Cast.ApplicationConnectionResult>()
{
#Override
public void onResult(Cast.ApplicationConnectionResult result) {
Status status = result.getStatus();
Log.d(TAG,"ApplicationConnectionResultCallback.onResult: statusCode"+ status.getStatusCode());
if (status.isSuccess())
{
ApplicationMetadata applicationMetadata = result.getApplicationMetadata();
mSessionId = result.getSessionId();
String applicationStatus = result.getApplicationStatus();
boolean wasLaunched = result.getWasLaunched();
Log.d(TAG,"application name: "+ applicationMetadata.getName()
+ ", status: "+ applicationStatus
+ ", sessionId: "+ mSessionId
+ ", wasLaunched: "+ wasLaunched);
mApplicationStarted = true;
// Create the custom message channel
mEventChannel = new EventChannel(myContext,TAG);
try
{
Cast.CastApi.setMessageReceivedCallbacks(mApiClient,mEventChannel.getNamespace(),mEventChannel);
}
catch (IOException e)
{
Log.e(TAG,"Exception while creating channel",e);
}
// set the initial instructions on the receiver
sendMessage("starting from mobile");
}
else
{
Log.e(TAG,"application could not launch");
teardown();
}
}
});
}
}
catch (Exception e)
{
Log.e(TAG, "Failed to launch application", e);
}
}
#Override
public void onConnectionSuspended(int cause)
{
Log.d(TAG, "onConnectionSuspended");
mWaitingForReconnect = true;
}
public void sendMessage(String message)
{
if (mApiClient != null && mEventChannel != null)
{
try
{
Cast.CastApi.sendMessage(mApiClient,mEventChannel.getNamespace(), message)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status result)
{
if (!result.isSuccess())
{
Log.e(TAG, "Sending message failed");
}
}
});
}
catch (Exception e)
{
Log.e(TAG, "Exception while sending message", e);
}
}
else
{
Toast.makeText(myContext, message, Toast.LENGTH_SHORT).show();
}
}
public void teardown()
{
Log.d(TAG, "teardown");
if (mApiClient != null)
{
if (mApplicationStarted)
{
if (mApiClient.isConnected() || mApiClient.isConnecting())
{
try
{
Cast.CastApi.stopApplication(mApiClient, mSessionId);
if (myChannel != null)
{
Cast.CastApi.removeMessageReceivedCallbacks(mApiClient,myChannel.getNamespace());
myChannel = null;
}
}
catch (IOException e)
{
Log.e(TAG, "Exception while removing channel", e);
}
mApiClient.disconnect();
}
mApplicationStarted = false;
}
mApiClient = null;
}
mSelectedDevice = null;
mWaitingForReconnect = false;
mSessionId = null;
}
}
MediaRouterCallback.java
public class MyMediaRouterCallback extends MediaRouter.Callback {
private GoogleApiClient mApiClient;
private Cast.Listener mCastListener;
private Context myContext;
private ConnectionFailedListener mConnectionFailedListener;
public MyConnectionCallbacks mConnectionCallbacks;
public String TAG;
//private String mSessionId;
public MyMediaRouterCallback(Context _context, String _TAG)
{
this.myContext = _context;
this.TAG = _TAG;
mConnectionCallbacks = new MyConnectionCallbacks(myContext,TAG);
}
#Override
public void onRouteSelected(MediaRouter router, MediaRouter.RouteInfo info) {
Log.d(TAG, "onRouteSelected");
mConnectionCallbacks.mSelectedDevice = CastDevice.getFromBundle(info.getExtras());
launchReceiver();
}
#Override
public void onRouteUnselected(MediaRouter router, MediaRouter.RouteInfo info) {
Log.d(TAG, "onRouteUnselected: info=" + info);
mConnectionCallbacks.teardown();
mConnectionCallbacks.mSelectedDevice = null;
}
private void launchReceiver()
{
try
{
mCastListener = new Cast.Listener() {
#Override
public void onApplicationDisconnected(int errorCode) {
Log.d(TAG, "application has stopped");
mConnectionCallbacks.teardown();
}
};
//Constructors for Google Play Services Connection
//mConnectionCallbacks = new MyConnectionCallbacks(myContext,TAG);
mConnectionFailedListener = new ConnectionFailedListener(TAG);
Cast.CastOptions.Builder apiOptionsBuilder =
Cast.CastOptions.builder(mConnectionCallbacks.mSelectedDevice, mCastListener);
// ApiClient to Connect to Google Play services
mApiClient = new GoogleApiClient.Builder(myContext)
.addApi(Cast.API, apiOptionsBuilder.build())
.addConnectionCallbacks(mConnectionCallbacks)
.addOnConnectionFailedListener(mConnectionFailedListener)
.build();
mConnectionCallbacks.setApiClient(mApiClient);//setting ApiClient to achieve sendMessage
//Connect to Google Play services
mApiClient.connect();
}
catch (Exception e)
{
Log.e(TAG, "Failed launchReceiver", e);
}
}
}
FirstActivity (where the chromecast is connected)
public class ConnectCastActivity extends ActionBarActivity {
private static final String TAG = ConnectCastActivity.class.getSimpleName();
private MediaRouter mMediaRouter;
private MediaRouteSelector mMediaRouteSelector;
private MediaRouter.Callback mMediaRouterCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(android.R.color.transparent));
setContentView(R.layout.activity_connect_cast);
// Configure Cast device discovery
mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mMediaRouteSelector = new MediaRouteSelector.Builder().addControlCategory(CastMediaControlIntent.categoryForCast(getResources().getString(R.string.app_id))).build();
mMediaRouterCallback = new MyMediaRouterCallback(getApplicationContext(),TAG);
TextView myTextView = (TextView)findViewById(R.id.txt_helloworld);
myTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});
}
#Override
protected void onStart() {
super.onStart();
// Start media router discovery
mMediaRouter.addCallback(mMediaRouteSelector, mMediaRouterCallback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY);
}
#Override
protected void onStop() {
// End media router discovery
Log.w(TAG, "onStop");
//mMediaRouter.removeCallback(mMediaRouterCallback);
super.onStop();
}
#Override
public void onDestroy() {
Log.w(TAG, "onDestroy");
// mMediaRouterCallback.onRouteUnselected(mMediaRouter,null);
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_connect_cast, menu);
MenuItem mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item);
MediaRouteActionProvider mediaRouteActionProvider = (MediaRouteActionProvider) MenuItemCompat.getActionProvider(mediaRouteMenuItem);
// Set the MediaRouteActionProvider selector for device discovery.
mediaRouteActionProvider.setRouteSelector(mMediaRouteSelector);
return true;
}
}
SecondActivity (the one that will send the message)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MediaRouter mMediaRouter = MediaRouter.getInstance(getApplicationContext());
mConnectionCallbacks = new MyConnectionCallbacks(getApplicationContext(),TAG);
setContentView(R.layout.activity_main);
//What should I put here?
}
If you have an application with multiple activities, you are better off if you do not tie the cast connectivity and related states to any of those activities, instead you can have a singleton, or use your Application instance or use a background service or ... to maintain the connection and access the required pieces that are maintained in that global place. If it fits your requirement, you might want to use the CastCompanionLibrary that already does most of the routine stuff for you; if not, you can take a look at it and the see how the CastVideos sample app uses that and try to do something similar for your application.
I am downloading objects(Videos) from aws s3 bucket. Once i call :
TransferManager transferManager = new TransferManager(s3client);
GetObjectRequest getRequest = new GetObjectRequest(bucket, entity.getName());
String s="";
download = transferManager.download(bucket, entity.getName(), f);
all the objects are downloading at background by default even if i exit my application or put my app on background.
BUT if u force close (means i long press my home button and close my application from running list)my application all the objects stops downloading
What are the ways to make downloading running at back even if application stops...
I tried with service as well:
public class MyDownloadingService extends Service {
public static Download download;
File f;
public static ArrayList<DownloadEntity> downloadList;
public class LocalBinder extends Binder {
public MyDownloadingService getService() {
return MyDownloadingService.this;
}
}
private final LocalBinder mBinder = new LocalBinder();
#Override
public void onCreate() {
super.onCreate();
// downloadList=new ArrayList<DownloadEntity>();
//Toast.makeText(this, "Service Created", 300);
}
#Override
public void onDestroy() {
super.onDestroy();
//Toast.makeText(this,"Service Destroy",300);
}
#Override
public void onLowMemory() {
super.onLowMemory();
//Toast.makeText(this, "Service LowMemory", 300);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Toast.makeText(this,"task perform in service",300);
if (intent!=null) {
String bucket = "", object = "", file = "";
if (intent.getExtras() != null) {
if (intent.getExtras().getString("bucket") != null) {
bucket = intent.getExtras().getString("bucket");
}
if (intent.getExtras().getString("object") != null) {
object = intent.getExtras().getString("object");
}
if (intent.getExtras().getString("file") != null) {
file = intent.getExtras().getString("file");
}
new downloader(bucket, object, file).execute();
}
}
return android.app.Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static void getList(){
if (downloadList!=null) {
SoapCostants.downloadList = downloadList;
}
}
public class downloader extends AsyncTask<String, String, String> {
String bucket,object;
String file;
public downloader(String bucket,String object,String file) {
this.object=object;
this.file=file;
this.bucket=bucket;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
File f=new File(file);
// Toast.makeText(this,"Service start",300);
TransferManager transferManager = new TransferManager(S3Getter.s3client);
try {
GetObjectRequest getRequest = new GetObjectRequest(bucket, object);
String s="";
download = transferManager.download(bucket, object, f);
DownloadEntity entity2=new DownloadEntity();
entity2.setKey(object);
entity2.setValue(download);
if (downloadList==null){
downloadList=new ArrayList<DownloadEntity>();
}
SoapCostants.downloadList.add(entity2);
downloadList.add(entity2);
for (int i = 0; i < SoapCostants.downloadedList.size(); i++) {
//SoapCostants.downloadedList
if (object.equalsIgnoreCase(SoapCostants.downloadedList.get(i).getName())) {
SoapCostants.downloadedList.get(i).setIsDownloading("yes");
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
}
i used start_sticky for services. But if my application was in background for long time it gets closed. or when i force close my application it gets closed.
i checked it by calling getList() of service class above. But it returns null.
The TransferManager is hosted in your application. Once the application is killed, everything it owns will be killed too, TransferManager included. When TransferManager is killed, it invokes shutdown() in finalized() to terminate all transfers running in its thread pool. If you really want it to continue to run, then you'd better try Service which can survive upon application termination. See http://developer.android.com/guide/components/services.html for more details.
I am creating bound service for socket connection.Which means it is creating a long polling connection and listens my server.If user closes the app in task manager my service is killing i have no problem with this.But when user presses the back button I am calling activity.finish() method for close app.But with this method my service doesn't kill,it is still connected to socket server.
Is this normal ? And Could be this drain the battery ?
My service:
public class SocketService extends Service {
//you need constants to tell servise and activity what you are sending a message for
public static final int REGISTER_CHAT_ACTIVITY = 1;
public static final int MESSAGE_RECEIVED = 2;
final Messenger mMessenger = new Messenger(new IncomingHandler());
Messenger chat;
private Socket socket;
#Override
public void onCreate() {
try {
socket = IO.socket("ip");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("connected", new Emitter.Listener() {
#Override
public void call(Object... args) {
}
}).on("message", new Emitter.Listener() {
#Override
public void call(Object... args) {
try {
chat.send(android.os.Message.obtain(null, MESSAGE_RECEIVED, args[0]));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
//and add all the other on listeners here
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (socket != null) {
socket.disconnect();
socket.connect();
} else {
try {
socket = IO.socket("ip");
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
class IncomingHandler extends Handler {
#Override
public void handleMessage(android.os.Message msg) {
switch(msg.what){
case REGISTER_CHAT_ACTIVITY:
chat = msg.replyTo;
break;
}
}
}
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
}
I had something similar a while ago i solved the issue by using shared preferences.(Note: I dont think it's the best answer but it solved my problem)
I saved in preferences a boolean to register when i dont need the service anymore but lost reference of it.
public class YourService extends Service {
private YourService serv;
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
serv = this;
Then Somehwere on your code that the service does frequently.
if(!sharedPref.getBoolean("TurnOffService", false)){
serv.stopSelf();
}
Hope it helps.
Good Morning All,
I am currently buidling a media player for Android, and I am having trouble binding my player service to an Activity and pulling data from it. Bear with me...a lot of code follows.
My code---
Interface:
interface MyInterface{
void playFile( in String file);
void shuffle ();
String getPlayingData();
}
Service:
public class MyService extends Service {
public Context context;
public static String nowPlayingData = null;
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final MyInterface.Stub mBinder = new MyInterface.Stub() {
public void playFile(String file) throws DeadObjectException {
//Song playing method working great!
}
public void shuffle()throws DeadObjectException {
//This method picks a random song and passes it to nowPlayingData string
}
public String getPlayingData() throws RemoteException {
return nowPlayingData;
}
};
#Override
public void onCreate() {
//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
mp.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
//Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
mp.stop();
}
#Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
Main Screen Activity, Shuffle Button:
Service is started in onCreate. When I click on the shuffle button it uses a method in the service to play a random song, thus setting the nowPlayingData string.
public class mainMenu extends Activity {
private MyInterface mInterface;
private ServiceToken mToken;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent startedSvc = new Intent(mainMenu.this, MyService.class);
boolean success = this.bindService(
startedSvc, svcConn, Context.BIND_AUTO_CREATE);
this.startService(startedSvc);
findViewById(R.id.shuffle).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
sInterface.shuffle();
} catch (RemoteException e) {
e.printStackTrace();
}
Intent play_screen = new Intent(MyPlayer.getContext(), NowPlaying.class);
startActivity(play_screen);
}
Player Activity:
I want to bind to the service, and pull nowPlayingData over using the interfaces getPlayingData method.
public class NowPlaying extends Activity implements OnClickListener {
public static String nowPlayingData = null;
MyInterface mInterface;
boolean isConnected = false;
RemoteServiceConnection conn = null;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.now_playing);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
Log.i("Log", "Player Loaded");
bindService();
getData();
fillView();
}
public void fillView(){
//This method needs the nowPlayingData string to update the view
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService ) {
mInterface = MyInterface.Stub.asInterface((IBinder)boundService);
isConnected = true;
Log.d("Now Playing", "Service Connected" );
}
public void onServiceDisconnected(ComponentName className) {
sInterface = null;
// updateServiceStatus();
isConnected = false;
Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
getData();
}
};
private void bindService() {
if(conn == null) {
conn = new RemoteServiceConnection();
Intent i = new Intent();
i.setClassName("com.musicplayer.MyPlayer", "com.musicplayer.MyPlayer.MyService");
bindService(i, conn, Context.BIND_AUTO_CREATE);
Log.d( getClass().getSimpleName(), "bindService()" );
} else {
Toast.makeText(NowPlaying.this, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
}
}
private void getData() {
if(conn == null) {
Log.i("getData", "No Connection");
} else {
try {
String data = mInterface.getPlayingData();
Log.i("Data Recieved", data);
Log.d( getClass().getSimpleName(), "invokeService()" );
} catch (RemoteException re) {
Log.e( getClass().getSimpleName(), "RemoteException" );
}
}
}
}
I have been studying many examples online, and perhaps my mish-mash of attempts has caused this to not work. My code works all the way through to binding the service, but OnServiceConnected is never called, and conn remains null.
Any help you guys can provide is greatly appreciated.
Thanks,
Josh
Android will not make re-entrant event calls to your activity, so onServiceConnected can't be called until onCreate has returned