其中HTTP主要使用HttpClient和HttpUrlConnection与服务器通信
HttpClient中一般使用默认的DeafultHttpClient和AndordiHttpClient
对于HttpClient在一个项目中的使用一般使用单例模式,但会发生多线程安全的问题,你需要做的是使用ThreadSafeClientConnManager创建DefaultHttpClient。
如果使用单例模式,要对个别的请求做不同处理时,可在Request级别上改变参数,会覆盖Client级别的参数。如:
HttpGet request=new HttpGet("www.qq.com");
HttpParams hps=request.getParams();
HttpConnectionParams.setSoTimeOut(params,60000);
String content=httpClient.execute(request,new BasicResponseHandler());
对于HttpClient中的post请求可封装如下:
public String requestByPost(String url, Map<String, String> params) {
String content = "";
try {HttpPost request = new HttpPost(url);
List<NameValuePair> args = new ArrayList<NameValuePair>();//构建参数列表
for (Map.Entry<String, String> entry : params.entrySet()) {
args.add(new BasicNameValuePair(entry.getKey(), entry
.getValue()));
}
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(args, //封装为实体
"UTF-8");
request.setEntity(entity);
HttpResponse response = httpClient.execute(request);//发生请求,得到响应
int code = response.getStatusLine().getStatusCode();
Header[] headers = response.getAllHeaders();
String c = "";
for (Header h : headers) {
c += h.getName() + ":" + h.getValue() + "\n";
}
if (code == 200) {
// 读取响应的内容
content = EntityUtils.toString(response.getEntity(), "UTF-8");//将得到的实体解析为字符串
}
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
对上面的调用:
HashMap params = new HashMap<String, String>()
params.put("status", "insertComments");//添加参数
params.put("newsId", content_url);
params.put("pId", "0");
params.put("content", str);
String data = newsService.requestByPost(HttpRequestUrl.url(urlString, params);
其中AndordiHttpClient的构造方法为
AndordiHttpClient client=AndordiHttpClient.newInstance("my-http-agent-string");
构造器中的参数为一个HTTP代理字符串。调用execute方法时必须在独立于UI线程中进行。
其重要作用为1、连接管理器默认为ThreadSafeClientConnManager(可解决多线程的问题)。 2、连接和套接字的超时默认值为20秒。
Android服务:
Android服务分为本地服务和远程服务,其中本地服务是指只能由承载该服务的应用程序访问,无法供在设备上运行的其他应用程序访问;远程服务是指除了可从承载服务的应用程序访问,还可从其他应用程序访问。一般都只用的到本地服务,因此下面着重讲解本地服务
本地服务由Context.startService()启动,直到调用Context.stopService()或者自己调用stopSelf()。当调用Context.startService()还未创建服务时,系统将实例化服务并调用服务的startCommand(),注意如果服务启动后调用Context.startService()不会为服务创建另外一个实力,但会调用正在运行的服务的startCommand()方法。下面是一个完整的实例:
服务类:
package com.test.service;
import com.example.aexercise927.MainActivity;
import com.example.aexercise927.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class Myservice extends Service {
NotificationManager notificationManager;
ThreadGroup group;//便于对创建的线程进行统一控制
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("Myservice", "onCreate()");
group = new ThreadGroup("group");
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//创建通知
onDisPlayMessage();
}
private void onDisPlayMessage() {
// TODO Auto-generated method stub
Notification notification = new Notification(R.drawable.ic_launcher,
"通知", System.currentTimeMillis());
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 1,
new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(getApplicationContext(), "你已被录取!",
"恭喜恭喜啊!", pendingIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notificationManager.notify("1", 1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.i("Myservice", "onStartCommand()");
String str = intent.getStringExtra("num");
new Thread(group, new MyRunnable(str)).start();
return START_STICKY;
}
class MyRunnable implements Runnable {
String tag;
public MyRunnable(String tag) {
// TODO Auto-generated constructor stub
this.tag = tag;
}
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("Thead-" + tag, "start");
Log.i("Thead-" + tag, "sleep10s...");
try {
Thread.sleep(10000);//休眠便于观察
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("Thead-" + tag, "over");
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
group.interrupt();
Log.i("Myservice", "onDestroy()");
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
活动类:package com.test.service;
import com.example.aexercise927.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MyMainActivity extends Activity {
public static int i = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.servicemain);
}
public void myAction(View v) {
switch (v.getId()) {
case R.id.button4:
Intent intent = new Intent(this, Myservice.class);
intent.putExtra("num", ++i+"");
startService(intent);
break;
case R.id.button5:
stopService(new Intent(this, Myservice.class));
break;
default:
break;
}
}
}
不要忘记在mainfest.xml注册服务!