在成功在实际设备上启动活动后,应用立即停止。NetworkOnMainThreadException

huangapple go评论57阅读模式
英文:

After successfully launching activity on physical device, application stops instatnly. NetworkOnMainThreadException

问题

这是来自一个Android项目的完整代码:

Translator.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator extends AppCompatActivity {

    EditText input;
    TextView translated;

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

    public void translate(View view) throws IOException {
        input = (EditText) findViewById(R.id.input);
        String text = input.getText().toString();
        translated = (TextView) findViewById(R.id.translatedText);

        String langFrom = "en";
        String langTo = "hi";

        // INSERT YOU URL HERE
        String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
                "?q=" + URLEncoder.encode(text, "UTF-8") +
                "&target=" + langTo +
                "&source=" + langFrom;
        URL url = new URL(urlStr);
        StringBuilder response = new StringBuilder();
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "Mozilla/5.0");
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        String output = response.toString();
        translated.setText(output);
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FAF3BD"
    tools:context=".Translator">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/tagLine"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.023" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.144"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.069">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/input"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:hint="@string/input"
            android:textSize="24sp" />
    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/translateButton"
        android:layout_width="175dp"
        android:layout_height="67dp"
        android:background="#FF9800"
        android:onClick="translate"
        android:text="@string/translateButton"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView"
        app:layout_constraintVertical_bias="0.46" />

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/translateButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.144"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textInputLayout"
        app:layout_constraintVertical_bias="0.558">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/target_language"
            android:textSize="24sp" />
    </com.google.android.material.textfield.TextInputLayout>

    <TextView
        android:id="@+id/translatedText"
        android:layout_width="305dp"
        android:layout_height="215dp"
        android:background="#FDDB73"
        android:scrollY="500dp"
        android:scrollbarAlwaysDrawVerticalTrack="true"
        android:scrollbarStyle="outsideOverlay"
        android:scrollHorizontally="false"
        android:shadowColor="#FFFFFF"
        android:text="@string/translated"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/translateButton"
        app:layout_constraintVertical_bias="0.751" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/translated_text"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/translatedText"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/translateButton"
        app:layout_constraintVertical_bias="0.731" />

    <View
        android:id="@+id/divider2"
        android:layout_width="350dp"
        android:layout_height="2dp"
        android:layout_marginTop="83dp"
        android:layout_marginBottom="12dp"
        android:background="?android:attr/listDivider"
        app:layout_constraintBottom_toTopOf="@+id/textView3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/translateButton" />

</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml:

<?xml version

<details>
<summary>英文:</summary>

This is my entire code from an android project

Translator.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class Translator extends AppCompatActivity {

EditText input;
TextView translated;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate (View view) throws IOException {
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
String langFrom = &quot;en&quot;;
String langTo = &quot;hi&quot;;
// INSERT YOU URL HERE
String urlStr = &quot;https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec&quot; +
&quot;?q=&quot; + URLEncoder.encode(text, &quot;UTF-8&quot;) +
&quot;&amp;target=&quot; + langTo +
&quot;&amp;source=&quot; + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty(&quot;User-Agent&quot;, &quot;Mozilla/5.0&quot;);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String output =  response.toString();
translated.setText(output);
}

}


activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FAF3BD"
tools:context=".Translator">

&lt;TextView
android:id=&quot;@+id/textView&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/tagLine&quot;
android:textSize=&quot;36sp&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintLeft_toLeftOf=&quot;parent&quot;
app:layout_constraintRight_toRightOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:layout_constraintVertical_bias=&quot;0.023&quot; /&gt;
&lt;com.google.android.material.textfield.TextInputLayout
android:id=&quot;@+id/textInputLayout&quot;
android:layout_width=&quot;300dp&quot;
android:layout_height=&quot;wrap_content&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.144&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/textView&quot;
app:layout_constraintVertical_bias=&quot;0.069&quot;&gt;
&lt;com.google.android.material.textfield.TextInputEditText
android:id=&quot;@+id/input&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;100dp&quot;
android:hint=&quot;@string/input&quot;
android:textSize=&quot;24sp&quot; /&gt;
&lt;/com.google.android.material.textfield.TextInputLayout&gt;
&lt;Button
android:id=&quot;@+id/translateButton&quot;
android:layout_width=&quot;175dp&quot;
android:layout_height=&quot;67dp&quot;
android:background=&quot;#FF9800&quot;
android:onClick=&quot;translate&quot;
android:text=&quot;@string/translateButton&quot;
android:textSize=&quot;30sp&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/textView&quot;
app:layout_constraintVertical_bias=&quot;0.46&quot; /&gt;
enter code here
&lt;com.google.android.material.textfield.TextInputLayout
android:layout_width=&quot;300dp&quot;
android:layout_height=&quot;wrap_content&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/translateButton&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.144&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/textInputLayout&quot;
app:layout_constraintVertical_bias=&quot;0.558&quot;&gt;
&lt;com.google.android.material.textfield.TextInputEditText
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:hint=&quot;@string/target_language&quot;
android:textSize=&quot;24sp&quot; /&gt;
&lt;/com.google.android.material.textfield.TextInputLayout&gt;
&lt;TextView
android:id=&quot;@+id/translatedText&quot;
android:layout_width=&quot;305dp&quot;
android:layout_height=&quot;215dp&quot;
android:background=&quot;#FDDB73&quot;
android:scrollY=&quot;500dp&quot;
android:scrollbarAlwaysDrawVerticalTrack=&quot;true&quot;
android:scrollbarStyle=&quot;outsideOverlay&quot;
android:scrollHorizontally=&quot;false&quot;
android:shadowColor=&quot;#FFFFFF&quot;
android:text=&quot;@string/translated&quot;
android:textSize=&quot;24sp&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.494&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/translateButton&quot;
app:layout_constraintVertical_bias=&quot;0.751&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/textView3&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/translated_text&quot;
android:textSize=&quot;30sp&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/translatedText&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintHorizontal_bias=&quot;0.497&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/translateButton&quot;
app:layout_constraintVertical_bias=&quot;0.731&quot; /&gt;
&lt;View
android:id=&quot;@+id/divider2&quot;
android:layout_width=&quot;350dp&quot;
android:layout_height=&quot;2dp&quot;
android:layout_marginTop=&quot;83dp&quot;
android:layout_marginBottom=&quot;12dp&quot;
android:background=&quot;?android:attr/listDivider&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/textView3&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;@+id/translateButton&quot; /&gt;

</androidx.constraintlayout.widget.ConstraintLayout>


AndroidManifest.xml:

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

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.Translator&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;

</manifest>


Logcat:

Process: com.dhimanujjwal.anuvaad, PID: 14480
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:6412)
at android.view.View$PerformClick.run(View.java:25341)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:6977)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:6412) 
at android.view.View$PerformClick.run(View.java:25341) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6977) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910) 
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:90)
at java.net.InetAddress.getAllByName(InetAddress.java:787)
at com.android.okhttp.Dns$1.lookup(Dns.java:39)
at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:175)
at com.android.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:141)
at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:83)
at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:174)
at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:299)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:237)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(Unknown Source:0)
at com.dhimanujjwal.anuvaad.Translator.translate(Translator.java:45)
at java.lang.reflect.Method.invoke(Native Method) 
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409) 
at android.view.View.performClick(View.java:6412) 
at android.view.View$PerformClick.run(View.java:25341) 
at android.os.Handler.handleCallback(Handler.java:790) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:6977) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:528) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:910) 


