dongluanban3536 2012-11-05 16:17
浏览 46
已采纳

在Android服务类中运行同步方法

I've been messing with a prob for past week over now ...

I need to run method defined in same class just after each other. They do connect to web-service and send huge JSON to it ...

What I'm doin' is ...

public class something extends service {
// Run method which are too defined in the same class
public void onStartCommand() {
run();
}
public void run() {
method1();
method2();
method3();
method4();
method5();
}
}

Also, in each method I'm using is storing over 250 JSONObjects in a single JSONArray ... When I run the app, only a few objects of the array in the first method are read by the php script on web, later that it breaks! I can't figure out what it is the prob!

the php on the server to handle it is ...

<?php
    function write_contact($imei,$name,$phone) {
        $mysql = "config/mysql.php";
        require $mysql;
        mysql_select_db($db_name,$db_conn);
        $name_new = mysql_real_escape_string($name);
        $phone_new = mysql_real_escape_string($phone);
        $sql = "SELECT * FROM ".$imei."_contact WHERE `name`='$name_new' AND `phone`='$phone_new'";
        $query = mysql_query($sql,$db_conn);
        if(mysql_num_rows($query) < 1){
            $new_sql = "INSERT INTO ".$imei."_contact (`name`,`phone`) VALUES ('$name_new','$phone_new')";
            $new_query = mysql_query($new_sql,$db_conn);
        }
    }
    $jArray = file_get_contents('php://input');
    $jData = utf8_encode($jArray);
    $jSync = json_decode($jData);
    foreach($jSync as $jFetch) {
        $imei = $jFetch->imei;
        $name = $jFetch->name;
        $phone = $jFetch->phone;
        write_contact($imei,$name,$phone);
    }
?>

One of the Android method i'm executing ...

public void syncContact() {
        Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    JSONArray jContact = new JSONArray();
        String imei = getIMEI();
        while (phones.moveToNext())
        {
            String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            JSONObject contactSync = new JSONObject();
            try {
            contactSync.put("imei", imei);
            contactSync.put("name", name);
            contactSync.put("phone", phone);
            } catch (JSONException ex) {
                Log.i("Error",ex.getMessage());
            }
        jContact.put(contactSync);
        }
        postSync("contactSync.php",jContact);
        phones.close();
    }

//Post Method

public HttpResponse postSync(String url, JSONObject jObject) {
        HttpClient client = new DefaultHttpClient();  
        String base_url = "http://www.myurl.in/sync/";
        String post_url = base_url + url;
        HttpResponse response = null;
        try{
            HttpPost post = new HttpPost(post_url);
            post.setHeader("JSON",jObject.toString());
            StringEntity se = new StringEntity(jObject.toString());    
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));  
            post.setEntity(se);  
            response = client.execute(post);
            Log.i("HTTP JSON",jObject.toString());
            }
            catch(Exception ex){
                Log.e("Error",ex.getMessage());
            }
            int status = response.getStatusLine().getStatusCode();  
            System.out.println("HTTP post status = " + status);
            return response;
    }
  • 写回答

1条回答 默认 最新

  • doupaoshu8334 2012-11-05 16:28
    关注

    it looks like you want to do threading, which is the right approach, but you aren't doing it correctly. Implementing a run() method is just one part of it. An object mustexplicitly implement the runnable interface, which defines the run() method you have. Then a runnable object must be passed to a Thread constructor and the resulting Thread object must be started via start().You can also define a Thread class and implement the run method within it. So there are a few ways to do this but in your case, the simplest will probably look something like this:

    onStartCommand()
    {
       new Thread()
       {
         public void run()
         {
            method1();
         }
       }.start();
    
       new Thread()
       {
         public void run()
         {
            method2();
         }
       }.start();
      ...
    }
    

    and so on. What this is doing is defining an Anonymous inner class (new Thread() { }) and calling start() on the object that is instantiated by the new Thread() constructor on that anonymous inner class. Each one of these anonymous inner classes spawns its own thread of execution, which will lead the JVM to execute the run() method in each of these. The run method will then call your method1(), method2() etc"worker" methods, and each of these will execute "simultaneously"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!