广播Receiver启动后的服务,如何在该服务中运行AsyncTask?

时间:2014-05-01 12:52:16

标签: android

我想启动一项服务,该服务会在固定的时间间隔(使用警报服务)后向服务器发送地理位置。即,广播接收器启动后的服务,如何在该服务中运行AsynTask?

我试过,但我收到此错误:: caused by:java.lang.RuntimeException:can't create handler inside thread that has not called looper.prepare

我制作了以下代码:

public void onReceive(Context context, Intent intent) {

    // Start periodic service.
    Calendar cal = Calendar.getInstance();

    Intent srvIntent = new Intent(context, NoLopper.class);                 //  StartAtBootService

    PendingIntent pIntent = PendingIntent.getService(context, 0, srvIntent, 0);
    // Use context argument to access service
    AlarmManager alarm =(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

    // Repeat every 5 seconds
    alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
                            10000, pIntent);                                                        
    }

这是我的服务类

    public class NoLopper extends Service 
{

    public static final String url = "http://10.0.2.2:1010/LociServer/HelloWorldServlet";
    String p="50" ;
    String imei="111" ;
    String returnString=null;
    Integer returnedValue=0;



    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see android.app.Service#onCreate()
     */
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Toast.makeText(this, "onCreate of lopper", Toast.LENGTH_LONG)
        .show();
    }

    /* (non-Javadoc)
     * @see android.app.Service#onStartCommand(android.content.Intent, int, int)
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        Toast.makeText(this, "on comand of lopper", Toast.LENGTH_LONG)
        .show();

        GetXMLTask task = new GetXMLTask();
         task.execute(new String[] { url });


         return START_STICKY;
    }


    private class GetXMLTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... urls) 
          {
             String output = null;

//          for (String url : urls) 
//           {
//              output = getOutputFromUrl(url);                         // a loop
//           }

//        return output;
//       }

//      private String getOutputFromUrl(String url) 
//      {
//          String output = null;


            try 
            {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                //ResponseHandler<String> res = new BasicResponseHandler();
                HttpPost httpPost = new HttpPost(url);


                try {


                    String lat="latitude valueee";
                    String lng ="put convereted double into string of latlng variables" ;

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("paramlat", lat));
                nameValuePairs.add(new BasicNameValuePair("paramlng", lng));
                //nameValuePairs.add(new BasicNameValuePair("Gender", gender));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));    // namevaluepair variable are being senddd as entity


                    HttpResponse httpResponse = httpClient.execute(httpPost);  //request the request To execute;; httpRequest variable can be used in future ,ie can be given a warning to the user back
                   // String response = httpClient.execute(httpPost, res);

                Toast.makeText(r.fn.sender.NoLopper.this, "from getxmTAsk inner try block", Toast.LENGTH_LONG).show();


                    HttpEntity httpEntity = httpResponse.getEntity();   //getting the responsed data ;called entites means onject
                    output = EntityUtils.toString(httpEntity);




                      }//end of inner try block



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

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


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



            } //end of outer try block



            catch(Exception e)
            {
                Log.e("log_tag", "Error in http connection "+e.toString());

            }

           Toast.makeText(r.fn.sender.NoLopper.this, "after catch block", Toast.LENGTH_LONG).show();  


         return output;


         }  //end of getOutputFromUrl method



        @Override
        protected void onPostExecute(String output)
        {
            //  tv.setText(output);

            //can be used for camera/turn off the phone keyField intent opening values ,if servlet returns open cam. instruction
        //  Log.d("Helloworld", "ur returned list array "+output.toString());

            Toast.makeText(r.fn.sender.NoLopper.this, "onPost method exe block", Toast.LENGTH_LONG).show();
        }




    }  // end of GetXMLTask
}

登录

    05-01 12:29:05.823: W/Trace(867): Unexpected value from nativeGetEnabledTags: 0
05-01 12:29:05.823: W/Trace(867): Unexpected value from nativeGetEnabledTags: 0
05-01 12:29:05.903: D/gralloc_goldfish(867): Emulator without GPU emulation detected.
05-01 12:29:05.943: W/Trace(867): Unexpected value from nativeGetEnabledTags: 0
05-01 12:29:05.993: W/Trace(867): Unexpected value from nativeGetEnabledTags: 0
05-01 12:29:06.803: E/log_tag(867): Error in http connection java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-01 12:29:06.803: W/dalvikvm(867): threadid=11: thread exiting with uncaught exception (group=0x40a70930)
05-01 12:29:06.843: E/AndroidRuntime(867): FATAL EXCEPTION: AsyncTask #1
05-01 12:29:06.843: E/AndroidRuntime(867): java.lang.RuntimeException: An error occured while executing doInBackground()
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.FutureTask.run(FutureTask.java:239)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.lang.Thread.run(Thread.java:856)
05-01 12:29:06.843: E/AndroidRuntime(867): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.os.Handler.<init>(Handler.java:197)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.os.Handler.<init>(Handler.java:111)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.widget.Toast$TN.<init>(Toast.java:324)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.widget.Toast.<init>(Toast.java:91)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.widget.Toast.makeText(Toast.java:238)
05-01 12:29:06.843: E/AndroidRuntime(867):  at r.fn.sender.NoLopper$GetXMLTask.doInBackground(NoLopper.java:157)
05-01 12:29:06.843: E/AndroidRuntime(867):  at r.fn.sender.NoLopper$GetXMLTask.doInBackground(NoLopper.java:1)
05-01 12:29:06.843: E/AndroidRuntime(867):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
05-01 12:29:06.843: E/AndroidRuntime(867):  at java.util.concurrent.FutureTask.run(FutureTask.java:234)
05-01 12:29:06.843: E/AndroidRuntime(867):  ... 4 more

1 个答案:

答案 0 :(得分:1)

您正在尝试从doInBackground()访问UI,这是一个非UI线程。从doInBackgroud()中删除Toast条消息。您可以使用Log来检查。

Toast.makeText(r.fn.sender.NoLopper.this, "after catch block", Toast.LENGTH_LONG).show();

移除doInBackground()