2012-04-02 4 views
1

次のクラスにAsyncTaskを追加しようとしていますが、どこから開始するのかはわかりません。可能であれば、クラス全体をカプセル化したいと思います。私はAndroidとJavaが初めてのので、自分が何をしているのか分からない。次のクラスが動作し、すべての情報をデータベースに正しく送信できます。ユーザーの場所が更新されるたびに、プログラムはまずユーザーIDのデータベース内の表をチェックします。テーブルに存在しない場合はGPS座標が送信されますが、ユーザーIDがテーブルにある場合、座標は送信されず、プログラムは位置更新の送信を停止します。これはうまくいくはずですが、UIをロックして対話しようとするとANRエラーがスローされます。私はAsyncTaskを実装する必要があることを知っていますが、いくつかのガイダンスが必要です。以下はクラスの完全なコードです。どんな助けも素晴らしいだろう!AsyncTaskを追加する - Android

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); 
} 
} 
+0

でインスタンス呼び出しnew BackgroundLoader().execute();を作成します(http://developer.android.com/reference/android/app/Service.html)は実装するのが良いです。詳細については – user370305

答えて

2

あなたがしなければならない必要があるすべては次のとおりです。

  • は、doInBackgroundのオーバーライドのためのasynctask
  • 変更startLocationを拡張することによってFindLocationクラスを変更します。

次に、startLocationの代わりにasynctaskのexecuteメソッドを呼び出します。

また、あなたのケースでは、asynctaskが最適でない場合があります。通常は、バックグラウンドで何かをしたいときにasynctaskを使います。そして、タスクが完了したら、いくつかのUIコンポーネントをバックグラウンド操作の結果で更新します。ここで、あなたはちょうどあなたがより良い通常のスレッド使用することができ、バックグラウンドで何かをしたいんが、何のUIのアップデートとして:

  • をあなたのクラスがスレッドを拡張し、実行
  • のオーバーライドのための
  • 変更startLocationがあなたを開始
  • 作ります代わりに、詳細を--update

startLocationを呼び出したスレッド -

これは単純かもしれないが、asyncTaskに精通取得するためのアイデアはに良いものをイアo。

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); 
+0

+1を参照してください。 – Deva

+0

これはもっと理にかなっています。 '実行のオーバーライドのためにstartLocationを変更する方法を拡張できますか?また、私はメインアクティビティからstartLocationを呼び出してユーザーIDを渡していますが、これをどのように渡しますか?私の主な活動の中で私の呼びかけは何でしょうか?ありがとう – mkyong

+0

あなたのメソッドstartLocationの名前をpublic void run()に変更してください。スレッドを開始するには、それをインスタンス化してstartを呼び出します。 – Snicolas

0
​​

を次にあなたのケースでは、あなたのonCreate()方法

関連する問題