AIDL: Stub class methods not being called - android

I am using AIDL to pass objects from an Activity to a Service and am getting some strange behavior. To my understanding, the idea behind AIDL is to create an interface in a .aidl file, which android will then implement (partially) in a dynamically generated class. Android will create an abstract class called Stub, which you then need to instantiate and add the implementation of the methods which you defined in your .aidl interface. Once all of that is in place, the remote service can be instantiated, and the methods declared in the .aidl interface file (and defined in your instantiation of the Stub class) can be called.
That is my impression of how this mechanism works, however when I tried implementing it, I notice that the definitions for the methods I declared in the Stub class are not being run; instead what is being run is IBinder.transct()
Here is a snippet of what I'm trying to do:
This is implemented in my Service:
public final INetService.Stub mBinder = new INetService.Stub() {
public void sendInteger(String ID, int data) throws RemoteException {
// TODO Auto-generated method stub
}
public void sendString(String ID, String data) throws RemoteException {
ServiceConnectionHandler connHandler = new ServiceConnectionHandler(ID, data);
}
public void sendObject(String ID, NetMessage data) throws RemoteException {
ServiceConnectionHandler connHandler = new ServiceConnectionHandler(ID, data.getData());
}
};
And this is inside my Activity, which tries to use and talk to the service:
private INetService mService = null;
private NetServiceConnection conn = null;
class NetServiceConnection implements ServiceConnection
{
public void onServiceConnected(ComponentName name, IBinder service) {
mService = INetService.Stub.asInterface(service);
Log.d( "ADDERSERVICECLIENT","onServiceConnected" );
}
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
Log.d( "ADDERSERVICECLIENT","onServiceDisconnected" );
}
};
private void initService()
{
conn = new NetServiceConnection();
Intent i = new Intent();
i.setClassName( "framework.network", "framework.network.NetService" );
if (!bindService( i, conn, Context.BIND_AUTO_CREATE))
{
Toast.makeText(this, "bindService fails..", Toast.LENGTH_LONG).show();
}
}
....
mService.sendString((char)0, finalMessage);
The methods defined in INetService.Stub, like sendString, appear never to be called; clearly I'm missing something; any thoughts?
Thanks a lot!
Iva

Without the rest of your code, it is difficult to answer your question. See here and here for a pair of sample projects implementing a remote service and its client, using AIDL. Perhaps those implementations will give you some idea of where things are going wrong for you.

You must specify your class in an .aidl-file to make it public to IPC.
See http://fauxgrammer.com/?p=4 for more information.
Cheers!

I came across the same situation earlier today. In my case, I had two copies of the AIDL file in the client side and server side.
I was updating the AIDL file in on the client side, but totally forgot about updating the server-side AIDL. Since there's no type checking on Stub implementation it just ran but never returned anything.

Related

How to use interface to communicate between activities after process death?

