Android,熄屏时获取位置

2023-12-24

我使用带有 fused api 的已启动服务,并直接在其上实现位置侦听器。 即使屏幕锁定,位置也会持续更新,但如果屏幕关闭,位置就会停止。

那么,有没有什么方法可以确保屏幕关闭时位置保持更新呢?

我读了很多其他问题,但我真的不知道我错过了什么。

public class CLocationService extends Service implements GoogleApiClient.ConnectionCallbacks, LocationListener,
    GoogleApiClient.OnConnectionFailedListener {

private GoogleApiClient mGoogleApiClient;
private PowerManager.WakeLock mWakeLock;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;

private Boolean servicesAvailable = false;

private boolean isStarted;

public static final int LOCATION_SERVICE_NOTIFICATION_ID = 4567654;

private void showNotification() {

    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    Notification notification = new Notification.Builder(this)
            .setContentTitle(getText(R.string.app_name))
            .setContentText("")
            .setSmallIcon(R.mipmap.ic_notification)
            .setContentIntent(pendingIntent)
            .setTicker("")
            .build();

    startForeground(LOCATION_SERVICE_NOTIFICATION_ID, notification);
}

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

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

    /*
     * Create a new location client, using the enclosing class to
     * handle callbacks.
     */
    setUpLocationClientIfNeeded();

    startLocationServices();
}

/*
 * Create a new location client, using the enclosing class to
 * handle callbacks.
 */
protected synchronized void buildGoogleApiClient() {
    this.mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

private boolean servicesConnected() {

    // Check that Google Play services is available
    int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    // If Google Play services is available
    if (ConnectionResult.SUCCESS == resultCode) {

        return true;
    } else {

        return false;
    }
}

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

    PowerManager mgr = (PowerManager) getSystemService(Context.POWER_SERVICE);

    /*
    WakeLock is reference counted so we don't want to create multiple WakeLocks. So do a check before initializing and acquiring.
    This will fix the "java.lang.Exception: WakeLock finalized while still held: MyWakeLock" error that you may find.
    */
    if (this.mWakeLock == null) { //**Added this
        this.mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
    }

    if (!this.mWakeLock.isHeld()) { //**Added this
        this.mWakeLock.acquire();
    }

    if (!servicesAvailable || mGoogleApiClient.isConnected() || mInProgress)
        return START_STICKY;

    setUpLocationClientIfNeeded();
    if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting() && !mInProgress) {
        mInProgress = true;
        mGoogleApiClient.connect();
    }

    return START_STICKY;
}

private void setUpLocationClientIfNeeded() {
    if (mGoogleApiClient == null)
        buildGoogleApiClient();
}

@Override
public void onDestroy() {

    stopLocationServices();

    super.onDestroy();
}

private void startLocationServices() {

    mInProgress = false;
    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create();
    // Use high accuracy
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    // Set the update interval to 5 seconds
    mLocationRequest.setInterval(5000);
    // Set the fastest update interval to 1 second
    mLocationRequest.setFastestInterval(1000);
    mLocationRequest.setSmallestDisplacement(0);

    servicesAvailable = servicesConnected();
}

private void stopLocationServices() {

    // Turn off the request flag
    this.mInProgress = false;

    if (this.servicesAvailable && this.mGoogleApiClient != null) {
        this.mGoogleApiClient.unregisterConnectionCallbacks(this);
        this.mGoogleApiClient.unregisterConnectionFailedListener(this);
        this.mGoogleApiClient.disconnect();
        // Destroy the current location client
        this.mGoogleApiClient = null;
    }
    // Display the connection status
    // Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ":
    // Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();

    if (this.mWakeLock != null) {
        this.mWakeLock.release();
        this.mWakeLock = null;
    }
}

private void cancelNotification() {
    NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    nMgr.cancel(LOCATION_SERVICE_NOTIFICATION_ID);
}

@Override
public void onLocationChanged(Location location) {
    // log the new location
}

@Override
public void onConnected(@Nullable Bundle bundle) {

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(this.mGoogleApiClient,
            mLocationRequest, this); // This is the changed line.
}

@Override
public void onConnectionSuspended(int i) {

    // Turn off the request flag
    mInProgress = false;
    // Destroy the current location client
    mGoogleApiClient = null;
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    mInProgress = false;

    /*
     * Google Play services can resolve some errors it detects.
     * If the error has a resolution, try sending an Intent to
     * start a Google Play services activity that can resolve
     * error.
     */
    if (connectionResult.hasResolution()) {

        // If no resolution is available, display an error dialog
    } else {

    }
}

}


我不确定我是否得到了你的答案,但既然你已经 9 天了,什么都没有,我会给出一些建议。

我的应用程序正在做你想做的事。我使用长时间运行的启动服务来保持位置更新,即使手机关闭时也是如此。

最有可能导致你的代码和我的代码之间不同行为的差异是从onStartCommand()。你回来了START_STICKY。这是类似这样的建议回报:

此模式对于将显式启动的事物有意义,并且 停止运行任意时间段,例如服务 进行背景音乐播放。

但是,我正在发送信息Intent我需要重新投递,所以我要回来START_REDELIVER_INTENT。尝试此操作(即使您不需要重新传送任何数据)以查看它是否可以解决您的问题。

另外,我不需要WakeLock在我的实施中。也许你的实现需要这个。你试过没有它吗?

