【问题标题】:How to Get GPS Location Using AsyncTask?如何使用 AsyncTask 获取 GPS 位置?
【发布时间】:2017-04-02 15:31:38
【问题描述】:

我已经看到很多此类问题的答案,但与我的任务无关。我正在尝试在后台获取 gps 位置,但在mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener); 中出现Cant Create Handler Inside Thread That Has Not Called Looper Prepare in Android 异常。

public class GPSLocation extends AsyncTask<Void, Void, Void>
    {  
        @Override
        protected void onPreExecute()
        {  
            super.onPreExecute(); 
            progressDialog = new ProgressDialog(RoadMaintenanceActivity.this);
            progressDialog.setCancelable(true);
            progressDialog.setMessage("Getting GPS Location...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setProgress(1);
            progressDialog.show();

        } 
        @Override 
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
         }

        @Override 
        protected void onPostExecute(Void result)
        { 

                progressDialog.cancel(); 
        }
        @Override
        protected Void doInBackground(Void... params) { 

            boolean isGps = false;

            while(!isGps)
            { 
                LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
                LocationListener mlocListener = new MyLocationListener();  
                mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);   
                if(longitude !=0 && latitude!=0)
                {
                    isGps = true; 
                    sendSMS();
                }  
            } 

            return null;  


        }

     } 

我不确定为什么我们不能在 doBackground() 方法中调用它。

