服务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