1

我的服务在后台上传了一些文件,并在我的清单中这样声明

<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 ) ); }

任何建议可能是什么原因?

谢谢

4

2 回答 2

1

您可以使用以下代码禁用线程执行的严格模式:

if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = 
        new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

再次不建议这样做。使用需要使用 AsyncTask 接口以获得更好的结果。

于 2013-01-17T09:39:11.610 回答
0

文档

与其他应用程序对象一样,服务在其托管进程的主线程中运行

所以我想如果你想在你的服务中做一些网络工作,你最好在后台线程中做(无论它运行在什么进程中)。

于 2013-01-17T09:36:27.387 回答