感谢你们的帮助。

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    我终于找到了问题所在,我想这会对像我这样的人有所帮助

    public class GPSLocation extends AsyncTask<Void, Void, Void>
        {  
            boolean running =true;
                    @Override
                    protected void onPreExecute()
                    {  
                        super.onPreExecute(); 
                        progressDialog = new ProgressDialog(RoadMaintenanceActivity.this);
                        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
                              public void onCancel(DialogInterface dialog) {
                                  getgps.cancel(true);  
                              }
                        });
                        LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
                        LocationListener mlocListener = new MyLocationListener();  
                        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);    
                        progressDialog.setCancelable(true);
                        progressDialog.setMessage("Getting GPS Location...");
                        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                        progressDialog.setProgress(1);
                        progressDialog.show();
    
                    } 
    
                    @Override 
                    protected void onProgressUpdate(Void... values) {
                        super.onProgressUpdate(values);
                        // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
                     }
    
                    @Override 
                    protected void onPostExecute(Void result)
                    {  
                            progressDialog.cancel(); 
                    }
    
                    @Override
                    protected Void doInBackground(Void... params) {  
                        boolean isDataSubmitted = false;
    
                        while(!isDataSubmitted)
                        {  
                            if(longitude !=0 && latitude!=0)
                            { 
                                sendSMS();
                                isDataSubmitted = true;  
                            }  
                        } 
    
                        return null;    
                    } 
         } 
    

    通过在onPreExecute() 中使用 Locationmanager,可以从我的应用程序中消除异常。我们可以在 onpreexecute 而不是 doinbackground() 中获取 gps。

    【讨论】:

      【解决方案2】:

      你不能那样做。mlocListener 需要一个 Looper 线程来操作。

      在doInBackground调用Looper.prepare();

      所以你的代码会变成这样。

      @Override
              protected Void doInBackground(Void... params) { 
                  Looper.myLooper().prepare();
                  boolean isGps = false;
                  -----------------
      

      【讨论】:

      • 感谢您的回答,实际上我解决了这个问题.. 现在它是另一个 SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(sms_phonenumber, null, message, sentPI, null); 它说空指针异常.. 您对此有任何想法...谢谢
      • 您应该使用最新的错误创建一个新问题,因为我们看不到的问题很难解决。
      【解决方案3】:

      这似乎适合我目前正在尝试做的事情。你有机会告诉我完整的来源吗?我目前已将其应用于我的代码中,但我想看看您如何获取 GPS 坐标并启动异步

      ProgressDialog progressDialog;
      double longitude, latitude;
      
      
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_confirm_screen);
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
          Boolean locationCheck = sp.getBoolean("LOCATION", false);
         if(locationCheck){
      
          }
         else
         {
          sendEmail();
          playSound();
         }
      
      }
      
      public class GPSLocation extends AsyncTask<Void, Void, Void>
      {  
          boolean running =true;
                  @Override
                  protected void onPreExecute()
                  {  
                      super.onPreExecute(); 
                      progressDialog = new ProgressDialog(ConfirmScreen.this);
                      progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){
                            public void onCancel(DialogInterface dialog) {
                                getgps.cancel(true);  
                            }
                      });
      
                      LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
                      LocationListener mlocListener = new MyLocationListener();  
                      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);    
                      progressDialog.setCancelable(true);
                      progressDialog.setMessage("Getting GPS Location...");
                      progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                      progressDialog.setProgress(1);
                      progressDialog.show();
      
                  } 
      
                  @Override 
                  protected void onProgressUpdate(Void... values) {
                      super.onProgressUpdate(values);
                      // Things to be done while execution of long running operation is in progress. For example updating ProgessDialog
                   }
      
                  @Override 
                  protected void onPostExecute(Void result)
                  {  
                          progressDialog.cancel(); 
                  }
      
                  @Override
                  protected Void doInBackground(Void... params) {  
                      boolean isDataSubmitted = false;
      
                      while(!isDataSubmitted)
                      {  
                          if(longitude !=0 && latitude!=0)
                          { 
                              sendEmail();
                              isDataSubmitted = true;  
                          }  
                      } 
      
                      return null;    
                  } 
       } 
      
      
      public void backHome(View view) 
      {
          Intent intent = new Intent (this, MainScreen.class);
          startActivity(intent);
      }
      
      // Method to start playing and looping a sound.
      
      public void playSound()
      {
          MediaPlayer clickSound = MediaPlayer.create(this, R.raw.warning);
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
          Boolean soundCheck = sp.getBoolean("SOUND", false);
          if (soundCheck)
          {
              clickSound.start();
          }
      
      
      
      }// method end
      
      public void sendEmail()
      {
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
          String nameValue = sp.getString("NAME", "failed to get name");
          String emailValue = sp.getString("EMAIL", "failed to get email");
          Intent i = new Intent(Intent.ACTION_SEND);
          i.setType("message/rfc822");
          i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
          i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
          i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. They didn't include co-ords as they assume you know where they are..\nKind Regards\nDon't Panic! \n\n\n");
      
          try
          {   startActivity(Intent.createChooser(i, "Send mail...."));
          } 
          catch (android.content.ActivityNotFoundException ex){
      
              Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
          }
      }
      
      
      public void sendEmail(String a, String b, String c)
      {
          SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
          String nameValue = sp.getString("NAME", "failed to get name");
          String emailValue = sp.getString("EMAIL", "failed to get email");
          Intent i = new Intent(Intent.ACTION_SEND);
          i.setType("message/rfc822");
          i.putExtra(Intent.EXTRA_EMAIL, new String[]{emailValue});
          i.putExtra(Intent.EXTRA_SUBJECT, "Email sent from DON'T PANIC - A Chris O'Brien Project");
          i.putExtra(Intent.EXTRA_TEXT, "Hi there\n" + nameValue + " is in mortal danger. Please see the co-ords attached and run to their rescue!" +
                  " If you don't see any co-ords, they didn't check the box and assume you know where they are.\nKind Regards\nDon't Panic! \n\n\n" + 
                  a + b + c);
      
          try
          {   startActivity(Intent.createChooser(i, "Send mail...."));
          } 
          catch (android.content.ActivityNotFoundException ex){
      
              Toast.makeText(ConfirmScreen.this, "There are no email clients installed or set up", Toast.LENGTH_SHORT).show();
          }
      }
      
      
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          getMenuInflater().inflate(R.menu.activity_confirm_screen, menu);
          return true;
      }
      
      
      
      
      
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        相关资源
        最近更新 更多