首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Restful API服务

Restful API服务
EN

Stack Overflow用户
提问于 2010-07-08 01:34:27
回答 10查看 121.1K关注 0票数 229

我正在寻找一个可以用来调用基于web的REST API的服务。

基本上,我想在app init上启动一个服务,然后我希望能够请求该服务请求一个url并返回结果。同时,我希望能够显示一个进度窗口或类似的窗口。

我目前已经创建了一个使用IDL的服务,我在某处读到,你只有在跨应用程序通信时才真正需要它,所以我认为这些需要剥离,但不确定如何在没有它的情况下进行回调。此外,当我点击post(Config.getURL("login"), values)时,应用程序似乎会暂停一段时间(看起来很奇怪--我以为服务背后的想法是它在不同的线程上运行!)

目前,我有一个带有post和get http方法的服务,几个AIDL文件(用于双向通信),一个处理启动、停止、绑定等到服务的ServiceManager,我正在根据需要动态创建一个带有特定回调代码的处理程序。

我不希望任何人给我一个完整的代码库来工作,但一些指针将非常感谢。

(大部分)完整的代码:

代码语言:javascript
复制
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) {...}
};

几个AIDL文件:

代码语言:javascript
复制
package com.something.android

oneway interface IRemoteServiceCallback {
    void userLogIn(String result);
}

代码语言:javascript
复制
package com.something.android
import com.something.android.IRemoteServiceCallback;

interface IRestfulService {
    void doLogin(in String username, in String password);
    void registerCallback(IRemoteServiceCallback cb);
}

和服务管理器:

代码语言:javascript
复制
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;
    }
}

服务初始化和绑定:

代码语言:javascript
复制
// this I'm calling on app onCreate
servicemanager = new ServiceManager(this);
servicemanager.startService();
servicemanager.bindService();
application = (ApplicationState)this.getApplication();
application.setServiceManager(servicemanager);

服务函数调用:

代码语言:javascript
复制
// 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);
        }

    }

};
EN

回答 10

Stack Overflow用户

回答已采纳

发布于 2010-07-08 01:53:07

如果你的服务将成为你的应用程序的一部分,那么你会让它变得比它需要的复杂得多。由于您有一个从RESTful Web服务获取一些数据的简单用例,因此您应该研究一下ResultReceiverIntentService

当您想要执行某些操作时,此服务+ ResultReceiver模式通过使用startService()启动或绑定到服务来工作。您可以指定要执行的操作,并通过Intent中的extras传入您的ResultReceiver (活动)。

在服务中,您可以实现onHandleIntent来执行意图中指定的操作。操作完成后,您可以使用传入的ResultReceiver将一条消息send回活动,此时将调用onReceiveResult

因此,例如,您希望从Web服务中提取一些数据。

在服务中创建intent和call startService.

  • The操作启动时,它会向活动发送一条消息,说明操作已启动。活动处理该消息,并显示progress.

  • The服务完成操作,并将一些数据发送回activity.

  • Your活动。处理数据,并将数据放入列表视图中。

  • 服务向您发送一条消息,说明操作已完成,并终止自身。

  • 活动获得完成消息,并隐藏进度对话框。

<

  • >G221>

我知道你提到过你不想要代码库,但是开源的Google I/O 2010应用程序使用了我所描述的这种方式的服务。

更新以添加示例代码:

活动。

代码语言:javascript
复制
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;
    }
}

服务:

代码语言:javascript
复制
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扩展-为实现MyResultReceiver.Receiver而编辑的内容

代码语言:javascript
复制
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);
        }
    }
}
票数 284
EN

Stack Overflow用户

发布于 2010-07-08 02:34:36

当我点击post(Config.getURL(“

”),values)时,应用程序似乎会暂停一段时间(看起来很奇怪--我以为服务背后的想法是它在不同的线程上运行!)

不,你必须自己创建一个线程,默认情况下,本地服务在UI线程中运行。

票数 16
EN

Stack Overflow用户

发布于 2011-09-13 03:38:48

我知道@Martyn不想要完整的代码,但我认为这个注释对这个问题很好:

10 Open Source Android Apps which every Android developer must look into

Foursquared for Android是open-source,它有一个有趣的代码模式与foursquare REST API交互。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3197335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档