从哪里开始异步任务 - Android电子 [英] Where to Start Async Task - Android

查看:122
本文介绍了从哪里开始异步任务 - Android电子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍然在学习Java / Android开发,我需要一些指导来实现一个异步任务。我主要不确定在哪里我的程序启动它。我在下面列出了一些code,可能有人告诉我在哪里以及如何实现的任务吗?我的应用程序发送的GPS坐标,每一秒的数据库,我需要一个单独的任务,所以我不陷入瘫痪主线程和风险的ARN错误。这里是我的code:

I'm still learning Java/Android development and I need some guidance to implement an Async task. I'm mostly unsure of where to start it in my program. I have outlined some code below, could someone show me where and how to implement the task? My app sends GPS coordinates to a database every second and I need a separate task so I don't bog down the main thread and risk an ARN error. Here is my code:

这首块是从我的主要活动。当按钮为pressed,三秒钟倒计时开始后,当它完成(onFinish)用户数据被发送到一个数据库( SendUserActivity.sendId ... ,这实际上是一个类,而不是一个活动,刚刚入选很差),然后应用程序开始跟踪用户发送坐标到不同的数据库每秒( location.startLocation ... )(两个数据库,以避免重复所有的用户数据)。

This first block is from my main activity. When the button is pressed, a three second countdown is initiated, and when it finishes (onFinish) the user data is sent to one database (SendUserActivity.sendId..., this is actually a class, not an activity, just poorly named) and the app then begins to track the user and send the coordinates to a different database every second (location.startLocation...) (two databases to avoid repeating all of the user's data).

MainActivity.java:

MainActivity.java:

public void onFinish() {
   button.setText("SENT");  
   SendUserActivity.sendId(usr_id1, first, last);                   
   location.startLocation(getBaseContext(), usr_id1);

这是从 LocationActivity 类code的第二块(也是一类,而不是一个活动,命名又变穷了)。它要求一个位置更新每一秒,然后将其发布到了将它插入到MySQL数据库的PHP脚本。

This is the second block of code from the LocationActivity class (also a class and not an activity, poor naming again). It requests a location update every second and then posts it to a PHP script that inserts it in a MySQL database.

public class LocationActivity {

    private LocationManager locManager;
    private LocationListener locListener;

    public void startLocation(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 location) {
            send(location, usr);
        }
        public void onProviderDisabled(String provider){
            //labelState.setText("Provider OFF");
        }
        public void onProviderEnabled(String provider){
            //labelState.setText("Provider ON ");
        }
        public void onStatusChanged(String provider, int status, Bundle extras){
            //Log.i("", "Provider Status: " + status);
            }
        };
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locListener);
    }

    public void send(Location loc, String usr_id2) {

         Log.i("", String.valueOf(loc.getLatitude() + " - " + String.valueOf(loc.getLongitude())));

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

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

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

要重申我的问题,我将如何实现异步任务发送GPS信息到数据库?我看了一下IntentServices,但也有一些建议我用一个异步任务。无论哪种方式,让我知道在哪里以及如何实现其中之一;我真的AP preciate它。谢谢!

To reiterate my question, how would I implement an async task to send the GPS information to the database? I have read about IntentServices, but some have suggested that I use an async task. Either way, let me know where and how to implement one of these; I'd really appreciate it. Thanks!

推荐答案

在这种情况下,基本上你换你发送方法引入的AsyncTask的 doInBackground()方法和结果在 onPostExecute(...)将被设置成一个数据库。让AsyncTask的一个内部类,如果你喜欢。这里是大量的如何使一个AsyncTask的例子。
这里有个例子只是一个问题

In this case basically you wrap your send method into the doInBackground() method of asynctask and a result in the onPostExecute(...) will be set into a DB. Make AsyncTask an inner class if you like. There're plenty of examples of how to make an AsyncTask. Here for example just a question

帮助使用的AsyncTask与数据库以及

的Andr​​oid的AsyncTask和SQLite数据库实例

本网站有很好的教程
http://www.vogella.de/articles/AndroidPerformance/article.html

和ofcourse的马克·墨菲(CommonsWare)
<一href=\"https://github.com/commonsguy/cw-lunchlist/blob/master/15-Internet/LunchList/src/apt/tutorial/FeedActivity.java\" rel=\"nofollow\">https://github.com/commonsguy/cw-lunchlist/blob/master/15-Internet/LunchList/src/apt/tutorial/FeedActivity.java

and ofcourse of Mark Murphy's (CommonsWare) https://github.com/commonsguy/cw-lunchlist/blob/master/15-Internet/LunchList/src/apt/tutorial/FeedActivity.java

干杯

这篇关于从哪里开始异步任务 - Android电子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