标签: networkonmainthread

Android上的服务启动android.os.NetworkOnMainThreadException

在Android上尝试我的全新服务之后我得到了这个:

我猜是与清单文件和权限相关的东西,服务在最后一个活动之后启动,更新服务器上的数据并检索新数据并在android上的sqlite上保存id:

这里还有清单文件:

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.ggservice.democracy"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />
        <uses-permission android:name="android.permission.INTERNET"/>

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.ggservice.democracy.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:label="@string/app_name" android:name="com.ggservice.democracy.sondaggioActivity"/>
            <activity android:label="@string/app_name" android:name="com.ggservice.democracy.domandeDiCategoria"/>
            <service android:name="com.ggservice.democracy.updateDemocracyService" />
        </application>

    </manifest>
Run Code Online (Sandbox Code Playgroud)

logcat:

01-02 15:33:30.960: W/dalvikvm(2570): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
01-02 15:33:31.160: E/AndroidRuntime(2570): FATAL EXCEPTION: main
01-02 15:33:31.160: E/AndroidRuntime(2570): java.lang.RuntimeException: Unable to start service com.ggservice.democracy.updateDemocracyService@412f0c60 with Intent { cmp=com.ggservice.democracy/.updateDemocracyService }: android.os.NetworkOnMainThreadException
01-02 15:33:31.160: E/AndroidRuntime(2570): …
Run Code Online (Sandbox Code Playgroud)

service android onstart logcat networkonmainthread

7
推荐指数
2
解决办法
2万
查看次数

AsyncTask的doInBackground中的android.os.NetworkOnMainThreadException

为什么我会进入一个应该是android.os.NetworkOnMainThreadException的AsyncTask?我认为AsyncTask是解决这个问题的方法.这个例外是在第7行.

