Java 添加异步任务-Android
我正在尝试向下面的类添加AsyncTask,但不确定从何处开始。如果可能的话,我想封装整个类。我是Android和Java新手,所以我真的不知道自己在做什么。下面的类有效,我可以将所有信息正确地发送到我的数据库。每次更新用户位置时,程序首先检查数据库中的一个表中的用户ID;如果表中不存在GPS坐标,则发送GPS坐标,但如果用户ID在表中,则不发送坐标,程序停止发送位置更新。这就像它应该的那样工作,但它会锁定我的UI,并在尝试交互时抛出ANR错误。我知道我需要实现一个异步任务,但我需要一些指导。下面是该类的完整代码。任何帮助都会很好Java 添加异步任务-Android,java,android,class,gps,android-asynctask,Java,Android,Class,Gps,Android Asynctask,我正在尝试向下面的类添加AsyncTask,但不确定从何处开始。如果可能的话,我想封装整个类。我是Android和Java新手,所以我真的不知道自己在做什么。下面的类有效,我可以将所有信息正确地发送到我的数据库。每次更新用户位置时,程序首先检查数据库中的一个表中的用户ID;如果表中不存在GPS坐标,则发送GPS坐标,但如果用户ID在表中,则不发送坐标,程序停止发送位置更新。这就像它应该的那样工作,但它会锁定我的UI,并在尝试交互时抛出ANR错误。我知道我需要实现一个异步任务,但我需要一些指导。下
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);
}
}
公共类查找位置{
受保护的静态最终上下文SendLocation=null;
私人场所经理;
私有位置侦听器;
上下文ctx;
公共查找位置(上下文ctx){
this.ctx=ctx;
}
公共上下文(最终上下文,字符串usr_id2){
最终字符串usr=usr_id2;
//获取LocationManager的引用
LocationManager=(LocationManager)context.getSystemService(context.LOCATION\u服务);
//选中以接收来自该职位的更新
locListener=新的LocationListener(){
位置更改后的公共无效(位置loc){
String lat=String.valueOf(loc.getLatitude());
String lon=String.valueOf(loc.getLongitude());
杰索纳雷·贾雷;
字符串结果=null;
InputStream=null;
StringBuilder sb=null;
ArrayList nameValuePairs=新的ArrayList();
添加(新的BasicNameValuePair(“id”,usr));
//http post
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“http://www.example.com/test/example.php");
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=httpclient.execute(httppost);
HttpEntity=response.getEntity();
is=entity.getContent();
}捕获(例外e){
e(“Log_标记”,“http连接错误”+e.toString());
}
//将响应转换为字符串
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
sb=新的StringBuilder();
sb.append(reader.readLine()+“\n”);
字符串行=“0”;
而((line=reader.readLine())!=null){
sb.追加(第+行“\n”);
}
is.close();
结果=sb.toString();
}
捕获(例外e){
Log.e(“Log_标记”,“错误转换结果”+e.toString());
}
试一试{
jArray=新的JSONArray(结果);
JSONObject json_data=null;
对于(int i=0;i您需要做的就是:
- 通过扩展asynctask修改FindLocation类
- 更改doInBackground覆盖的位置
然后调用asynctask的execute方法,而不是startLocation
另外,在您的情况下,asynctask可能不是最好的。通常您使用asynctask是因为您希望在后台执行某些操作,然后在任务完成后,使用后台操作的结果更新某些ui组件。在这里,由于您只希望在后台执行某些操作,而不需要进行ui更新,因此使用普通的thre可能会更好广告:
- 让你的类延伸线程
- 更改运行覆盖的位置
- 启动您的线程,而不是调用
--更新详细信息--
这可能更简单,但更熟悉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.
}
}
要在活动中使用线程,请执行以下操作:
new LocationFinder( this ).start( userId );
私有类后台加载程序扩展异步任务{
私人对话;
受保护的长doInBackground(){
dialog=新进度对话框(ctx);
dialog.show();
}
受保护的void doInBackground(){
//在这里执行所有不修改UI的操作
}
受保护的void onPostExecute(长结果){
//执行您需要的操作以访问UI
dialog.dismise();
}
然后在onCreate()中创建实例调用newbackgroundloader().execute();
method在您的情况下,可以很好地实现。好的,这更有意义。您可以详细介绍如何更改startLocation以覆盖run吗?
另外,我正在从我的主活动调用startLocation并传递一个用户id,我将如何传递它?我在主活动中的调用具体是什么?谢谢命名您的方法开始位置到public void run()。然后要启动您的线程,请实例化它并调用start。那么如何从我的主要活动中调用它呢?不。然后在将参数保存到数据成员中后,定义一个方法start(userId)并从中调用start()。您的方法运行,因为它是一个重写,应该没有参数。让我们来看看
private class BackgroundLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Long doInBackground() {
dialog = new ProgressDialog(ctx);
dialog.show();
}
protected void doInBackground() {
// do all your stuff here that doesn't modify the UI
}
protected void onPostExecute(Long result) {
// do what you need to to the UI
dialog.dismiss();
}