编辑:最后,您使用什么样的设备?link https://stackoverflow.com/a/41772487/7292819

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android,熄屏时获取位置 的相关文章

  • 这个方法比 Math.random() 更快吗?

    我是一名初学者 目前已经开始开发一款使用粒子群优化算法的 Android 游戏 我现在正在尝试稍微优化我的代码 并且 for 循环中有相当多的 Math random 几乎一直在运行 所以我正在考虑一种方法来绕过并跳过所有 Math ran
  • Gradle 构建错误:内存不足

    当我使用 gradle 构建时 它失败并显示以下信息 OpenJDK 64 Bit Server VM warning INFO os commit memory 0x0000000788800000 89128960 0 failed e
  • 使用一个 apk 安装两个应用程序

    我有 2 个应用程序 1 内容提供者 2 使用此 ContentProvider 的应用程序 我需要使用单个 apk 文件安装这 2 个应用程序 我想在 Eclipse 中同时推送这两个应用程序 如果我将另一个项目添加到一个应用程序的构建路
  • 从历史堆栈中删除活动

    我的应用程序在用户第一次运行应用程序时显示注册活动 如下所示 活动启动画面 欢迎来到游戏 注册帐户 ActivitySplashScreenSignUp 很好 填写此信息 ActivityGameMain 游戏主屏幕 因此 当用户单击每个屏
  • 需要使用手机后退按钮返回 Web 视图的帮助

    这是我的代码 package com testappmobile import android app Activity import android os Bundle import android view KeyEvent impor
  • 如何在android中压缩和解压png图像

    您好 在我的应用程序中 当我单击 zip 按钮时 我需要压缩图像文件 当我单击解压缩按钮时 我需要解压缩文件 我尝试使用下面的代码来压缩图像 但我的问题是当我单击 zip 按钮时 正在创建 zip 文件 但之后在使用 winzip 软件的系
  • Android PhoneGap 插件,UI 选项卡栏,调整 WebView 大小

    我正在创建一个美味的 PhoneGap 插件 希望一旦它能被打开 准备好了 插件基本完成了 我只需要一个漂亮的用户界面 相互作用 简而言之 我想创建一个 本机 android 工具栏组件 如果您实现 PhoneGap UIControls
  • 如何向开发人员发送崩溃报告?

    我开发 Android 应用程序 但在某些情况下我的应用程序force close 如果出现以下情况 我如何向开发人员发送包含详细信息的电子邮件force close随时发生 The ACRA https github com ACRA a
  • 在 Android Lollipop 中从 Uri 中裁剪照片后总是返回 Null?

    我尝试在拍照或挑选照片后从 Uri 中裁剪图像 我的代码是这样的 public static void cropImage Uri uri Activity activity int action code Intent intent ne
  • 使用 Android Firebase 堆栈推送通知

    我开发了使用 Firebase 接收推送通知的 Android 应用程序 我的代码基于 Firebase Google 官方文档 https firebase google com docs cloud messaging android
  • 如何在 NumberPicker 中一次显示 3 个以上的值

    我正在创建一个数字选择器 如下图所示 但如果有可用空间 我想显示 3 个以上的值 该选择器有 20 个项目 并且有足够的空间来显示 3 个以上的值 这可以使用 NumberPicker 来完成吗 只需以编程方式设置numberPicker
  • 适用于 Android 的 Google 云端硬盘\文档 API

    我在几个小时内将 Dropbox 与我的应用程序集成 因为 SDK 描述清晰并且有很好的使用示例 Google Drive 似乎只有一个 一刀切 的 Gdata SDK 它非常重 有很多依赖项 它使我的应用程序的大小增加了三倍 而且不是很直
  • android中listview显示数据库中的数据

    我是安卓新手 我想知道如何在列表视图中显示数据库中的数据 它不会向数据库添加数据 我只是显示我们存储在数据库中的任何内容 请帮助我实现这一目标 提前致谢 使用这些课程可能会对您有所帮助 用于数据库创建 package com example
  • 未解决的包含:“cocos2d.h” - Cocos2dx

    当我在 Eclipse 中导入 cocos2dx android 项目时 我的头文件上收到此警告 Unresolved inclusion cocos2d h 为什么是这样 它实际上困扰着我 该项目可以正确编译并运行 但我希望这种情况消失
  • 剪切评级栏中的图像

    我制作了自己的评级栏 花朵图像有 4 种尺寸 xdpi hdpi 等 从 24px24px 到 64x64px
  • Android 地理围栏无法正常工作(未调用 IntentService)

    这是我的代码 安卓清单
  • 如何关闭 EditText 中的建议?

    如何在 Android 中关闭 EditText 中的建议 android inputType textNoSuggestions 根据this http comments gmane org gmane comp handhelds an
  • 在 Android 手机中通过耳机插孔发送数据

    我目前正在处理一个新项目 我必须通过具有特定电压的耳机插孔发送数据 然后我可以在该电压上工作 所以这里我需要根据我的数据来编程具体电压 我是否可以在android中访问耳机的输出电压 然后创建一个应用程序来控制该电压 这是一篇讨论此问题的
  • 我应该如何在 Android 上使用 Retrofit 处理“无互联网连接”

    我想处理没有互联网连接的情况 通常我会运行 ConnectivityManager cm ConnectivityManager context getSystemService Context CONNECTIVITY SERVICE N
  • 将焦距(以毫米为单位)转换为像素 - Android

    在 Android 中 我当前正在访问camera s焦距通过使用getFocalLength in Camera1 Camera2不是一个选择 我正在尝试完全填充当前的计算 focal length pix focal length m

随机推荐