gpt4 book ai didi

java - 添加 AsyncTask - Android

转载 作者:行者123 更新时间:2023-11-29 22:09:38 24 4
gpt4 key购买 nike

我正在尝试将 AsyncTask 添加到以下类,但我不确定从哪里开始。如果可能的话,我想封装整个类。我是 Android 和 Java 的新手,所以我真的不知道自己在做什么。以下类(class)有效,我可以将所有信息正确发送到我的数据库。每次更新用户的位置时,程序首先检查数据库中的一个表以查找用户 ID;如果表中不存在,则发送 GPS 坐标,但如果用户 ID 在表中,则不发送坐标,程序停止发送位置更新。这可以正常工作,但它会锁定我的 UI 并在尝试交互时抛出 ANR 错误。我知道我需要实现 AsyncTask,但我需要一些指导。下面是该类的完整代码。任何帮助都会很棒!

public class FindLocation  {

protected static final Context SendLocation = null;
private LocationManager locManager;
private LocationListener locListener;

Context ctx;

public FindLocation(Context ctx) {
this.ctx = ctx;
}
public void startLocation(final Context context, String usr_id2) {

final String usr = usr_id2;

//get a reference to the LocationManager
locManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

//checked to receive updates from the position
locListener = new LocationListener() {
public void onLocationChanged(Location loc) {

String lat = String.valueOf(loc.getLatitude());
String lon = String.valueOf(loc.getLongitude());

JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("id", usr));

//http post
try{

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.example.com/test/example.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}

//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");

String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}

catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
String ct_name = json_data.getString("phoneID");
if(ct_name == usr) {
locManager.removeUpdates(locListener);
}
}
}

catch(Exception e){
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/test/example.php");

try {
List<NameValuePair> nameValuePairs1 = new ArrayList<NameValuePair>(2);
nameValuePairs1.add(new BasicNameValuePair("lat", lat));
nameValuePairs1.add(new BasicNameValuePair("lon", lon));
nameValuePairs1.add(new BasicNameValuePair("id", usr));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs1));
httpclient.execute(httppost);
}
catch (ClientProtocolException g) {
// TODO Auto-generated catch block
} catch (IOException f) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


public void onProviderDisabled(String provider){
}
public void onProviderEnabled(String provider){
}
public void onStatusChanged(String provider, int status, Bundle extras){
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 0, locListener);
}
}

最佳答案

你所要做的就是:

  • 通过扩展 asynctask 修改 FindLocation 类
  • 更改 startLocation 以覆盖 doInBackground。

然后调用 asynctask 的 execute 方法而不是 startLocation。

此外,在您的情况下,异步任务可能不是最好的。通常你使用 asynctask 是因为你想在后台做一些事情,然后当任务完成时,用后台操作的结果更新一些 ui 组件。在这里,因为你只是想在后台做一些事情而不是 UI 更新,你最好使用普通线程:

  • 让你上课扩展话题
  • 更改 startLocation 以覆盖运行
  • 启动线程而不是调用 startLocation

--更新细节--

这可能会更简单,但更熟悉 asyncTask 的想法也是一个很好的想法。

public class LocationFinder extends Thread {

public LocationFinder( Context ctx ) {
this.ctx = ctx;
}

public void start( String userId ) {
this.userId = userId;
super.start();
}

//defensive programming : prevent your thread from beeing started in an undesired way
@Override
public void start() {
throw new IllegalStateException( "LocationFinder can't be started using start(). Prefer start( int )." );
}

public void run() {
//remaining of the code of startLocation except the first line.
}

}

使用你的线程然后在一个 Activity 中做:

new LocationFinder( this ).start( userId );

关于java - 添加 AsyncTask - Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9971455/

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