I am building an SDK and need to implement callbacks between activities, without actually finish an activity. I previously used onActivityResult to provide results back to caller activity. However, this closes activity and I need to deliver callback, without finishing activity from SDK. My current implementation:
fun initializeSDK(){
SDK.getInstance().initialize(resultsCallbackImpl)
}
val resultsCallbackImpl:ResultsCallback = object : ResultsCallback {
override fun response1() {
}
override fun response2() {
}
};
For example, the client calls initializeSDK() from his activity after the button click. Then the client passes interface as parameter, which is set as a property in SDK singleton. Then I use that interface to return results.
The problem occurs after process death. The interface becomes null, because it is not serialized and I can't return callback to client anymore. How should I edit my code to tackle this issue? Is it even possible?
I know that client can initialize SDK in the application class, then it will be re-set after process death. However, such an approach will result in difficulty for the client to communicate results back to activity from application class.
Update:
Do a right click on the project tree and add a new AIDL file called IMyAidlInterface.aidl:
package com.test.aidlsample;
import com.test.aidlsample.MyData;
interface IMyAidlInterface {
List<MyData> getData(long id);
}
If you need to return objects to your client you need to declare and define them as parcelable and import them in aidl file too, here is the MyData.aidl that should be beside the other aidl file:
package com.test.aidlsample;
// Declare MyData so AIDL can find it and knows that it implements
// the parcelable protocol.
parcelable MyData;
and this is MyData.java in the java folder:
public class MyData implements Parcelable {
private long productId;
private String productName;
private long productValue;
public MyData(long productId, String productName, long productValue) {
this.productId = productId;
this.productName = productName;
this.productValue = productValue;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(this.productId);
dest.writeString(this.productName);
dest.writeLong(this.productValue);
}
protected MyData(Parcel in) {
this.productId = in.readLong();
this.productName = in.readString();
this.productValue = in.readLong();
}
public static final Parcelable.Creator<MyData> CREATOR = new Parcelable.Creator<MyData>() {
#Override
public MyData createFromParcel(Parcel source) {
return new MyData(source);
}
#Override
public MyData[] newArray(int size) {
return new MyData[size];
}
};
}
Now build the project so Stub class gets built. After a successful build continue with the service:
public class SdkService extends Service {
private IMyAidlInterface.Stub binder = new IMyAidlInterface.Stub() {
#Override
public List<MyData> getData(long id) throws RemoteException {
//TODO: get data from db by id;
List<MyData> data = new ArrayList<>();
MyData aData = new MyData(1L, "productName", 100L);
data.add(aData);
return data;
}
};
#Nullable
#Override
public IBinder onBind(Intent intent) {
return binder;
}
}
and add the service to the sdk manifest. If you are adding sdk as a dependency to the client like: implementation project(':sdk') you don't need to add AIDL files to client. If not, you have to add them and build the client application. Now, only remains to implement the client activity:
public class MainActivity extends AppCompatActivity {
IMyAidlInterface mService;
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mConnection = new ServiceConnection() {
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. We are communicating with our
// service through an IDL interface, so get a client-side
// representation of that from the raw service object.
mService = IMyAidlInterface.Stub.asInterface(service);
try {
List<MyData> data = mService.getData(1L);
updateUi(data);
} catch (RemoteException e) {
// In this case the service has crashed before we could even
// do anything with it; we can count on soon being
// disconnected (and then reconnected if it can be restarted)
// so there is no need to do anything here.
}
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
}
};
private void updateUi(List<MyData> data) {
//TODO: Update UI here
}
#Override
protected void onResume() {
if (mService == null) {
Intent serviceIntent = new Intent();
//CAREFUL: serviceIntent.setComponent(new ComponentName("your.client.package", "your.sdk.service.path"));
serviceIntent.setComponent(new ComponentName("com.test.sampleclient", "com.test.aidlsample.SdkService"));
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
} else {
try {
updateUi(mService.getData(1L));
} catch (RemoteException e) {
e.printStackTrace();
}
}
super.onResume();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
every time your client activity gets visibility, it gets data from sdk service. Just build your logic over this template. In sdk activity save data to a database and in service query them from database. I've used simple parameters in this sample.
I assumed your sdk is a library in the client app. If not, you need to do some small modifications maybe. And as I mentioned before you can find more details here: Android Interface Definition Language (AIDL). There are lots of samples and even more Q/A here in the SO on the subject. Good luck.
Original: You need to get callbacks from an activity that is currently invisible since your SDK activity is in front, right? To do that you can create a database for your SDK, persist data to your database and get data via an AIDL in the starting activity:
SdkService sdkService;
CallbackData callbackData
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
sdkService = SdkService.Stub.asInterface(service);
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
Log.e(TAG, "Service has unexpectedly disconnected");
sdkService = null;
}
};
in onCreate:
Intent i = new Intent()
i.setClassName("your.sdk.packageName", "your.sdk.service.path.and.name");
bindService(i, mConnection, Context.BIND_AUTO_CREATE);
and in whenever needed:
if(sdkService != null){
callbackData = sdkService.getCallbacks();
updateUI();
}
Just be careful getting a binder is an async job so if you call bindService and right after call sdkService.getCallbackData you get a NullPointerException. So you might want to move getCallbacks and updateUI inside the onServiceConnected and call bindService in onResume so every time activity becomes visible you would check if there is CallbackData so you can update your UI or whatever.
You cannot use interfaces directly to communicate between activities.
As soon as you start a new activity and new activity becomes visible android OS can kill 1st activity anytime (you can try this with a flag inside developer option "Don't keep activities"). So user of your SDK will complain about certain random "null pointer exception".
So, Now if you want to share data between current and previous screen, you might have to rethought your solution using Fragments.
Exposing your UI using a fragment and communicating back your result to activity which then would update proper fragment which needs the data.
I faced similar issue in one existing app which I was asked to fix. I switched entire app to fragments and single activity, first to release a hot fix.
The problem occurs after process death. The interface becomes null, because it is not serialised and I can't return callback to client anymore. How should I edit my code to tackle this issue? Is it even possible?
This is not possible. If the client process dies, all of its executing code - including your SDK - gets wiped away.
I know that client can initialise SDK in the application class, then it will be re-set after process death. However, such approach will result in difficulty for client to communicate results back to activity from application class.
So what? If the client Activity is restarted, it should call the SDK again to set a new callback instance which you can use from that point forward.
You can use a sharedviewmodel that is bound to both activities; have a mutablelivedata variable that you can observe from the two activities.
ideally on the first activity you can just put the value inside the mutablelivedata variable. Then on the second activity get the activity.
Follow the following link to give you a guideline.
ViewModel Overview

