在Android应用中调用RESTful服务
REST是一个被广泛采用的架构模式,尤其在API、Web Services、云计算流行的大环境下,所有主流的互联网厂商都提供了其服务的REST接口,用户可采用JSON、XML格式使用HTTP进行方法调用和数据传输。
RESTful已成为主流客户-服务器编程模式,在手机端与后端系统的交互中也被普遍采用。
现在我们就来分析下Android环境下的RESTful编程模式和一般方法。
错误的实现方式
这个做法会导致:
- 操作系统shutdown这个进程;
- 数据不能持久化保存。
而正确处理REST方法通常有三种设计模式:
- 使用 Service API
- 使用 ContentProvider API
- 使用 ContentProvider API 和 SyncAdapter
其中,Service Helper的作用是:
以单体(Singleton)的方式暴露一个简单的异步API给用户接口使用。
• 准备和发送服务请求
– 检测方法是否已经被挂起
– 创建请求意图
– 添加操作类型和一个唯一的请求id号
– 添加方法的特殊属性值
– 添加binder回调
– 调用startService(意图)
– 返回请求id号
• 处理从服务返回的回调
– 将回调分发给用户接口监听器
实战一下:
从An attempt at implementing a RESTful Android application 开始RESTful Android应用的尝试
git clone https://github.com/jeremyhaberman/restful-android.git
在 eclipse > file > import > Existing Projects into Workspace
Debug As Android Application,这里使用了Simple OAuth library for Java第三方库
如通过Twitter API使用OAuth验证
import com.jeremyhaberman.restfulandroid.rest.Request;
// RESTful Android Twitter app settings
private static final String TWITTER_API_KEY = “ssdfiwKoedslVjUsngtow”;
private static final String TWITTER_API_SECRET = “sdfsIkkmIKLFDvzaLdnBeLAVkwPFUxxZ9Ulf8fkY”;
private static final String TWITTER_CALLBACK_URL = “restful-android://callback”;
总结:
- 不要在Activities里实现REST方法;
- 从一个服务中启动长时间运行的操作;
- 持久要早、要经常(Persist early & persist often)
- 最大限度的减少网络使用(Minimize the network usage);
- 是不是在关键时刻使用同步适配器执行后台操作(Use a sync adapter to execute background operations which are not time critical),使用Android Cloud to Device Messaging。
参考: