Android Service 与 Activity使用Pending Intent通信
service使用pending intent返回结果给客户端
我们使用一个activity作为一个客户端,来通过startService()的方法启动一个服务,这个服务的功能很简单,就是去访问客户端指定的Url,然后返回这个url对应的页面的源代码的字符数量。这个例子中,我们是不允许这个服务被绑定的。即我们在onBind()方法中返回null。那么好了,现在我们这个服务不可以被绑定,只可以通过startService()的方法启动,那么此时服务和客户端的通信方式就只有一种了,即通过Pending Intent了。
1.首先自定义我们的服务类:MyService
public class MyService extends Service {
private ServiceHandler mHandler;
//内部类
private final class ServiceHandler extends Handler{
public ServiceHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == 0x1234){
Log.v("MyService","handleMessage()被调用");
int charNum = ((String)(msg.obj)).length();
Bundle bundle = msg.getData();
PendingIntent client = bundle.getParcelable("receiver");
Log.v("MyService","字符数为" + charNum);
Intent intent = new Intent();
intent.putExtra("CHARNUM",charNum);
try {
client.send(ge