</details>
# 答案1
**得分**: 2
你遇到了 `Caused by: android.os.NetworkOnMainThreadException` 异常。我认为这已经解释了一切。要执行这样的操作,你必须在另一个线程上进行。你可以使用 `JobIntentService`。
在你的清单文件中:
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.teststackjava">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ExampleJobIntentService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</application>
</manifest>

MainActivity:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;

public class MainActivity extends AppCompatActivity
{
    EditText input;
    TextView translated;

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

    public void translate(View view)
    {
        input = (EditText) findViewById(R.id.input);
        String text = input.getText().toString();
        translated = (TextView) findViewById(R.id.translatedText);

        ExampleJobIntentService.translatedText.observe(this,
            new Observer<String>()
            {
                @Override
                public void onChanged(String s)
                {
                    translated.setText(s); // change text
                }
            }
        );

        Intent serviceIntent = new Intent(this,
            ExampleJobIntentService.class
        );
        serviceIntent.putExtra("inputExtra", text);
        ExampleJobIntentService.enqueueWork(this, serviceIntent);
    }
}

接下来创建一个继承自 JobIntentService 的类:

import android.content.Context;
import android.content.Intent;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.lifecycle.MutableLiveData;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class ExampleJobIntentService extends JobIntentService
{
    private static final String TAG = "ExampleJobIntentService";

    public static MutableLiveData<String> translatedText = new MutableLiveData<>(); 

    static void enqueueWork(Context context, Intent work)
    {
        enqueueWork(context, ExampleJobIntentService.class, 123, work);
    }

    @Override
    public void onCreate()
    {
        super.onCreate();
        Log.d(TAG, "onCreate");
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent)
    {
        Log.d(TAG, "onHandleWork");

        String input = intent.getStringExtra("inputExtra");

        String langFrom = "en";
        String langTo = "hi";

        try
        {
            String urlStr = "https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec" +
                    "?q=" + URLEncoder.encode(input, "UTF-8") +
                    "&target=" + langTo +
                    "&source=" + langFrom;
            URL url = new URL(urlStr);
            StringBuilder response = new StringBuilder();
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            con.setRequestProperty("User-Agent", "Mozilla/5.0");
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
            {
                response.append(inputLine);
            }
            in.close();
            String output = response.toString();

            Log.i(TAG, "onHandleWork: " + output);

            translatedText.postValue(output);
        }
        catch (IOException e)
        {
            Log.i(TAG, "onHandleWork: ERROR");
        }
    }

    @Override
    public void onDestroy()
    {
        Log.d(TAG, "onDestroy");
        super.onDestroy();
    }

    @Override
    public boolean onStopCurrentWork()
    {
        Log.d(TAG, "onStopCurrentWork");
        return super.onStopCurrentWork();
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <EditText
        android:id="@+id/input"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:hint="input"
        android:textSize="24sp" />


    <Button
        android:id="@+id/translateButton"
        android:layout_width="175dp"
        android:layout_height="67dp"
        android:background="#FF9800"
        android:onClick="translate"
        android:text="translateButton"
        android:textSize="30sp" />


    <TextView
        android:id="@+id/translatedText"
        android:layout_width="305dp"
        android:layout_height="215dp"
        android:background="#FDDB73"
        android:scrollY="500dp"
        android:scrollbarAlwaysDrawVerticalTrack="true"
        android:scrollbarStyle="outsideOverlay"
        android:scrollHorizontally="false"
        android:shadowColor="#FFFFFF"
        android:text="translated"
        android:textSize="24sp" />


</LinearLayout>
英文:

You are getting Caused by: android.os.NetworkOnMainThreadException. I think it says everything. To execute operations like this You have to do it on another thread. You can use JobIntentService.

In Your manifest file:

&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.example.teststackjava&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.WAKE_LOCK&quot; /&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;service
android:name=&quot;.ExampleJobIntentService&quot;
android:permission=&quot;android.permission.BIND_JOB_SERVICE&quot; /&gt;
&lt;/application&gt;
&lt;/manifest&gt;

MainActivity:

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
public class MainActivity extends AppCompatActivity
{
EditText input;
TextView translated;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void translate(View view)
{
input = (EditText) findViewById(R.id.input);
String text = input.getText().toString();
translated = (TextView) findViewById(R.id.translatedText);
// setting observer to translated text
ExampleJobIntentService.translatedText.observe(this,
new Observer&lt;String&gt;()
{
@Override
public void onChanged(String s)
{
translated.setText(s); // change text
}
}
);
Intent serviceIntent = new Intent(this,
ExampleJobIntentService.class
);
serviceIntent.putExtra(&quot;inputExtra&quot;, text);
ExampleJobIntentService.enqueueWork(this, serviceIntent);
}
}

Then create class which extends JobIntentService:

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.lifecycle.MutableLiveData;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ExampleJobIntentService extends JobIntentService
{
private static final String TAG = &quot;ExampleJobIntentService&quot;;
// This is data type which can be observed by another class
public static MutableLiveData&lt;String&gt; translatedText = new MutableLiveData&lt;&gt;(); // I made it public, better to use private and getter
static void enqueueWork(Context context, Intent work)
{
enqueueWork(context, ExampleJobIntentService.class, 123, work);
}
@Override
public void onCreate()
{
super.onCreate();
Log.d(TAG, &quot;onCreate&quot;);
}
@Override
protected void onHandleWork(@NonNull Intent intent)
{
Log.d(TAG, &quot;onHandleWork&quot;);
String input = intent.getStringExtra(&quot;inputExtra&quot;);
String langFrom = &quot;en&quot;;
String langTo = &quot;hi&quot;;
// INSERT YOU URL HERE
try
{
String urlStr = &quot;https://script.google.com/macros/s/AKfycbxt1kjnGx5twzn8lGZopvHkivUCL-B8su8PLXsSRlByiAdRKgA/exec&quot; +
&quot;?q=&quot; + URLEncoder.encode(input, &quot;UTF-8&quot;) +
&quot;&amp;target=&quot; + langTo +
&quot;&amp;source=&quot; + langFrom;
URL url = new URL(urlStr);
StringBuilder response = new StringBuilder();
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty(&quot;User-Agent&quot;, &quot;Mozilla/5.0&quot;);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
String output = response.toString();
Log.i(TAG, &quot;onHandleWork: &quot; + output);
translatedText.postValue(output);//here I am updating data
}
catch (IOException e)
{
Log.i(TAG, &quot;onHandleWork: ERROR&quot;);
}
}
@Override
public void onDestroy()
{
Log.d(TAG, &quot;onDestroy&quot;);
super.onDestroy();
}
@Override
public boolean onStopCurrentWork()
{
Log.d(TAG, &quot;onStopCurrentWork&quot;);
return super.onStopCurrentWork();
}
}

activity_main.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:orientation=&quot;vertical&quot;&gt;
&lt;EditText
android:id=&quot;@+id/input&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;100dp&quot;
android:hint=&quot;input&quot;
android:textSize=&quot;24sp&quot; /&gt;
&lt;Button
android:id=&quot;@+id/translateButton&quot;
android:layout_width=&quot;175dp&quot;
android:layout_height=&quot;67dp&quot;
android:background=&quot;#FF9800&quot;
android:onClick=&quot;translate&quot;
android:text=&quot;translateButton&quot;
android:textSize=&quot;30sp&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/translatedText&quot;
android:layout_width=&quot;305dp&quot;
android:layout_height=&quot;215dp&quot;
android:background=&quot;#FDDB73&quot;
android:scrollY=&quot;500dp&quot;
android:scrollbarAlwaysDrawVerticalTrack=&quot;true&quot;
android:scrollbarStyle=&quot;outsideOverlay&quot;
android:scrollHorizontally=&quot;false&quot;
android:shadowColor=&quot;#FFFFFF&quot;
android:text=&quot;translated&quot;
android:textSize=&quot;24sp&quot; /&gt;
&lt;/LinearLayout&gt;

I have tested this and it seems to work when I tried to translate School I got स्कूल.

在成功在实际设备上启动活动后,应用立即停止。NetworkOnMainThreadException

答案2

得分: 0

我认为您忘记在Java文件中考虑Button部分,您需要创建和链接该Button,然后使用setOnClickListener()为其设置点击事件,以告诉按钮点击时发生的情况。

英文:

I think you forgot to account for the Button in the Java file, you need to create and link the Button and then setOnClickListener() for it , to tell what happens when the Button Clicks.

答案3

得分: 0

Your method transform should must match signature of View.OnClickListener.
You need delete throws IOException it, and handle exception inside method with try/catch block

英文:

Your method transform should must match signature of View.OnClickListener.

You need delete throws IOException it, and handle exception inside method with try/catch block

答案4

得分: 0

如果您在运行应用程序时使用的设备版本为Android 9(API级别28)或更高版本,则默认情况下禁用了明文支持。然后您的AndroidManifest.xml文件应添加以下行:

<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true"
        ...>
        ...
    </application>
</manifest>
英文:

If you run your app in device with version Android 9 (API level 28) or later, cleartext support is disabled by default. Then your AndroidManifest.xml file should add the line:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest ...&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;application
...
android:usesCleartextTraffic=&quot;true&quot;
...&gt;
...
&lt;/application&gt;
&lt;/manifest&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年8月26日 00:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63583458.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定