服务Service和通信HttpGet及HttpPost

本文详细介绍了Android中的Service基本使用,包括如何创建、启动和停止Service,以及Activity与Service的绑定。同时,文章讲解了HTTP的HttpGet和HttpPost方法,包括设置URL、处理响应状态码以及POST请求的参数设置。
摘要由CSDN通过智能技术生成

服务Service

Service基础
定义MyService类继承Service,并重载onCreate(),onStart(),onDestroy().
在主Activity中调用StartService(serviceIntent)函数调用Service,或者StopService(serviceIntent)结束Service。
在AndroidManifest.xml中注册Service.
Activity和Service绑定
定义MyService类继承Service,并在该类中声明内部类MyBinder,继承Binder。
              public MyBinder extends Binder

{

MyService getService()

{

return MyService.this;

}

}

       2.  创建内部类MyBinder的对象myBinder;

       3.重载onReBind()和onUnBind()函数

       4.在主Activity中创建MyService变量myService和ServiceConnection变量mConnection;

           private MyService myService;

private ServiceConnection mConnection=new ServiceConnection()

{

.....

}

并在mconnection中重载的onServiceConnected(ComponentName name,IBinder service)函数中获取Service对象

myService=((Myservice.Mybinder)service).getService();

       5.调用bindService(serviceIntent,mConnection,Context.BIND_AUTO_CREATE);

 

通信HttpGet和HttpPost

HttpGet

1.定义url

2.HttpRespone httpRespone=null;

3.HttpGet httpGet=new HttpGet(url)//url中需添加一些请求参数

4.HttpRespone=new DefaultHttpClient.execute(httpGet);

5.if(HttpRespone.GetStatusLine().GetStatusCode()==200)  //相应状态码为200

   {

    ....

   }

 

HttpPost

1,2同上

3.List<NameValuePair> params=new ArrayList<NameValuePair>();

4.params.add(new BasicNameValuePair("name","value"));

5.httpPost.setEntity(new UrlEncodeFormEntity(params,HTTP.UTF_8));

6,7同HttpGet中4,5步骤,只要将httpGet换成httpPost

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值