How to add additional handlings to Vpn disconnection in Android?

I have a custom implementation of VpnService, which needs to perform some additional cleanup on disconnection. Everything works fine when I am stoping VpnService from my application using service bindings, but I need to perform that cleanup when client is disconnecting from the Vpn using system dialog.
So, how can I catch the disconnection and add some handlings to that?
Get VPN Connection status on Android - this could be the solution, but it's not working on android 4+.
From logs point of view there are only two entries:
03-20 03:27:09.478: INFO/Vpn(504): Switched from org.my.package to [Legacy VPN]
03-20 03:27:09.478: DEBUG/Vpn(504): setting state=IDLE, reason=prepare
I just ran into the same issue. VpnService.onRevoke() is not called.
It turns out this happens because I use a custom IBinder defined via AIDL wich I return from onBind(). VpnService implements onBind() too and returns an instance of VpnService.Callback.
Which is implemented this way:
private class Callback extends Binder {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
if (code == IBinder.LAST_CALL_TRANSACTION) {
onRevoke();
return true;
}
return false;
}
}
VpnService.Callback does not use AIDL and just checks if the function code IBinder.LAST_CALL_TRANSACTION was sent. If so it executes onRevoke().
I integrated this code fragment in my custom IBinder implementation and now I receive the onRevoke() message. See the following example:
private final IBinder mBinder = new ServiceBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public final class ServiceBinder extends ICustomVpnService.Stub
{
... implement methods defined in ICustomVpnService.Stub ....
/**
* Intercept remote method calls and check for "onRevoke" code which
* is represented by IBinder.LAST_CALL_TRANSACTION. If onRevoke message
* was received, call onRevoke() otherwise delegate to super implementation.
*/
#Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException
{
// see Implementation of android.net.VpnService.Callback.onTransact()
if ( code == IBinder.LAST_CALL_TRANSACTION )
{
onRevoke();
return true;
}
return super.onTransact( code, data, reply, flags );
}
private void onRevoke()
{
// shutdown VpnService, e.g. call VpnService.stopSelf()
}
}
How did I figure it out? I searched the android source code for where onRevoke() is actually invoked. For that I find grepcode (android) pretty helpful. I often read the android source to understand how things work.
This happens if we use a custom IBinder defined via AIDL, which I return from onBind().
VpnService implements onBind() too and returns an instance of VpnService.Callback private-class.
Solution:
#Override
public IBinder onBind(Intent intent) {
String action = intent != null ? intent.getAction() : null;
if (action != null && action.equals(VpnService.SERVICE_INTERFACE)) {
return super.onBind(intent);
}
return yourBinder;
}
Note that above works as long as you never set VpnService.SERVICE_INTERFACE as action manually.
That action should only be set by Android's internal-logic (automatically, never by our code manually).

How connect paired bluetooth A2dp device on Android 4.2 using reflection?