private class ImageDownloadTask extends AsyncTask<String, Integer, byte[]> {
    @Override
    protected byte[] doInBackground(String... params) {
        try {
            URL url = new URL(params[0]);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
            int bufferSize = 1024;
            byte[] buffer = new byte[bufferSize];

            int len;
            while ((len = inputStream.read(buffer)) != -1) {
                byteBuffer.write(buffer, 0, len);
            }
            return byteBuffer.toByteArray();
        } catch (IOException ex) {
            return new byte[0];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想用它来下载图片.

public byte[] getProfilePicture(Context context, String id) {
    String url …
Run Code Online (Sandbox Code Playgroud)

android android-asynctask networkonmainthread

6
推荐指数
1
解决办法
4534
查看次数

服务器中的android.os.NetworkOnMainThreadException在一个单独的进程中

在ICS上,我在使用UrlConnection时遇到android.os.NetworkOnMainThreadException错误 - 即使我在一个运行在它自己的进程上的服务中发出此请求,并且被异步调用以通过Messenger完成.

更改StrictPolicy无效,我仍然收到错误.

我能做什么?

编辑:此服务在一个单独的进程中运行 - 具有不同的pid和所有内容.

android networkonmainthread

5
推荐指数
1
解决办法
3431
查看次数

尝试使用Calimero Java Library通过WiFi连接时出现"android.os.NetworkOnMainThreadException"

我正在使用一个使用开源Java库(Calimero)的Android应用程序.当我尝试通过WiFi连接到KNXnet/IP路由器时,我的代码会引发错误.

这里的问题代码:

private static KNXNetworkLinkIP connect(InetSocketAddress isaLocalEP, InetSocketAddress isaRemoteEP)
  {
    KNXNetworkLinkIP netLinkIp = null;

    int serviceMode = KNXNetworkLinkIP.TUNNEL; // tunnel to IP router
    boolean useNAT = true; // NAT not used for PC true or false , but needed for emulator = true
    KNXMediumSettings tpSettings = new TPSettings(true); // TP1 medium

    try
    {
      // Output the local end point address

      if (m_debugOutput == true)
      {
        System.out.println("..Tunneling, NAT ignored, TP1 medium");

        // Should be the PC's VPN address

        System.out.print("..Local  EP:");
        System.out.println(isaLocalEP.getHostName() …
Run Code Online (Sandbox Code Playgroud)

sockets networking android android-wifi networkonmainthread

5
推荐指数
2
解决办法
2万
查看次数

AsyncTask中的android.os.NetworkOnMainThreadException

我建立一个应用程序,我得到一个NetworkOnMainThreadException INSIDE的的AsyncTask

呼叫:

new POST(this).execute("");
Run Code Online (Sandbox Code Playgroud)

的AsyncTask:

public class POST extends AsyncTask<String, Integer, HttpResponse>{
private MainActivity form;
public POST(MainActivity form){
    this.form = form;
}


@Override
protected HttpResponse doInBackground(String... params) {
try {
        HttpPost httppost = new HttpPost("http://diarwe.com:8080/account/login");
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
    nameValuePairs.add(new BasicNameValuePair("email",((EditText)form.findViewById(R.id.in_email)).getText().toString()));
    //add more...
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    return new DefaultHttpClient().execute(httppost);
} catch (Exception e) {
    Log.e("BackgroundError", e.toString());
}
return null;
}

@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
try {
    Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
    gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
} catch …
Run Code Online (Sandbox Code Playgroud)

android http-post android-asynctask networkonmainthread

5
推荐指数
1
解决办法
6031
查看次数

Service中的NetworkOnMainThreadException

我得到一个NetworkOnMainThreadException在我的Service类,它本质上是没有意义的,因为服务是后台进程,据我了解.

在Service方法中,我正在调用静态帮助器方法来下载数据.我也在使用DefaultHttpClient.

这里发生了什么?

android networkonmainthread

4
推荐指数
1
解决办法
3355
查看次数

NetworkOnMainThreadException从Web上读取时

当我尝试从网站上读取单行文本时我得到错误(NetworkOnMainThreadException).我尝试了一些东西但到目前为止没有任何作用.所以这里是代码,如果有人可以帮助.在清单中我有互联网许可,所以不应该是问题.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class Weather extends Activity {

    Button button;
    TextView t;
    String result;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

        setContentView(R.layout.weather);

        t = (TextView)findViewById(R.id.textView1);

    }   

    public void myButtonClickHandler (View view) throws ClientProtocolException, IOException {
        result = getContentFromUrl("http://url.com");
        t.setText(result);
    }

    public static String getContentFromUrl(String url) throws ClientProtocolException, IOException {

        HttpClient httpClient = …
Run Code Online (Sandbox Code Playgroud)

android networkonmainthread

3
推荐指数
2
解决办法
5751
查看次数

Android HttpClient:NetworkOnMainThreadException

我在下面有一些代码:

protected void testConnection(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    ResponseHandler<String> responsehandler = new BasicResponseHandler();

    try {
        String connection = httpclient.execute(httpget, responsehandler);
        Toast.makeText(getBaseContext(), R.string.connection_succeed, Toast.LENGTH_SHORT).show();
        view_result.setText(connection);
    } catch(IOException e) {
        Toast.makeText(getBaseContext(), R.string.connection_failed, Toast.LENGTH_SHORT).show();
    }
    httpclient.getConnectionManager().shutdown();
}
Run Code Online (Sandbox Code Playgroud)

并在Menifest中添加权限:

<uses-permission android:name="android.permission.INTERNET"/>
Run Code Online (Sandbox Code Playgroud)

但它有一个例外:NetworkOnMainThreadException,我该怎么办?

android networkonmainthread

3
推荐指数
1
解决办法
8014
查看次数

Retrofit Request Interceptor阻止主线程

这里已经提到这个问题,但这是一个很老的问题,我找不到任何其他信息.

Retrofit API调用的Request Interceptor在主线程上执行.处理AccountManager以将auth令牌添加到请求标头时,这是一个问题,例如

String token = mAccountManager.blockingGetAuthToken(account, AuthConsts.AUTH_TYPE, false);
Run Code Online (Sandbox Code Playgroud)

同样的问题上讨论G +并没有在GitHub上一个相关的问题在这里.

虽然这一切都有效(感谢SquareUp!),解决它的最佳方法是什么?在AsyncTask或类似事件中包装Retrofit调用感觉就像使整个想法失效一样.

android networkonmainthread retrofit

3
推荐指数
1
解决办法
3733
查看次数

Android主线程 - 是否与其他应用共享

想象一下,我们同时打开了两个应用程序(例如三星如何拆分屏幕并允许两个应用程序同时运行).这两个应用程序共享主线程吗?我的问题确实是每个应用程序打开得到自己的主线程?还是它们共享的一个主题?

multithreading android networkonmainthread

3
推荐指数
1
解决办法
61
查看次数