私のサービスはいくつかのファイルをバックグラウンドでアップロードし、マニフェストでこのように宣言します
<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 ) ); }
理由は何かアドバイスはありますか?
ありがとう