I need to connect defined BT device by simple pressing the button.
The requirement is user shouldn't receive any notification dialogs as in case of using standard socket methods.
In my project I used this solution.
Code was next:
/**
* Return system service to work with A2DP
*
* #return bluetooth interface
*/
private static IBluetoothA2dp getIBluetoothA2dp() {
IBluetoothA2dp ibta = null;
try {
final Class serviceManager = Class.forName("android.os.ServiceManager");
final Method getService = serviceManager.getDeclaredMethod("getService", String.class);
final IBinder iBinder = (IBinder) getService.invoke(null, "bluetooth_a2dp");
final Class iBluetoothA2dp = Class.forName("android.bluetooth.IBluetoothA2dp");
final Class[] declaredClasses = iBluetoothA2dp.getDeclaredClasses();
final Class c = declaredClasses[0];
final Method asInterface = c.getDeclaredMethod("asInterface", IBinder.class);
asInterface.setAccessible(true);
ibta = (IBluetoothA2dp) asInterface.invoke(null, iBinder);
} catch (final Exception e) {
Log.e("Error " + e.getMessage());
}
return ibta;
}
It worked well until I've launched my app on Android 4.2. Now I'm unable to get IBluetoothA2dp interface because getService() method doesn't return me an IBinder with "bluetooth_a2dp" key.
Can someone help me?
Thanks in advance!
Finally got this working on 4.2. See the details here: http://code.google.com/p/a2dp-connect2/
It is quite different from 4.1 and before.
First call connect to the interface like this:
public static void getIBluetoothA2dp(Context context) {
Intent i = new Intent(IBluetoothA2dp.class.getName());
if (context.bindService(i, mConnection, Context.BIND_AUTO_CREATE)) {
} else {
// Log.e(TAG, "Could not bind to Bluetooth A2DP Service");
}
}
When the interface is returned it will call back to this:
public static ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
ibta2 = IBluetoothA2dp.Stub.asInterface(service);
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
}
};
ibta2 above is the IBluetoothA2dp interface.
On a related note, IBluetooth interface also changed. I use this to get the device alias name (the one the user can edit). This getRemoteAlias() function needed the mac address before. Now it takes a BluetoothDevice.
Keep in mind using these hidden interfaces is risky as they can and too often do change with new Android versions. I have been bit by that several times now. You really need to stay on top of it.
If some one needs the answer to something related to autopairing, can check my answer here.
https://stackoverflow.com/a/30362554/3920157

android send string to a service running in another process

I'm using this tutorial to help me use a service that will always run in the background even if the application itself is in the background, and I want to be able to transfer strings between My main process and the service.
The thing is, I see all over the place that marshaling strings is supposed to be very easy, but for more complex stuff one needs AIDL.
Since I only want to send string messages, I figured there must be a very easy way to do this, but I can't find it..
Thanks
I suppose a intent service is the way to go.
Howto create a intent service is explained here
Ok, this is a very hackish solution and very not OOP-like, but it's what I ended up doing, so I'm putting it here if anyone ever finds the needs for a simple, not very elegant (but working) solution.
I'm using sendBroadcast and broadcastReceiver to communicate between the service and the application.
The problem is that sending intents cross process for some reason removes all the extras, so I used SharedPrefences instead.
this is the (singleton) class I use in order to publish and subscribe to such string messaging.
The Visitor interface
public interface Visitor<T> {
public void visit(T element);
}
The publish subscriber interface:
public interface IPulishSubscribe {
/**
* Publish a new string message
*
* #param key The key to publish under
* #param text The message's content
*/
public void publish(String key, String text);
/**
* Subscribe to a message
*
* #param key The key to subscribe to
* #param visitor The visitor to handle the message when received
*/
public void subscribe(final String key, final Visitor<String> visitor);
}
The implementation
public class PublishSubscriber implements IPulishSubscribe {
private static IPulishSubscribe _instance = new PublishSubscriber();
private static Context _context;
// key -> handler, isn't of much use ATM, but you may need it for removals...
private Map<String, BroadcastReceiver> _subscribers = new HashMap<String, BroadcastReceiver>();
private PublishSubscriber() {
}
public static void init(Context context) {
_context = context;
}
public static IPulishSubscribe getInstance() {
return _instance;
}
#Override
public synchronized void publish(String key, String text) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(_context);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(key, text);
editor.commit();
_context.sendBroadcast(new Intent(key));
}
#Override
public synchronized void subscribe(final String key, final Visitor<String> visitor) {
BroadcastReceiver newSubscriber = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(_context);
String data = mPrefs.getString(key, null);
if (visitor != null) {
visitor.visit(data);
}
}
};
_context.registerReceiver(newSubscriber, new IntentFilter(key));
_subscribers.put(key, newSubscriber);
}
}
#Gal I like your answer. I dont know how fast it is but I hope it gets your job done.
I have been also confronting this problem. My first try was Messenger api, as demonstrated in Service documentation. It works but is rather limiting as to what you can send. You have to use a Bundle to send Strings.
Message msg = Message.obtain();
Bundle data = new Bundle(1); // size of Bundle array
data.putString("anything");
messenger.send(msg);
There are some nuances about reusing Message and Bundle objects in case you dont want to constantly create new objects.
I then tried AIDL in order to do interprocess communications easier. But after building the api, I clicked send send send and saw nothing.
The final way I tried was with files. Simple create a file, write to it and read from it on the other end. Sounds easy, but getting working properly is hard. Then you must understanding that the file will just grow and grow in size.
class Service_ extends Service
{
#Override protected void onCreate
{
new FileObserver("/sdcard/IFILE")
{
#Override public void onEvent(int event,String path)
{
if(event == MODIFY){} // Client sent message
}
}
}
}
class Client extends ServiceConnection
{
java.io.RandomAccessFile serviceWriter = new java.io.RandomAccessFile("/sdcard/IFILE");
}
Problem I have been facing is FileObserver seems to always be notified of file modification, yet my service fails to read the INIT instruction, which the client sents once so that the service can create the backing Console activity.
another thing is that Android is essentially Linux. Linux has raw methods for sending messages and file handle between processes. Atleast in the C api.

