英文:
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 = "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" />
enter code here
<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="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dhimanujjwal.anuvaad">
<uses-permission android:name="android.permission.INTERNET"/>
<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=".Translator">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</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:
<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);
// setting observer to translated text
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);
}
}
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 = "ExampleJobIntentService";
// This is data type which can be observed by another class
public static MutableLiveData<String> translatedText = new MutableLiveData<>(); // 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, "onCreate");
}
@Override
protected void onHandleWork(@NonNull Intent intent)
{
Log.d(TAG, "onHandleWork");
String input = intent.getStringExtra("inputExtra");
String langFrom = "en";
String langTo = "hi";
// INSERT YOU URL HERE
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);//here I am updating data
}
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>
I have tested this and it seems to work when I tried to translate School
I got स्कूल
.
答案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 -->
<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
<uses-permission android:name="android.permission.INTERNET" />
<application
...
android:usesCleartextTraffic="true"
...>
...
</application>
</manifest>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论