打开位置弹出窗口或应用程序被杀死时 GPS 图标消失

Posted

技术标签:

【中文标题】打开位置弹出窗口或应用程序被杀死时 GPS 图标消失【英文标题】:GPS icon disappear when open location popup or the app is killed 【发布时间】:2017-05-21 13:06:27 【问题描述】:

我正在开发一个应用程序,它应该每 10 分钟向服务器发送一次 gps 数据。问题是当我在 GPS 开启时终止应用程序时,GPS 图标从状态栏中消失(而 GPS 仍然开启)并且不再发送数据。如果我对谷歌地图应用程序执行相同操作,则图标不会消失。 有人可以解释一下为什么会这样吗? 这是我使用的代码

报警管理器

/**
 * ALARM_MANAGER_GPS_TIME_INTERVAL = 10 min
 */
PendingIntent mPendingIntent = PendingIntent
            .getService(
                    context,
                    PENDING_INTENT_REQUEST_CODE_FOR_GPS,
                    new Intent(context, GpsDataService.class),
                    PendingIntent.FLAG_IMMUTABLE);
    AlarmManager mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    mAlarmManager.setInexactRepeating(
            AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime(),
            ALARM_MANAGER_GPS_TIME_INTERVAL,
            mPendingIntent);

服务

public class GpsDataService extends Service implements
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener,
    LocationListener 

/**
 * Provides the entry point to Google Play services.
 */
protected GoogleApiClient mGoogleApiClient;

/**
 * Stores parameters for requests to the FusedLocationProviderApi.
 */
protected LocationRequest mLocationRequest;

/**
 * Represents a geographical location.
 */
protected Location mCurrentLocation;

private String mPayLoad;
private GpsPojoBuilder mGpsPojoBuilder;

@Override
public void onCreate() 
    super.onCreate();


@Override
public int onStartCommand(Intent intent, int flags, int startId) 


    if(mGoogleApiClient == null)
        buildGoogleApiClient();

    mGoogleApiClient.connect();

    if (mGoogleApiClient.isConnected())
        startLocationUpdates();

    return Service.START_NOT_STICKY;

protected synchronized void buildGoogleApiClient() 

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    createLocationRequest();

/**
 * UPDATE_INTERVAL_IN_MILLISECONDS = 4 sec
 * FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 2 sec
 */
protected void createLocationRequest() 
    mLocationRequest = new LocationRequest();
    mLocationRequest
            .setInterval(UPDATE_INTERVAL_IN_MILLISECONDS)
            .setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS)
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);


@Override
public void onConnected(@Nullable Bundle bundle) 
    startLocationUpdates();

@Override
public void onConnectionSuspended(int i) 
    // The connection to Google Play services was lost for some reason. Call connect() to
    // attempt to re-establish the connection.
    mGoogleApiClient.connect();

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 

/**
 * Requests location updates from the FusedLocationApi.
 */
protected void startLocationUpdates() 
    checkForPermission();

private void checkForPermission() 

    Location location;

    if (Build.VERSION.SDK_INT >= 23) 

        if (ContextCompat.checkSelfPermission(getApplicationContext(),
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            //permission denied
         else 
            location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            if (location != null)
                handleLocation(location);
            else
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        
    else 
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if(location != null)
            handleLocation(location);
        else
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    

@Override
public void onLocationChanged(Location location) 
    handleLocation(location);

private void handleLocation(Location location)

    mCurrentLocation = location;

    Toast.makeText(this, "location foound: " + location.toString(), Toast.LENGTH_SHORT).show();

    Thread thread = new Thread() 
        @Override
        public void run() 
            try 
                mGpsPojoBuilder = new GpsPojoBuilder(getApplicationContext());
                mPayLoad = mGpsPojoBuilder
                        .getCheckInJson(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                sendJSON(mPayLoad, CHECKINS_URL);
             catch (GooglePlayServicesRepairableException e) 
                e.printStackTrace();
             catch (GooglePlayServicesNotAvailableException e) 
                e.printStackTrace();
             catch (IOException e) 
                e.printStackTrace();
             finally 
                if(mGoogleApiClient.isConnected()) 
                    stopLocationUpdates();
                    mGoogleApiClient.disconnect();
                
            
        
    ;
    thread.start();

public void sendJSON(String payLoadData, String url_suffix) 
    HttpConnectionCreator mHttpConncectionClass = new HttpConnectionCreator(payLoadData, url_suffix);
    mHttpConncectionClass.connect();

/**
 * Removes location updates from the FusedLocationApi.
 */
protected void stopLocationUpdates() 
               LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);


@Nullable
@Override
public IBinder onBind(Intent intent) 
    return null;


@Override
public void onDestroy() 

    if (mGoogleApiClient.isConnected()) 
        stopLocationUpdates();
        mGoogleApiClient.disconnect();
    
    super.onDestroy();
  

【问题讨论】:

【参考方案1】:

根据android.developer,如果你想让你的服务保持活跃,你需要使用START_STICKY。

int START_STICKY 从 onStartCommand(Intent, int, int) 返回的常量:如果该服务的进程在启动时被杀死(从 onStartCommand(Intent, int, int) 返回后),则将其保持在已启动状态但不保留此状态传递的意图。稍后系统会尝试重新创建服务。

在以下函数中:

@Override
public int onStartCommand(Intent intent, int flags, int startId) 


if(mGoogleApiClient == null)
    buildGoogleApiClient();

mGoogleApiClient.connect();

if (mGoogleApiClient.isConnected())
    startLocationUpdates();

return Service.START_NOT_STICKY;

改成这样:

@Override
public int onStartCommand(Intent intent, int flags, int startId) 


if(mGoogleApiClient == null)
    buildGoogleApiClient();

mGoogleApiClient.connect();

if (mGoogleApiClient.isConnected())
    startLocationUpdates();

return Service.START_STICKY;

【讨论】:

感谢您的回答。但实际上我的目标不是让服务保持活力。我只想每十分钟创建一次服务,将数据发送到服务器,然后停止服务。为什么我需要保持服务活着?我是不是误会了什么?

以上是关于打开位置弹出窗口或应用程序被杀死时 GPS 图标消失的主要内容,如果未能解决你的问题,请参考以下文章

电脑打开应用没图标怎么办

面临禁用时日历图标在另一个日历弹出窗口上重叠的问题

Android GPS 和定位服务帮助

Gps 位置图标未关闭

在应用程序启动时打开GPS

Jquery 移动弹出窗口在页面调整大小或滚动时的错误位置重新打开