Restful API service

前端 未结 11 1505
清歌不尽
清歌不尽 2020-11-22 14:28

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 t

相关标签:
11条回答
  • 2020-11-22 15:11

    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.

    0 讨论(0)
  • 2020-11-22 15:11

    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.

    0 讨论(0)
  • 2020-11-22 15:13

    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.

    I wrote about a general approach here http://ugiagonzalez.com/2012/07/02/theres-life-after-asynctasks-in-android/

    I'll be putting specific sample code in upcoming posts. Hope it helps, feel free to contact me for sharing the approach and solving potential doubts or issues.

    0 讨论(0)
  • 2020-11-22 15:19

    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

    0 讨论(0)
  • 2020-11-22 15:23

    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.

    1. You create the intent and call startService.
    2. The operation in the service starts and it sends the activity a message saying it started
    3. The activity processes the message and shows a progress.
    4. The service finishes the operation and sends some data back to your activity.
    5. Your activity processes the data and puts in in a list view
    6. The service sends you a message saying that it is done, and it kills itself.
    7. 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);
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题