1

描述:我正在开发LBS应用程序,我正在使用 GPS 和网络提供商来访问位置并将数据通过 GPRS 发送到服务器。我想连续运行这个应用程序来定位用户。一切都运行得很好,只有当我的应用程序进入后台时。

问题:我的应用程序在前台运行时正确运行,但我希望此应用程序在后台运行,当我在运行应用程序时按下主页按钮时,我收到此错误消息。以下是我的 MainActivity 和 Mylocationlistener 类。

主要活动:-

package com.example.trackme;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

    private Button start;

    private static final int TEN_SECONDS = 10000;
    private static final int TEN_METERS = 10;
    private static final int TWO_MINUTES = 1000 * 60 * 2;
    private boolean mGeocoderAvailable;
    private String addressText;
    LocationManager mlocManager ;
     LocationListener mlocListener=new MyLocationListener("", "");

    private String device_ID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

         mGeocoderAvailable =Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD && Geocoder.isPresent();

        setContentView(R.layout.activity_main);


        start=(Button)findViewById(R.id.button1);


        start.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {



            }
        });
    }



    protected void onResume() {
        super.onResume();
        setup();
    }
    private void setup() {
         Location gpsLocation = null;
            Location networkLocation = null;


            TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);

            device_ID=telephonyManager.getDeviceId();

            mlocManager.removeUpdates(mlocListener);
                gpsLocation = requestUpdatesFromProvider(
                     LocationManager.GPS_PROVIDER);

                networkLocation = requestUpdatesFromProvider(
                        LocationManager.NETWORK_PROVIDER);
                // Update the UI immediately if a location is obtained.

                // If both providers return last known locations, compare the two and use the better
                // one to update the UI.  If only one provider returns a location, use it.
                if (gpsLocation != null && networkLocation != null) {
                    updateUILocation(getBetterLocation(gpsLocation, networkLocation));
                } else if (gpsLocation != null) {
                    updateUILocation(gpsLocation);
                } else if (networkLocation != null) {
                    updateUILocation(networkLocation);


    }
}



                private void doReverseGeocoding(Location location) {
                    // Since the geocoding API is synchronous and may take a while.  You don't want to lock
                    // up the UI thread.  Invoking reverse geocoding in an AsyncTask.
                    (new ReverseGeocodingTask(this)).execute(new Location[] {location});
                      mlocListener = new MyLocationListener(addressText,device_ID); 
                }

                private void updateUILocation(Location location) {
                    // We're sending the update to a handler which then updates the UI with the new
                    // location.
                    Toast.makeText(getApplicationContext(),location.getProvider()+ ","+ location.getLatitude() + ", " + location.getLongitude(),Toast.LENGTH_LONG).show();


                    if (mGeocoderAvailable) doReverseGeocoding(location);
                }

                protected Location getBetterLocation(Location newLocation, Location currentBestLocation) {
                    if (currentBestLocation == null) {
                        // A new location is always better than no location
                        return newLocation;
                    }

                    // Check whether the new location fix is newer or older
                    long timeDelta = newLocation.getTime() - currentBestLocation.getTime();
                    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
                    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
                    boolean isNewer = timeDelta > 0;

                    // If it's been more than two minutes since the current location, use the new location
                    // because the user has likely moved.
                    if (isSignificantlyNewer) {
                        System.out.println("Provider"+newLocation.getProvider());
                        return newLocation;
                    // If the new location is more than two minutes older, it must be worse
                    } else if (isSignificantlyOlder) {
                        System.out.println("Provider"+currentBestLocation.getProvider());
                        return currentBestLocation;
                    }

                    // Check whether the new location fix is more or less accurate
                    int accuracyDelta = (int) (newLocation.getAccuracy() - currentBestLocation.getAccuracy());
                    boolean isLessAccurate = accuracyDelta > 0;
                    boolean isMoreAccurate = accuracyDelta < 0;
                    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

                    // Check if the old and new location are from the same provider
                    boolean isFromSameProvider = isSameProvider(newLocation.getProvider(),
                            currentBestLocation.getProvider());

                    // Determine location quality using a combination of timeliness and accuracy
                    if (isMoreAccurate) {
                        System.out.println("Provider"+newLocation.getProvider());
                        return newLocation;

                    } else if (isNewer && !isLessAccurate) {
                         System.out.println("Provider"+newLocation.getProvider());
                        return newLocation;

                    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
                         System.out.println("Provider"+newLocation.getProvider());
                        return newLocation;
                    }
                    System.out.println("Provider"+currentBestLocation.getProvider());
                    return currentBestLocation;


                }

                private boolean isSameProvider(String provider1, String provider2) {
                    if (provider1 == null) {
                      return provider2 == null;
                    }
                    return provider1.equals(provider2);
                }

    private Location requestUpdatesFromProvider(String provider) {
        Location location = null;

        if (mlocManager.isProviderEnabled(provider)) {
            mlocManager.requestLocationUpdates(provider, TEN_SECONDS, TEN_METERS, mlocListener);
            location = mlocManager.getLastKnownLocation(provider);
        } else {
          //  Toast.makeText(this, errorResId, Toast.LENGTH_LONG).show();
        }
        return location;

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }


    @Override
    protected void onStart() {
        super.onStart();

         mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

        final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 


        if (!gpsEnabled) {
            // Build an alert dialog here that requests that the user enable
            // the location services, then when the user clicks the "OK" button,
            // call enableLocationSettings()

            Toast.makeText(getApplicationContext(), "Pls Enable GPS" , Toast.LENGTH_LONG).show();

    }

}