sendBroadcast(intent) gives a null pointer exception

This is my second post today as fixing the 1st post lead to another problem which I am really struggling on. I want to use Broadcasts and intent to send data packets back from a service to the UI. I managed to bind and start the service successfully
see my other post if you want history and code
The null pointer exception comes on the sendBroadcast() inside the service. The service class does have its constructor re-called after binding the UI to the service. This happens from another class so Context can not be easily used. So I guess the sendBroadcast has no-where to go :(
I suspect this is my problem...the re-calling of the Service constructor after the initial binding. I have onDestroy, onPause and onResume covered with binding an unbinding.
Any ideas or suggestion would be great or maybe I am just going about this wrong is there another way?
EDIT
The previous problem of binding is now solved and due to me being new to the forums a slight delay in accepting the answer...sorry.
The class diagram is like this (it is ported C#code)
Activity doBind (on Curve.class)---> Activity starts a worker class (not treated as a service) Comm.class with a Handler for some comms--> the Comm starts another worker class --> previous worker class finally calls new Curve.class.
It is this last stage Curve.class where the sendBroadcastReceiver() then throws a nullpointer ref becasue the binder is lost.
I tested the broadcastreceiver just with a simple timer cutting out the worker classes in between and it works fine. Problems start when the Curve.class is recalled later further down the hierarchy and the binder gets nulled or "lost".
I removed all references of the binder from Curve except in onBind(). This might not be a good idea. Again the code below does work if used with a simple timer started directly from the UI (no other worker classes).
Some more code here:
The service
public class Curve extends Service
{
private NewCurvePointEventArgs newpoint = null;
private static final String TAG = "Curve";
Intent intent;
int counter = 0;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
IBinder mBinder = new LocalBinder<Curve>(this);
return mBinder;
}
#Override
public void onStart(Intent intent, int startId) {
}
#Override
public void onDestroy() {
}
public Curve(){
}
private void refreshintent(NewCurvePointEventArgs tmp)
{
ArrayList<String> thepoint = new ArrayList<String>();
thepoint.add()//various things added here
Bundle bundle = new Bundle();
// add data to bundle
bundle.putStringArrayList("New_Point", thepoint);
intent = new Intent();
intent.setAction(NEWCURVE_POINT);
intent.putExtra("NEW_POINT", bundle
sendBroadcast(intent);
}
The activity has this code now. the doBind() is called after the onCreate of the activity.
private BroadcastReceiver CurveReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Curve.NEWCURVE_POINT)) {
displaynewpoint(intent);
}
}
};
private ServiceConnection CurveServiceConncetion = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
// TODO Auto-generated method stub
CurveService = ((LocalBinder<Curve>) service).getService();
}
#Override
public void onServiceDisconnected(ComponentName name) {
// TODO Auto-generated method stub
CurveService = null;
}
};
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
}
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
if(D) Log.e(TAG, "--- ON DESTROY ---");
unregisterReceiver(CurveReceiver);
unbindService(CurveServiceConncetion);
}
public void doBind(){
Boolean tmp;
tmp = bindService(new Intent(this, Curve.class), CurveServiceConncetion, Context.BIND_AUTO_CREATE);//Context.BIND_AUTO_CREATE
IntentFilter filter = new IntentFilter(Curve.NEWCURVE_POINT);
registerReceiver(CurveReceiver, filter);
}
This problem to me is because the Curve.class has its constructor called again after the initial doBind().
Surely there must be a way around this otherwise I have to load my worker classes closer in hierarchy to the UI with the code from Curve.class???
EDIT
Curve is an object that processes data, constants etc sent from an external machine and contains the processed data in arrays.
The logCat did of course exist I just wasn't looking in the right place here it is
ARN/System.err(10505): java.lang.NullPointerException
WARN/System.err(10505): at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:271)
WARN/System.err(10505): at pi.droid.Core.Curve.refreshintent(Curve.java:206)
WARN/System.err(10505): at pi.droid.Core.Curve.AddPoint(Curve.java:400)
WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$CommMeasurement.AddPoint(CommMeasure.java:363)
WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$GenericCommMeasurement.TryProcessData(CommMeasure.java:168)
WARN/System.err(10505): at pi.droid.Core.Comm.CommMeasure$CommMeasurement.ProcessData(CommMeasure.java:302)
WARN/System.err(10505):at pi.droid.Core.Comm.ClientConnection$timer_tick.run(ClientConnection.java:164)
WARN/System.err(10505): at java.util.Timer$TimerImpl.run(Timer.java:289)
You can also see the chain of the 2 other worker classes I use. The constructor of Curve is called after the bind from CommMeasure.
So this is my problem.
Do I need to totally change how my program is set up or is there another way around this?
FINAL EDIT
This code is brought from c# and Curve used eventhandlers to pass data around. I got rid of all them(java listeners) and used android Handler and broadcastreceiver.
It has been suggested that I should pass the CurveService around but this will be problematic as Curve has multiple constructors. The no parameter 1 for the service and then 1 like this
public Curve(Unit XUnit, Unit YUnit)
{ this.Title = "Curve";
this.finished = false;
this.XUnit = XUnit;
this.YUnit = YUnit;
this.YDirection = CurveDirection.Unspecified;
}
so surely instantiating that would be a problem with CurveService, which has to be like this: public Curve(){} ??
Anyway many thanks for all your help and advice.
Final Edit +1..lol
The UI creates a new instance of ClientConnection, that in turns creates a new instance of CommMeasure and finally CommMeasure creates a new instance of Curve to access Curve.addpoint.
I think this thread and the other linked 1 goes beyond a simple android problem and highlights the difficulties of code porting. Any .Net developer for example reading this will learn some peculiarities of android a lot quicker than I did. There is also good working code in there.
Thanks to all who helped especially Justin Breitfeller
The best thing for you to do is follow the example from the Android APIDemos.
A service to be used like you want to use it:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html
Look at the Binding class inside of this file to see a class that does binding like you should:
http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalServiceActivities.html
Finally, if your constructor is being called twice on your service, you aren't binding to your service properly, or perhaps you are unbinding from it and binding to it again unexpectedly.
EDIT
From the stack trace, it appears that CommMeasure needs to have a reference to the instance of Curve that you receive in onServiceConnected.
EDIT 2
If you really want to make your life simple, pass getApplicationContext() to your CommMeasure class and just appContext.sendBroadcast() from that class to send out your point. This will prevent you from requiring a reference to the service in your long-running task.

Categories

Resources