gpt4 book ai didi

java - 在android中启动asynctask时出错

转载 作者:行者123 更新时间:2023-12-02 05:36:30 25 4
gpt4 key购买 nike

我正在两个不同的服务中启动两个异步任务,第一个任务正常工作并打开套接字,但第二个任务未启动,这里是我的应用程序基于 wifip2p 中的客户端套接字编程的代码。

    public class RecieveAudioService extends Service {

String tag = "Recieve Audio Service";

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Recieve audio :requesting to client", Toast.LENGTH_LONG).show();

String[] param = {"h", "j", "k"};

new request().execute();
Log.v("Recieve Audio", "Inside Recieve audio service");

return super.onStartCommand(intent, flags, startId);
}

//===================== This class is sending request to server for connection when invocked
public class request extends AsyncTask<String, String, String> {

protected String doInBackground(String... arg0) {

Log.v("second asyn", "this is second asynchronous task");

try {

Toast.makeText(getApplicationContext(), "Request to connect sent to server",
Toast.LENGTH_LONG).show();
String toConnectDeviceIP = "192.168.49.1";
Integer toConnectDevicePort = 8988;

Socket connect = new Socket();

connect.bind(null);
connect.connect((new InetSocketAddress(toConnectDeviceIP, toConnectDevicePort)),
5000);
Log.v(tag, "sent the connection request to clint");
connect.close();

} catch (Exception e) {
// TODO Auto-generated catch block
Log.v(tag, "" + e.toString());
Toast.makeText(getApplicationContext(), "i found exception in connection"
+e.toString(), Toast.LENGTH_LONG).show();
}

return "success";
}
}
//====================================================================

}

最佳答案

您似乎是在 Android 4.x/3.x 上启动您的应用。在 Android 3.0 之前,AsyncTasks 是并发运行的,但更高版本(>3.x)的系统会依次执行任务。所以你有两个选择:

a) 使用Threads而不是AsyncTasks

b) 使用AsyncTaskexecuteOnExecutor来并发执行任务:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
task.execute();
}

关于java - 在android中启动asynctask时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24918321/

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