【问题标题】:best way to run a method inside service without disturbing Main UI thread在不干扰主 UI 线程的情况下在服务内运行方法的最佳方法
【发布时间】:2017-07-02 08:56:15
【问题描述】:

我有一个方法可以从手机中获取联系人并将其发送到 php 服务器进行处理,然后它将返回数据,以便在 sql lite DB 中更新。我需要在后台连续运行此方法。我正在使用 Volley 进行网络操作。我在服务内部使用 Handler 来运行这个方法。问题是我看到太多跳帧并且应用程序非常慢并且卡住了。我想在不干扰主线程的情况下运行此方法。服务代码如下。

public class serv extends Service {

ArrayList<String> aa= new ArrayList<>();
ArrayList<String> bb= new ArrayList<>();
JSONObject JSONimdb;
JSONObject EverythingJSON;
ArrayList<mobstat> musers = new ArrayList<mobstat>();
private RequestQueue requestQueue;
String l;
private static Timer timer = new Timer();

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.e("Shiva","Service Killed");
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//nonstop1();
 threadcheck();
    return Service.START_STICKY;
}

private void _startService()
{
    long UPDATE_INTERVAL = 5 * 1000;
    timer.scheduleAtFixedRate(
    new TimerTask()
    {
       public void run()
       {
         try
          {
            getNumber(serv.this.getContentResolver());
          } catch (JSONException e)
          {
            e.printStackTrace();
          }
          }
          }, 1000, UPDATE_INTERVAL);
 }

private void nonstop1()
{
   final Handler handlera = new Handler();
    Runnable updatea = new Runnable()
    {
        @Override
        public void run()
        {

            try {
                getNumber(serv.this.getContentResolver());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            handlera.postDelayed(this , 1000);
        }
    };
    handlera.postDelayed(updatea, 10);
}

private void threadcheck()
{
    new Thread() {
         public void run() {
            try {
                Log.e("Shiva","Threadcheck");
                getNumber(serv.this.getContentResolver());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }.start();
}
@Override
public void onDestroy()
{
    super.onDestroy();
   // Intent broadcatIntent = new Intent("com.statmob.findnum");
    //sendBroadcast(broadcatIntent);
    //stoptimertask();
  //nonstop1();
   threadcheck();
}



public void getNumber(ContentResolver cr) throws JSONException
{
    Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    while (phones.moveToNext())
    {
        String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        if (phoneNumber.length()>=10)
        {
          l = phoneNumber.substring(phoneNumber.length()-10);
          aa.add(l);
          bb.add(name);}
    }
    phones.close();

    JSONimdb = new JSONObject();
    for (int i = 0; i < aa.size(); i++)
    {
      try
       {
         JSONimdb.put(bb.get(i), aa.get(i));
       } catch (JSONException e)
         {
           e.printStackTrace();
         }
    }

    EverythingJSON = new JSONObject();
    try
      {
        EverythingJSON.put("imdblist", JSONimdb);
      } catch (JSONException e)
        {
          e.printStackTrace();
        }

   StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://xxxxxxxx/cont.php",
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String s)
                {
                  if (s != null)
                  {
                    parseJSONresponse(s);
                  }
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                  Log.e("Shiva",""+error);
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError
                {
                  Map<String, String> params = new Hashtable<String, String>();
                  params.put("arr", EverythingJSON.toString());
                  return params;
                }
            };

    int socketTimeout = 50000;
    RetryPolicy policy = new DefaultRetryPolicy(socketTimeout,
    DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
    if(requestQueue==null)
    {
      requestQueue = Volley.newRequestQueue(serv.this);}
      stringRequest.setRetryPolicy(policy);
      requestQueue.add(stringRequest);
    }

private void parseJSONresponse(String s)
{
   try
      {
        JSONArray json = new JSONArray(s);

        for (int i = 0; i < json.length(); i++)
        {
          JSONObject e = json.getJSONObject(i);
          musers.add(new mobstat(e.getString("name"), e.getString("status"),e.getLong("time")));
          SugarRecord.updateInTx(musers);

        }
    } catch (JSONException e)
      {
        e.printStackTrace();
      }
    }
 }

我已经尝试过 Timer & Handler,它们工作正常,但它使应用程序变慢并且没有响应。线程不工作。请提出一些更好的方法来在后台运行此方法,而不会对主线程造成任何干扰。

【问题讨论】:

    标签: android multithreading service android-handler


    【解决方案1】:

    在清单文件中为您的服务创建单独的进程可能会对您有所帮助

    <manifest>
    ....
    <application>
    .....
     <service android:name=".serv"  android:process=":myprocess"  >
    </application>
    </manifest>
    

    【讨论】:

      【解决方案2】:

      你试过IntentService吗?这是运行耗时的后台任务的简单方法。

      【讨论】:

        【解决方案3】:

        使用IntentServices 修改您当前的实现。

        默认情况下IntentServices 在后台线程中运行。如果使用Services,它默认使用主线程。然后,您需要在服务内部运行 Thread 以在后台执行该执行块。

        通过thisthis link 了解更多信息

        【讨论】:

        • 但方法 getNumber(serv.this.getContentResolver());只运行一次,我无法在意图服务中启动 nonstop() 处理程序。
        猜你喜欢
        • 2016-12-19
        • 2012-05-07
        • 1970-01-01
        • 1970-01-01
        • 2012-01-20
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        相关资源
        最近更新 更多