private class ReverseGeocodingTask extends AsyncTask<Location, Void, Void> {
    Context mContext;


    public ReverseGeocodingTask(Context context) {
        super();
        mContext = context;

           }





    @Override
    protected Void doInBackground(Location... params) {
        Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

        Location loc = params[0];
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
        } catch (IOException e) {
            e.printStackTrace();
            // Update address field with the exception.

            System.out.println(e.toString());
        }
        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            // Format the first line of address (if available), city, and country name.
             addressText = String.format("%s, %s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                    address.getLocality(),
                    address.getCountryName());
            // Update address field on UI.
           // Message.obtain(mHandler, UPDATE_ADDRESS, addressText).sendToTarget();
        //Toast.makeText(getApplicationContext(), addressText, Toast.LENGTH_LONG).show();
        System.out.println(addressText);




        }
        return null;
    }
}
}

Mylocation监听器:-

package com.example.trackme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.IBinder;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class MyLocationListener extends Service implements android.location.LocationListener {




    private static String device_ID;
    private float mySpeed;
    private Object time;
    private String lat;
    private String longitude;
    private int level;

    private String locate;


    public MyLocationListener(String addressText,String Device_id) {
        locate=addressText;
        MyLocationListener.device_ID=Device_id;
    }




    @Override
    public void onLocationChanged(Location loc) {




        lat= String.valueOf(loc.getLatitude());

        longitude=String.valueOf(loc.getLongitude());


        if((lat!=null) && (longitude!=null))
        {


              String Text = "My current location is: " +

              "Latitud = " + loc.getLatitude() +

              "Longitud = " + loc.getLongitude();

            //  Toast.makeText(this, Text, Toast.LENGTH_SHORT).show();


          //  Send.performClick();
              AsyncTaskRunner runner = new AsyncTaskRunner();
                String sleepTime = "2000";

                if(loc.hasSpeed()){ 

                    mySpeed =  (float) (3.6 * (loc.getSpeed())); 
                   //  System.out.println("\nCurrent speed: " + mySpeed + " km/h"); 
                }

                runner.execute(sleepTime);
            Log.d("Location Found", Text);
        }



    }


    @Override
    public void onProviderDisabled(String provider) {
    Toast.makeText(getApplicationContext(), "Provider is Disabled",Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderEnabled(String provider) {

        Toast.makeText(getApplicationContext(), "Provider is Enabled",Toast.LENGTH_SHORT).show();


    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

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


    private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {


        @Override
        public void onReceive(Context context, Intent intent) {

        //  int  health= intent.getIntExtra(BatteryManager.EXTRA_HEALTH,0);
        //  int  voltage= intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE,0);
             level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,0);

            System.out.println( "Level" +level);
        }
    };


    private class AsyncTaskRunner extends AsyncTask<String, String, String> {

          private String resp;


          @Override
          protected String doInBackground(String... params) {
           publishProgress("Sleeping..."); // Calls onProgressUpdate()
           try {
            // Do your long operations here and return the result
            int time = Integer.parseInt(params[0]);


            // Sleeping for given time period
            Thread.sleep(time);

           HttpClient httpClient = new DefaultHttpClient();

            String postURL = "";

             postURL = "http://smpl.trackfleet.biz/lat_long.php?lat="+lat+"&long="+longitude+"&speed="+mySpeed +"&IMEI_NO="+MyLocationListener.device_ID+"&battery_level="+level +"&location="+locate;

            //postURL = "http://bb.trackfleet.biz/android_gps/lat_long.php?lat="+lat+"&long="+longitude+"&speed=0" +"&IMEI_NO=911223100301734"+"&battery_level="+level;
                    System.out.println(postURL);
            HttpPost httpPost = new HttpPost(postURL);

            HttpResponse httpResponse = null;

            try
            {
        //      Toast.makeText(getApplicationContext(),"Sending location to Server", Toast.LENGTH_SHORT).show();
                System.out.println("Sending to server");
                httpResponse = httpClient.execute(httpPost); 

                String str = inputStreamToString(httpResponse.getEntity().getContent()).toString();
                System.out.println("Response"+str);
            //  location_sms="Sales Person="+str+"latitude="+lat+"longitude="+longitude+"&speed="+mySpeed +"&IMEI_NO="+device_ID+"&battery_level="+level +"&location="+addressText;
                // getSharedPreferences("Values", 4).edit().putString("location_sms",location_sms).commit();

            //  Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();


            }
            catch(Exception ex)
            {
                //Toast.makeText(getApplicationContext(),"Could not communicate with Server" , Toast.LENGTH_SHORT).show();  
                System.out.println("Could not communicate with Server");
ex.printStackTrace();
            }





           } catch (InterruptedException e) {
            e.printStackTrace();
            resp = e.getMessage();
           } catch (Exception e) {
            e.printStackTrace();
            resp = e.getMessage();
           }
           return resp;
          }



        private StringBuilder inputStreamToString(InputStream is) {
          String line = "";
            StringBuilder total = new StringBuilder();
    // Wrap a BufferedReader around the InputStream
    BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    // Read response until the end
    try {
        while ((line = rd.readLine()) != null) { 
            total.append(line); 
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    // Return full string
    return total;
}
    }

    }

日志猫:-

 WIN DEATH: Window{40c12c30 com.example.trackme/com.example.trackme.MainActivity paused=false}
02-18 13:16:45.939: I/SurfaceFlinger(201):                                                                              
02-18 13:16:45.939: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting enter
02-18 13:16:45.939: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting exit: 0
02-18 13:16:45.940: I/SurfaceFlinger(201):                                                                              
02-18 13:16:45.940: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting enter
02-18 13:16:45.940: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting exit: 0
02-18 13:16:45.942: D/IPCThreadState(201): [DN #5] BR_DEAD_BINDER cookie 0x3b5c08
02-18 13:16:45.942: D/IPCThreadState(201): [DN #5] BR_CLEAR_DEATH_NOTIFICATION_DONE cookie 0x3b5c08
02-18 13:16:45.942: D/IPCThreadState(201): [DN #5] BR_DEAD_BINDER cookie 0x20ce78
02-18 13:16:45.942: V/LocationManagerService(201): Location listener died
02-18 13:16:45.942: D/IPCThreadState(201): [DN #5] BR_DEAD_BINDER cookie 0x5ba5d8
02-18 13:16:45.943: V/ActivityManager(201): Death received in com.android.server.am.ActivityManagerService$AppDeathRecipient@40945b90 for thread android.os.BinderProxy@40a29e30
02-18 13:16:45.943: I/ActivityManager(201): Process com.example.trackme (pid 26976) has died.
02-18 13:16:45.943: V/ActivityManager(201): Dying app: ProcessRecord{408e7ae8 26976:com.example.trackme/10067}, pid: 26976, thread: android.os.BinderProxy@40a29e30
02-18 13:16:45.943: V/ActivityManager(201): Removing app ProcessRecord{408e7ae8 0:com.example.trackme/10067} from list [HistoryRecord{40a61240 com.android.phone/.InCallScreen}, HistoryRecord{4077ea58 com.example.trackme/.MainActivity}, HistoryRecord{40875438 com.android.mlabs/.Launcher}, HistoryRecord{409808e8 com.android.settings/.SettingsTabActivity}, HistoryRecord{40adb610 com.android.settings/.ApplicationSettings}, HistoryRecord{4093d3a0 com.android.settings/.ManageApplications}] with 6 entries
02-18 13:16:45.943: V/ActivityManager(201): Record #5 HistoryRecord{4093d3a0 com.android.settings/.ManageApplications}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.943: V/ActivityManager(201): Record #4 HistoryRecord{40adb610 com.android.settings/.ApplicationSettings}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.943: V/ActivityManager(201): Record #3 HistoryRecord{409808e8 com.android.settings/.SettingsTabActivity}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.943: V/ActivityManager(201): Record #2 HistoryRecord{40875438 com.android.mlabs/.Launcher}: app=ProcessRecord{407ef4e8 23796:android.process.acore/10036}
02-18 13:16:45.943: V/ActivityManager(201): Record #1 HistoryRecord{4077ea58 com.example.trackme/.MainActivity}: app=ProcessRecord{408e7ae8 0:com.example.trackme/10067}
02-18 13:16:45.943: V/ActivityManager(201): Removing this entry!
02-18 13:16:45.943: V/ActivityManager(201): Record #0 HistoryRecord{40a61240 com.android.phone/.InCallScreen}: app=ProcessRecord{40881af0 289:com.android.phone/1001}
02-18 13:16:45.943: V/ActivityManager(201): Removing app ProcessRecord{408e7ae8 0:com.example.trackme/10067} from list [] with 0 entries
02-18 13:16:45.943: V/ActivityManager(201): Removing app ProcessRecord{408e7ae8 0:com.example.trackme/10067} from list [] with 0 entries
02-18 13:16:45.943: V/ActivityManager(201): Removing app ProcessRecord{408e7ae8 0:com.example.trackme/10067} from list [] with 0 entries
02-18 13:16:45.944: V/ActivityManager(201): Removing app ProcessRecord{408e7ae8 0:com.example.trackme/10067} from history with 10 entries
02-18 13:16:45.944: V/ActivityManager(201): Record #9 HistoryRecord{4093d3a0 com.android.settings/.ManageApplications}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.944: V/ActivityManager(201): Record #8 HistoryRecord{40adb610 com.android.settings/.ApplicationSettings}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.944: V/ActivityManager(201): Record #7 HistoryRecord{409808e8 com.android.settings/.SettingsTabActivity}: app=ProcessRecord{40c1f9e8 26810:com.android.settings/1000}
02-18 13:16:45.944: V/ActivityManager(201): Record #6 HistoryRecord{40875438 com.android.mlabs/.Launcher}: app=ProcessRecord{407ef4e8 23796:android.process.acore/10036}
02-18 13:16:45.944: V/ActivityManager(201): Record #5 HistoryRecord{4077ea58 com.example.trackme/.MainActivity}: app=ProcessRecord{408e7ae8 0:com.example.trackme/10067}
02-18 13:16:45.944: V/ActivityManager(201): Keeping entry, setting app to null
02-18 13:16:45.944: V/ActivityManager(201): Record #4 HistoryRecord{40c103b8 com.android.mms/.ui.ComposeMessageActivity}: app=null
02-18 13:16:45.944: V/ActivityManager(201): Record #3 HistoryRecord{40a540b8 com.android.mms/com.gionee.mms.ui.MmsSmsTabActivity}: app=null
02-18 13:16:45.944: V/ActivityManager(201): Record #2 HistoryRecord{40923ef8 com.android.contacts/.DialtactsActivity}: app=null
02-18 13:16:45.944: V/ActivityManager(201): Record #1 HistoryRecord{40a21258 com.android.calculator2/.Calculator}: app=null
02-18 13:16:45.944: V/ActivityManager(201): Record #0 HistoryRecord{40a61240 com.android.phone/.InCallScreen}: app=ProcessRecord{40881af0 289:com.android.phone/1001}
02-18 13:16:45.944: D/IPCThreadState(201): [DN #5] BR_CLEAR_DEATH_NOTIFICATION_DONE cookie 0x5ba6c8
02-18 13:16:45.947: V/LocationManagerService(201): _removeUpdates: listener = Receiver{409892c0 Listener android.os.BinderProxy@40929d88}mUpdateRecords: {gps=UpdateRecord{40a5e288 mProvider: gps mUid: 10067}, network=UpdateRecord{408e66d0 mProvider: network mUid: 10067}}
02-18 13:16:45.949: D/IPCThreadState(201): [DN #5] BR_CLEAR_DEATH_NOTIFICATION_DONE cookie 0x5ba5d8
02-18 13:16:45.949: D/LocationManagerService(201): removeUpdatesLocked is called provider:receiver: Receiver{409892c0 Listener android.os.BinderProxy@40929d88}mUpdateRecords: {gps=UpdateRecord{40a5e288 mProvider: gps mUid: 10067}, network=UpdateRecord{408e66d0 mProvider: network mUid: 10067}}callingPid: 201ap name:system
02-18 13:16:45.950: D/PowerManagerService(201): acquireWakeLock flags=0x1 tag=GpsLocationProvider
02-18 13:16:45.950: I/SurfaceFlinger(201):                                                                              
02-18 13:16:45.950: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting enter
02-18 13:16:45.950: I/SurfaceFlinger(201): surface flinger stars handleComposing3DStateSetting exit: 0
02-18 13:16:45.952: D/Settings/Provide(201): lookupValue, table secure cache.containsKey location_providers_allowed
02-18 13:16:45.952: D/LocationManagerService(201): isAllowedBySettingsLocked gpsistrue
02-18 13:16:45.952: D/PowerManagerService(201): acquireWakeLock flags=0x1 tag=GpsLocationProvider
02-18 13:16:45.952: D/Settings/Provide(201): lookupValue, table secure cache.containsKey location_providers_allowed
02-18 13:16:45.952: D/LocationManagerService(201): isAllowedBySettingsLocked networkistrue
02-18 13:16:45.955: W/GpsLocationProvider(201): Unneeded remove listener for uid 1000
02-18 13:16:45.955: D/IPCThreadState(201): [DN #5] BR_CLEAR_DEATH_NOTIFICATION_DONE cookie 0x20ce78
02-18 13:16:45.957: D/androidNlpServiceThread(280): adding listener com.google.android.location.internal.client.NetworkLocationClient$1@40553208 with period 86400
02-18 13:16:45.957: D/androidNetworkLocationListeners(280): Still have listener com.google.android.location.internal.client.NetworkLocationClient$1@40553208
02-18 13:16:45.959: D/PowerManagerService(201): acquireWakeLock flags=0x1 tag=NetworkLocationLocator
02-18 13:16:45.960: D/GpsLocationProvider(201): stopNavigating
02-18 13:16:45.961: D/WifiService(201): acquireWifiLockLocked: WifiLock{NetworkLocationLocator type=2 binder=android.os.BinderProxy@409c64a0}
02-18 13:16:45.961: D/Settings/Provide(201): lookupValue, table secure cache.containsKey wifi_on
02-18 13:16:45.961: D/WifiService(201): doUpdateWifiState, mDisableByWifiManager=false, wifiEnabled=true
02-18 13:16:45.961: D/Settings/Provide(201): lookupValue, table system cache.containsKey airplane_mode_radios
02-18 13:16:45.961: D/Settings/Provide(201): lookupValue, table system cache.containsKey airplane_mode_on
02-18 13:16:45.962: D/PowerManagerService(201): acquireWakeLock flags=0x1 tag=*wifi*
02-18 13:16:45.963: D/WifiService(201): setWifiEnabledBlocking, enable=true, persist=false, uid=1000
02-18 13:16:45.963: D/WifiStateTracker(201): restart, mConnectingSupplicant=false
02-18 13:16:45.964: V/AlarmManager(201): set: Alarm{40936e10 type 2 com.google.android.location}
02-18 13:16:45.965: V/AlarmManager(201): Adding alarm Alarm{40936e10 type 2 com.google.android.location} at 0
02-18 13:16:45.965: V/AlarmManager(201): alarms: 5 type: 2
02-18 13:16:45.965: V/AlarmManager(201): 0: Jan 02 10:10:39 am com.google.android.location
02-18 13:16:45.965: V/AlarmManager(201): 1: Jan 02 10:14:56 am com.google.android.gsf
02-18 13:16:45.965: V/AlarmManager(201): 2: Jan 02 10:30:33 am com.google.android.apps.maps
02-18 13:16:45.965: V/AlarmManager(201): 3: Jan 02 11:52:19 am com.google.android.apps.maps
02-18 13:16:45.965: V/AlarmManager(201): 4: Dec 15 06:01:30 am com.google.android.apps.maps
02-18 13:16:45.965: V/AlarmManager(201): Native set alarm :Alarm{40936e10 type 2 com.google.android.location}
02-18 13:16:45.966: E/TelephonyManager(280): getDefaultSim is sim1

我在向服务器发送数据时使用了 AsyncTask,并且我正在服务方法中执行我的 GPS 活动。我不知道为什么 WindowManager 会在应用程序中停止我的 GPS。我看到了一些与 ANR 问题相关的帖子,但在我的 logcat 中没有生成 ANR。我的活动响应正常,我正在后台做所有繁重的工作,但这种情况仍在发生。

我在 logcat WindowManager 中看到 WIN 死亡信号正在发出,因为我的 GPS 正在停止。我无法找到解决此问题的方法。

有人可以告诉我原因并告诉我解决方案吗?

4

1 回答 1

0

好吧,一方面,你不能Service像你在这里做的那样实例化:

LocationListener mlocListener=new MyLocationListener("", "");

Service是一个 Android 组件,Android 组件由 Android 框架实例化。要启动Service您需要调用startService(). 由于您显然想将一些参数传递给您的Service,您可以将它们放入Intent您传递给的startService().

不要为Service. 安卓会这样做。

阅读Android 文档Service中的生命周期

于 2013-02-18T11:28:00.093 回答