我的服务在后台上传了一些文件,并在我的清单中这样声明
<service
android:name="uploader.services.AttachService"
android:icon="@drawable/loading_icon"
android:label="@string/attachServiceName"
android:process=":attachServiceBackground" />
在 Android 4.1.1 上它会发生NetworkOnMainThreadException
但我不知道为什么。我知道由于蜂窝不允许在主线程上进行联网,这就是服务将在自己的线程中运行的原因。
实际上我正在像这样开始服务我的活动
startService(new Intent(MainActivity.this, AttachService.class));
是否有必要在 AsyncTask 中启动服务,尽管它声明在自己的线程中运行?这是我的服务的一种方法,它不起作用
public static String attach(File attRequestFile, File metaDataFile, Job j) {
String retVal = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(j.getTarget().getServiceEndpoint() + ATTACH_PATH);
MultipartEntity mp = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
mp.addPart("metadata", new FileBody(metaDataFile));
mp.addPart("request", new FileBody(attRequestFile));
File img = new File(j.getAtach().getAttUri());
if (img != null){
mp.addPart("data", new FileBody(img));
}
post.setEntity(mp);
HttpResponse response;
try {
response = client.execute(post);
if (response.getEntity() == null){
retVal = "";
}
else{
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
retVal = sb.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return retVal;
}
使用设置视图中的按钮,用户可以启动服务,如下所示
public void startSendDataAction(View view) { startService( new Intent( this, AttachService.class ) ); }
任何建议可能是什么原因?
谢谢