os.NetowrkOnMainThreadException 服务

os.NetowrkOnMainThreadException service

我阅读了一些教程(一个在教程点,一个在 developer.android.com)并认为我这样做是正确的以避免出现此错误 android.os.NetworkOnMainThreadException 然而,尽管如此,我仍然得到它通过调用 startService 启动我在服务中的网络连接(这发生在我单击 mainactivity 中的开始按钮时,我没有添加布局 xml,但已设置 onClick 方法)

我会尝试在这里粘贴相关代码:

主要activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void startService(View view) {
       startService(new Intent(getBaseContext(),MyService.class));
    }

    public void stopService(View view) {
        stopService(new Intent(getBaseContext(), MyService.class));
    }
}

服务

public class MyService extends Service {
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    /*@Override
    public void onCreate() {

    }*/

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
        KClient client = new KClient(8096);

        if(client.openConn("login","password")) {
            Toast.makeText(this,"Connected",Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this,"failed to connect",Toast.LENGTH_SHORT).show();
        }

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
    }
}

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.frizzled.MyService">

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService" />

    </application>
    <uses-permission android:name="android.permission.INTERNET"/>


</manifest>

服务不是 运行 在单独的线程上,它们 运行 在 UI 线程上。您需要将其移动到服务拥有的 AsyncTask 或 Thread。

onStartCommand() 在主应用程序线程上调用。 A Service 没有自己的线程。 Service 的某些特定子类,如 IntentService,可以。您是否应该使用 IntentService,或者您是否应该继续使用 Service 但分叉您自己的线程,这在很大程度上取决于您打算如何处理网络连接:

  • 如果工作是事务性的(打开连接,做一些工作,关闭连接,离开),使用 IntentService,你的网络工作在 onHandleIntent()

  • 如果工作在时间上会比较开放,比如聊天客户端,使用你自己的线程(由 Service 管理或不管理,取决于你是否需要其他Service 的特征,例如流程重要性)