I have made an application based on the android API's remote service application wich uses callbacks to notify the main activity for changes, the app works fine passing just a single int value from the remote service back to the activity.
The problem is that I would like to pass some Strings and not an int back in order to update the activiti's UI, how can I do that? I have thought of returning an object but there is lack of documentation and don't know how or if it is possible.
Ok just figure it out, I am posting the solution in order to help others with similar problem.
1.you need to make a separate aidl file that only contains the parcable object(see the link in the comments above).
Second in the callback interface import that interface and then add it as a parameter.
when you implement the method from the callback interface in your activity class add the returned object (this would be the parsable object) as the Message object and send that message.
in the handler just unmarshall the object and use it.
This is a sample code:
The Parcable's object interface:
package sap.max;
parcelable ParcableInfo;
The Callback interface:
package sap.max;
import sap.max.ParcableInfo;
/**
* A callback interface used by IMonitorService to send
* synchronous notifications back to its clients. Note that this is a
* one-way interface so the server does not block waiting for the client.
*/
oneway interface IRemoteServiceCallback {
/**
* Called when the service has a new value for you.
*/
void valueChanged(in ParcableInfo info);
}
The service's actions (note this is only what the service will call not complete code):
private final Handler mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
switch (msg.what) {
// It is time to bump the value!
case REPORT_MSG: {
// Up it goes.
int value = ++mValue;
// Broadcast to all clients the new value.
final int N = mCallbacks.beginBroadcast();
for (int i=0; i<N; i++) {
try {
ParcableInfo parceInfo = new ParcableInfo(telephonyManager.getSubscriberId() );
parceInfo.setID(telephonyManager.getSubscriberId());
mCallbacks.getBroadcastItem(i).valueChanged(parceInfo);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mCallbacks.finishBroadcast();
// Repeat every 3 second.
sendMessageDelayed(obtainMessage(REPORT_MSG), 1*3000);
} break;
default:
super.handleMessage(msg);
}
}
};
And finally the Activities part:
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
#Override
public void valueChanged(ParcableInfo info) throws RemoteException {
CellInfo cellInfo = new CellInfo(null, null, null, null, null, null, null);
cellInfo.setDeviceId(info.ID);
Message msg = mHandler.obtainMessage(BUMP_MSG, info);
mHandler.sendMessage(msg);
}
And the message is handled by:
//this is the handler for the service...
private Handler mHandler = new Handler() {
#Override public void handleMessage(Message msg) {
switch (msg.what) {
case BUMP_MSG:
ParcableInfo info = (ParcableInfo) msg.obj;
configView.setText(info.ID);
Toast.makeText(AntiTheft.this, "Received from service: " + info.ID,
Toast.LENGTH_SHORT).show();
break;
default:
super.handleMessage(msg);
}
}
};
Hope this helps others, thanks for the help fedj.
You can pass Strings by default and you should take a look to Parcelable objects (there is no lack of documentation)
I created the simple "ParcableInfo.aidl" file containing :
package my.package.name;
parcelable ParcableInfo;
However, when I build the project the "ParcableInfo.java" isn't generated in the "gen" folder.
Related
I'm essentially trying to create a SystemService in Android. I read that intercommunication from an app to this service should be handled by a Handler?
So what about returning some object from the Service's function to the calling app? How can this be handled.
To make my question more clear, Imagine I have a Service TestService with the following method definitions:
public class TestService extends ITestService.Stub {
public TestService(Context context) {
super();
mContext = context;
mWorker = new TestWorkerThread("TestServiceWorker");
mWorker.start();
Log.i(TAG, "Spawned worker thread");
}
public void setValue(int val) {
Message msg = Message.obtain();
msg.what = TestWorkerHandler.MESSAGE_SET;
msg.arg1 = val;
mHandler.sendMessage(msg);
}
public Object getValue() {
// ********************* QUESTION HERE *****************
// Can I call this method directly??
// Or do I have to process this through the handler?????
}
private class TestWorkerThread extends Thread {
public TestWorkerThread(String name) {
super(name);
}
public void run() {
Looper.prepare();
mHandler = new TestWorkerHandler();
Looper.loop();
}
}
private class TestWorkerHandler extends Handler {
private static final int MESSAGE_SET = 0;
#Override
public void handleMessage(Message msg) {
try {
if (msg.what == MESSAGE_SET) {
Log.i(TAG, "set message received: " + msg.arg1);
}
} catch (Exception e) {
// Log, don't crash!
Log.e(TAG, "Exception in TestWorkerHandler.handleMessage:", e);
}
}
}
}
This is what I understand from the above in order to be synchronous we generally make the setValue to be executed as part of the handleMessage()
What about the getValue method can make a call to this method using the Service instance and process it normally like how we do traditionally? Or do I have to work with the handler which is highly unlikely (I beleive). Kindly let me know the best process to deal with in this scenario.
Thanks
You don't HAVE to use a Handler to do any of that. If you've created an AIDL file that describes the communication with the service then you're done: all you have to do next is implement the AIDL methods inside your service.
When AIDL is translated into java code by the Android "compiler", you functions will all be blocking (the client will wait for the service to finish the methods).
If you specifically add the keyword 'oneway' then the method call won't be blocking.
You should check out Google's documentation on IBinder to understand things a little better.
I would like to know when into an Activity Android execute a function itself and when is necessary to call a function. For example in the following script I downloaded, the first 4 methods are executed without calling it, but the last one sendMessage(), needs to be called:
public class BroadcastChat extends Activity {
// Debugging
private static final String TAG = "BcastChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_READ = 1;
public static final int MESSAGE_WRITE = 2;
public static final int MESSAGE_TOAST = 3;
// Key names received from the BroadcastChatService Handler
public static final String TOAST = "toast";
// Layout Views
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Member object for the chat services
private BroadcastChatService mChatService = null;
// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
if(D) Log.e(TAG, "[handleMessage !!!!!!!!!!!! ]");
switch (msg.what) {
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
String readBuf = (String) msg.obj;
mConversationArrayAdapter.add("You: " + readBuf);
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
// Set up the window layout
setContentView(R.layout.main);
}
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
setupChat();
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
mChatService.start();
}
private void sendMessage(String message) {
if(D) Log.e(TAG, "[sendMessage]");
// Check that there's actually something to send
if (message.length() > 0 ) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
... Incomplete script, just a part shown for the question
}
So my question is double:
1- In an Android Activity are the methods called sequencially from the first line to the last one?, Is there a loop that makes the "pointer" go back to the first line once the last one is reached?
2-How can you determine which methods are going to be executed automatically (like onCreate() ) and which are going to wait until they are called by another method of the script.
Thank you very much for your time
The first thing to understand, and it's a vital point, is that this is not a script, it's code. If you think of it as a script, you won't "get" what the code is doing. A script executes from start to finish. It might branch out into a function but ultimately, things happen in order.
In Java ( and therefore Android), everything happens as a response to an event or a callback. Some of these events are raised by Android and Nickolaus has already pointed you to the Activity lifecycle which documents callbacks made by Android to your Activity and the precise order in which they happen. Other events are raised by Receivers, ContentProviders, Listeners etc.
Note that this order is not time based (although of course you can create time based code events) and doesn't happen one after another. They are called when the state of the Activity changes, and only when the state changes.
In the handlers for these callbacks, you can of course call your own functions, create instances of classes and call their methods, and do stuff in order, from top to bottom - but only inside the handler.
The first thing that happens when your app starts is that Android instantiates the Application class. Every app has an instance of the Application class, whether you know it or not, and that Application class instance also has a lifecycle similar to an Activity, so Application.onCreate() is the first event in the application to be fired. Once the Application class instance is instantiated, then the main activity, defined in you rmanifest, is created and it's onCreate() method is called.
After that, everything happens in response to a callback from, for example listeners (onClick, onReceive etc) or in response to events. From the end of your onCreate(), your code only executes when some other event happens.
You can shorten all this, and answer your question,by saying that sendMessage can only be called from somewhere inside a callback handler.
It gets more complicated when there are multiple threads executing code but that's for another day.
I hope that this helps rather than makes things more confusing!
Here take a look at the activity lifecycle this should explain it to you.
I have a service which is pulling data from the server. And I have activity as gui which needs to get updated.
So on different occassions, e.g. the information was pulled from the server successfully, the server must signal the activity that there is new information.
For this I implemented this function:
/**
* ServerService.class
*
* Sends a message to the observer that there is a new status message to be
* pulled from the service#
*
* #param pMessage
* the message to be set to the public status
*/
private void signalNewStatus(String pMessage) {
//check if there is a message at all to be signaled as new
if (pMessage != null) {
Log.v(tag, "signalNewStatus:" + pMessage);
// set the message
vStatus = pMessage;
// start the new callback via the handler
myMessageHandler.sendEmptyMessage(I_STATUS_UPDATE_SIGNAL);
}
}
To handle the messages, I have the message handler:
private final Handler myMessageHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
Log.i(tag, "handleMessage: "+msg.what);
switch (msg.what) {
case I_STATUS_UPDATE_SIGNAL: {
// Broadcast to all clients the new value.
final int N = myCallbackList.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
myCallbackList.getBroadcastItem(i).sendUpdateStatusSignal(true);
} catch (RemoteException e) {
}
}
myCallbackList.finishBroadcast();
}
break;
The first function is called quite often, and I can see in the logging that this works right on time.
But the logging for the message handling does not get called right away. It is delayed and gets called most often at the end. Somehow as bulk.
I cannot figure out why this is the case. The rest works well, the message gets to the UI thread without a problem once the message was handled.
Any suggestions?
Thanks a lot!
I can't be sure without more code, but it sounds like a threading issue.
Try putting your handler code in a separate HandlerThread, retrieve the handler in the service and send the message to it.
Which is the better way to use a handler. Any advantages. All examples I have come across seem to give the inline version.
Using implements Handler.Callback in the class and implementing interface method.
or
Using inline code version
private Handler mHandler = new Handler(){ ....};
The common term or these inline class definitions is Anonymous Classes.
You can read more about the discussion on these in Java/Android: anonymous local classes vs named classes
Essentially the main differences are readbility, speed of coding, re-use and scope.
From a resource point of view the anonymous class creation may cause an overhead in the garbage collector as discussed in Avoid Creating Unnecessary Objects. I am not certain on the exact details of anonymous class creation, however, it is logical that implementing the interface on the class is more efficient.
#WilliamTMallard has provided an example of what NOT to do. In his example, a long and syntacticly complex handler should be implementented on the class rather than anonymous handler because it is harder to read and edit when defined inline.
http://developer.android.com/reference/android/os/Handler.html
package : android.os
public class
Handler
extends Object
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
There are two main uses for a Handler:
to schedule messages and runnables to be executed as some point
in the future; and
to enqueue an action to be performed on a different thread than
your own.
Exmaple 1
use handler in app splash page.
if (!isFirstIn) {
mHandler.sendEmptyMessageDelayed(GO_HOME, SPLASH_DELAY_MILLIS);
} else {
mHandler.sendEmptyMessageDelayed(GO_GUIDE, SPLASH_DELAY_MILLIS);
}
/**************************************************************************************
*1. Handler
*/
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if(isAuto){
switch (msg.what) {
case GO_HOME:
goHome();
break;
case GO_GUIDE:
goGuide();
break;
}
}
super.handleMessage(msg);
}
};
private void goHome() {
Intent intent = new Intent(SplashActivity.this, MainAct.class);
SplashActivity.this.startActivity(intent);
SplashActivity.this.finish();
}
private void goGuide() {
Intent intent = new Intent(SplashActivity.this, GuideActivity.class);
SplashActivity.this.startActivity(intent);
SplashActivity.this.finish();
}
Example 2
use Handler request network in child thread if the request work may takes time.
new Thread(new Runnable(){
#Override
public void run() {
String versionPath = Parameters.getCheckVersionPath();
String result = RequestHelper.doGet(versionPath, null);
Message msg = new Message();
Bundle data = new Bundle();
data.putString("result",result);
msg.setData(data);
handler1.sendMessage(msg);
}
}).start();
handler1 = new Handler(){
#Override
public void handleMessage(Message msg) {
String result = msg.getData().getString("result");
JSONObject obj;
try {
obj = new JSONObject(result);
Map<String, String> versionInfo = Helper.getSoftwareVersion(obj);
if (versionInfo != null) {
newVersion = versionInfo.get("version");
updateUrl = versionInfo.get("url");
}
} catch (JSONException e) {
Log.w("net work error!", e);
}
}
};
Example 3
use Handler and Timer to update progress bar.
logobar = (ImageView) findViewById(R.id.splash_bar);//progress bar.
logobarClipe = (ClipDrawable) logobar.getBackground();
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
updateLogoBarHandler.sendEmptyMessage(0);
}}, 0, rate);
/**************************************************************************************
*2. Handler
*/
//update progress bar.
private Handler updateLogoBarHandler = new Handler() {
public void handleMessage(Message msg) {
if(logobarClipe.getLevel() < 10000){
//1.update image.
logobarClipe.setLevel(logobarClipe.getLevel() + rate*2);
//2.update text.
float percent = logobarClipe.getLevel() /100;
String percentTxtVerbose = String.valueOf(percent);
String percentTxt = percentTxtVerbose.substring(0, percentTxtVerbose.indexOf('.')) + "%";
bartxt.setText(percentTxt);
}else{
timer.cancel();
}
super.handleMessage(msg);
}
};
This really isn't an answer to the above question because I don't know what "the best way" is, and it likely depends on what you're doing. However, I'll explain what I'm doing and why.
I'm writing an app that serves as a remote controller. There are several activities that will interact with the controlled device, and different things need to happen based on the result of the command and the activity it came from. Two things I didn't like about handlers are A) that they end up being a sort of "kitchen sink" construct, implementing functionality from different sources, and B) that they separated an action (the send of the command in my case) from the processing of the result of that action. However, using an anonymous (right term? I'm such a noob.) handler as a parameter allows me to keep the logic together. Here's the pseudocode for my approach:
command = "Wake up!";
mDeviceInterface.write(command, new Handler() {
#Override
public void handleMessage(Message msg) {
switch(msg.what) {
case DeviceInterface.MESSAGE_TIMEOUT: // Process the timeout.
announce("Device not responding.");
break;
case DeviceInterface.MESSAGE_READ: // Process the response.
byte[] readBuf = (byte[]) msg.obj;
if (readBuf[0] == 0x05) {
// Success, update device status.
} else {
announce("Error!");
break;
}
}
}
});
(Always remember, this is probably worth exactly what you've paid for it. ;) )
There is a danger in using anonymous classes in Android. As described in this blog post -
In Java, non-static inner and anonymous classes hold an implicit
reference to their outer class.
And here comes an opportunity for a leak.
So, the short answer would be: implement the interface methods or use static inner classes (which don't hold an outer class reference).
For instance, a leak-safe Handler could look like this:
private static class ChangeTextHandler extends Handler {
private final WeakReference activity;
public ChangeTextHandler(MainActivity activity) {
this.activity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
MainActivity activity = this.activity.get();
if (activity == null) {
Log.e(TAG, "Activity is null ChangeTextHandler.handleMessage()!");
return;
}
final String text = (String) msg.getData().get(BUNDLE_KEY);
if (!TextUtils.isEmpty(text)) {
switch (msg.what) {
// do something
}
}
}
}
I made a blog post around usage of Handlers, so might be worth checking as well :)
I'm looking to make a service which I can use to make calls to a web-based REST API.
Basically I want to start a service on app init then I want to be able to ask that service to request a url and return the results. In the meantime I want to be able to display a progress window or something similar.
I've created a service currently which uses IDL, I've read somewhere that you only really need this for cross app communication, so think these needs stripping out but unsure how to do callbacks without it. Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)
Currently I have a service with post and get http methods inside, a couple of AIDL files (for two way communication), a ServiceManager which deals with starting, stopping, binding etc to the service and I'm dynamically creating a Handler with specific code for the callbacks as needed.
I don't want anyone to give me a complete code base to work on, but some pointers would be greatly appreciated.
Code in (mostly) full:
public class RestfulAPIService extends Service {
final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>();
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
public IBinder onBind(Intent intent) {
return binder;
}
public void onCreate() {
super.onCreate();
}
public void onDestroy() {
super.onDestroy();
mCallbacks.kill();
}
private final IRestfulService.Stub binder = new IRestfulService.Stub() {
public void doLogin(String username, String password) {
Message msg = new Message();
Bundle data = new Bundle();
HashMap<String, String> values = new HashMap<String, String>();
values.put("username", username);
values.put("password", password);
String result = post(Config.getURL("login"), values);
data.putString("response", result);
msg.setData(data);
msg.what = Config.ACTION_LOGIN;
mHandler.sendMessage(msg);
}
public void registerCallback(IRemoteServiceCallback cb) {
if (cb != null)
mCallbacks.register(cb);
}
};
private final Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
// Broadcast to all clients the new value.
final int N = mCallbacks.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
switch (msg.what) {
case Config.ACTION_LOGIN:
mCallbacks.getBroadcastItem(i).userLogIn( msg.getData().getString("response"));
break;
default:
super.handleMessage(msg);
return;
}
} catch (RemoteException e) {
}
}
mCallbacks.finishBroadcast();
}
public String post(String url, HashMap<String, String> namePairs) {...}
public String get(String url) {...}
};
A couple of AIDL files:
package com.something.android
oneway interface IRemoteServiceCallback {
void userLogIn(String result);
}
and
package com.something.android
import com.something.android.IRemoteServiceCallback;
interface IRestfulService {
void doLogin(in String username, in String password);
void registerCallback(IRemoteServiceCallback cb);
}
and the service manager:
public class ServiceManager {
final RemoteCallbackList<IRemoteServiceCallback> mCallbacks = new RemoteCallbackList<IRemoteServiceCallback>();
public IRestfulService restfulService;
private RestfulServiceConnection conn;
private boolean started = false;
private Context context;
public ServiceManager(Context context) {
this.context = context;
}
public void startService() {
if (started) {
Toast.makeText(context, "Service already started", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("com.something.android", "com.something.android.RestfulAPIService");
context.startService(i);
started = true;
}
}
public void stopService() {
if (!started) {
Toast.makeText(context, "Service not yet started", Toast.LENGTH_SHORT).show();
} else {
Intent i = new Intent();
i.setClassName("com.something.android", "com.something.android.RestfulAPIService");
context.stopService(i);
started = false;
}
}
public void bindService() {
if (conn == null) {
conn = new RestfulServiceConnection();
Intent i = new Intent();
i.setClassName("com.something.android", "com.something.android.RestfulAPIService");
context.bindService(i, conn, Context.BIND_AUTO_CREATE);
} else {
Toast.makeText(context, "Cannot bind - service already bound", Toast.LENGTH_SHORT).show();
}
}
protected void destroy() {
releaseService();
}
private void releaseService() {
if (conn != null) {
context.unbindService(conn);
conn = null;
Log.d(LOG_TAG, "unbindService()");
} else {
Toast.makeText(context, "Cannot unbind - service not bound", Toast.LENGTH_SHORT).show();
}
}
class RestfulServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className, IBinder boundService) {
restfulService = IRestfulService.Stub.asInterface((IBinder) boundService);
try {
restfulService.registerCallback(mCallback);
} catch (RemoteException e) {}
}
public void onServiceDisconnected(ComponentName className) {
restfulService = null;
}
};
private IRemoteServiceCallback mCallback = new IRemoteServiceCallback.Stub() {
public void userLogIn(String result) throws RemoteException {
mHandler.sendMessage(mHandler.obtainMessage(Config.ACTION_LOGIN, result));
}
};
private Handler mHandler;
public void setHandler(Handler handler) {
mHandler = handler;
}
}
Service init and bind:
// this I'm calling on app onCreate
servicemanager = new ServiceManager(this);
servicemanager.startService();
servicemanager.bindService();
application = (ApplicationState)this.getApplication();
application.setServiceManager(servicemanager);
service function call:
// this lot i'm calling as required - in this example for login
progressDialog = new ProgressDialog(Login.this);
progressDialog.setMessage("Logging you in...");
progressDialog.show();
application = (ApplicationState) getApplication();
servicemanager = application.getServiceManager();
servicemanager.setHandler(mHandler);
try {
servicemanager.restfulService.doLogin(args[0], args[1]);
} catch (RemoteException e) {
e.printStackTrace();
}
...later in the same file...
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case Config.ACTION_LOGIN:
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
try {
...process login results...
}
} catch (JSONException e) {
Log.e("JSON", "There was an error parsing the JSON", e);
}
break;
default:
super.handleMessage(msg);
}
}
};
If your service is going to be part of you application then you are making it way more complex than it needs to be. Since you have a simple use case of getting some data from a RESTful Web Service, you should look into ResultReceiver and IntentService.
This Service + ResultReceiver pattern works by starting or binding to the service with startService() when you want to do some action. You can specify the operation to perform and pass in your ResultReceiver (the activity) through the extras in the Intent.
In the service you implement onHandleIntent to do the operation that is specified in the Intent. When the operation is completed you use the passed in ResultReceiver to send a message back to the Activity at which point onReceiveResult will be called.
So for example, you want to pull some data from your Web Service.
You create the intent and call startService.
The operation in the service starts and it sends the activity a message saying it started
The activity processes the message and shows a progress.
The service finishes the operation and sends some data back to your activity.
Your activity processes the data and puts in in a list view
The service sends you a message saying that it is done, and it kills itself.
The activity gets the finish message and hides the progress dialog.
I know you mentioned you didn't want a code base but the open source Google I/O 2010 app uses a service in this way I am describing.
Updated to add sample code:
The activity.
public class HomeActivity extends Activity implements MyResultReceiver.Receiver {
public MyResultReceiver mReceiver;
public void onCreate(Bundle savedInstanceState) {
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
...
final Intent intent = new Intent(Intent.ACTION_SYNC, null, this, QueryService.class);
intent.putExtra("receiver", mReceiver);
intent.putExtra("command", "query");
startService(intent);
}
public void onPause() {
mReceiver.setReceiver(null); // clear receiver so no leaks.
}
public void onReceiveResult(int resultCode, Bundle resultData) {
switch (resultCode) {
case RUNNING:
//show progress
break;
case FINISHED:
List results = resultData.getParcelableList("results");
// do something interesting
// hide progress
break;
case ERROR:
// handle the error;
break;
}
}
The Service:
public class QueryService extends IntentService {
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
String command = intent.getStringExtra("command");
Bundle b = new Bundle();
if(command.equals("query") {
receiver.send(STATUS_RUNNING, Bundle.EMPTY);
try {
// get some data or something
b.putParcelableArrayList("results", results);
receiver.send(STATUS_FINISHED, b)
} catch(Exception e) {
b.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, b);
}
}
}
}
ResultReceiver extension - edited about to implement MyResultReceiver.Receiver
public class MyResultReceiver implements ResultReceiver {
private Receiver mReceiver;
public MyResultReceiver(Handler handler) {
super(handler);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
#Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
Developing Android REST client applications has been an awesome resource for me. The speaker does not show any code, he just goes over design considerations and techniques in putting together a rock solid Rest Api in android. If your a podcast kinda person or not, I'd recommend giving this one at least one listen but, personally I've listened to it like 4 or five times thus far and I'm probably going to listen to it again.
Developing Android REST client applications
Author: Virgil Dobjanschi
Description:
This session will present architectural considerations for developing RESTful applications on the Android platform. It focuses on design patterns, platform integration and performance issues specific to the Android platform.
And there are so many considerations I really hadn't made in the first version of my api that I've had to refactor
Also when I hit
the post(Config.getURL("login"),
values) the app seems to pause for a
while (seems weird - thought the idea
behind a service was that it runs on a
different thread!)
No you have to create a thread yourself, a Local service runs in the UI thread by default.
I know #Martyn does not want full code, but I think this annotation its good for this question:
10 Open Source Android Apps which every Android developer must look into
Foursquared for Android is open-source, and have an interesting code pattern interacting with the foursquare REST API.
I would highly recommend the REST client Retrofit.
I have found this well written blog post extremely helpful, it also contains simple example code.
The author uses Retrofit to make the network calls and Otto to implement a data bus pattern:
http://www.mdswanson.com/blog/2014/04/07/durable-android-rest-clients.html
Just wanted to point you all in the direction of an standalone class I rolled that incorporates all of the functionality.
http://github.com/StlTenny/RestService
It executes the request as non-blocking, and returns the results in an easy to implement handler. Even comes with an example implementation.
Lets say I want to start the service on an event - onItemClicked() of a button. The Receiver mechanism would not work in that case because :-
a) I passed the Receiver to the service (as in Intent extra) from onItemClicked()
b) Activity moves to the background. In onPause() I set the receiver reference within the ResultReceiver to null to avoid leaking the Activity.
c) Activity gets destroyed.
d) Activity gets created again. However at this point the Service will not be able to make a callback to the Activity as that receiver reference is lost.
The mechanism of a limited broadcast or a PendingIntent seems to be more usefull in such scenarios- refer to Notify activity from service
Note that the solution from Robby Pond is somehow lacking: in this way you only allow todo one api call at a time since the IntentService only handles one intent at a time. Often you want to perform parallel api calls. If you want todo this you have to extend Service instead of IntentService and create your own thread.
Also when I hit the post(Config.getURL("login"), values) the app seems to pause for a while (seems weird - thought the idea behind a service was that it runs on a different thread!)
In this case its better to use asynctask, which runs on a different thread and return result back to the ui thread on completion.
Robby provides a great answer, though I can see you still looking for more information. I implemented REST api calls the easy BUT wrong way. It wasn't until watching this Google I/O video that I understood where I went wrong. It's not as simple as putting together an AsyncTask with a HttpUrlConnection get/put call.
There is another approach here which basically helps you to forget about the whole management of the requests. It is based on an async queue method and a callable/callback based response.
The main advantage is that by using this method you'll be able to make the whole process (request, get and parse response, sabe to db) completely transparent for you. Once you get the response code the work is already done. After that you just need to make a call to your db and you are done.
It helps as well with the problematic of what happens when your activity is not active.
What will happen here is that you'll have all your data saved in your local database but the response won't be processed by your activity, that's the ideal way.