gpt4 book ai didi

android - 不同 Activity 中的 AsyncTask 类?

转载 作者:行者123 更新时间:2023-11-29 12:18:53 27 4
gpt4 key购买 nike

可以在不同的类中使用连接类(AsyncTask)吗?

例如,我的 MainActivity 中有以下代码,但我想在不同的 Activity 中使用它,如何将它用作辅助线程?:

public class Connect extends AsyncTask<String, Void, String> {

String resultadoConexion;

@Override
protected String doInBackground(String... urls) {

Connection conn;
try {

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://XXXXXXXXXX?user=XXXX&password=XXXX");
Log.i("Exito","Conexion a la base de datos realizada con exito");

resultadoConexion = "Conectado";
}

catch (Exception e)
{
resultadoConexion = "Error al conectar";
Log.i("ErrorBBDD", "Error: " + e.getMessage());
e.printStackTrace();
}
return resultadoConexion;
}

//Metodo que ejecuta la tarea del hilo
public void Conectar() {
Connect task = new Connect();
task.execute();
}

//Creamos el metodo setText para poder asignar dentro del hilo secundario
private void setText(final TextView text, final String value)
{
runOnUiThread(new Runnable(){
@Override public void run(){
text.setText(value);
}
});
}

}

最佳答案

将内联类放在单独的类文件中并重用它。

ConnectAsyncTask.class

public class ConnectAsyncTask extends AsyncTask<String, Void, String> {

String resultadoConexion;

@Override
protected String doInBackground(String... urls) {

Connection conn;
try {

Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://XXXXXXXXXX?user=XXXX&password=XXXX");
Log.i("Exito","Conexion a la base de datos realizada con exito");

resultadoConexion = "Conectado";
}

catch (Exception e)
{
resultadoConexion = "Error al conectar";
Log.i("ErrorBBDD", "Error: " + e.getMessage());
e.printStackTrace();
}
return resultadoConexion;
}

//Metodo que ejecuta la tarea del hilo
public void Conectar() {
Connect task = new Connect();
task.execute();
}

//Creamos el metodo setText para poder asignar dentro del hilo secundario
private void setText(final TextView text, final String value)
{
runOnUiThread(new Runnable(){
@Override public void run(){
text.setText(value);
}
});
}

然后在任何你想要的地方使用它:

我的 Activity 1:

import package...ConnectAsyncTask;
public void onCreate(Bundle savedinstance) {
new ConnectAsyncTask().execute(url);
}

我的 Activity 2:

import package...ConnectAsyncTask;
public void onCreate(Bundle savedinstance) {
new ConnectAsyncTask().execute(url);
}

或者直接重用您的 Activity 的内部类。例如,您的 Activity 名称是 MyActivity,那么您可以获得连接任务的实例,如下所示:

new MyActivity.Connect()

关于android - 不同 Activity 中的 AsyncTask 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29344104/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com