添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

设备锁定时安卓停止前台服务

0 人关注

在我的安卓12设备上,ActivityManager在设备锁定时停止了我的前台服务。该服务的目的是获取GPS信息,进行各种跟踪和特殊的地理围栏(常规的GeoFencing功能无法处理)。我需要它一直运行。

我的活动是这样的。

            Context context = getApplicationContext();
            Intent intent = new Intent(context, NavService.class); // Build the intent for the Navigation service
            if (!isNavServiceRunning())
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                    Log.v(LOG_TAG, "startForegroundService(NavService)");
                    context.startForegroundService(intent);
                } else
                    context.startService(intent);

而那个Log.v条目确实出现了。

Then my Service does:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "Foreground Service Channel", NotificationManager.IMPORTANCE_DEFAULT);
        NotificationManager manager = getSystemService(NotificationManager.class);
        manager.createNotificationChannel(serviceChannel);
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);
        Notification notification = new Notification.Builder(this, CHANNEL_ID)
                .setContentTitle(getText(R.string.nav_service_title))
                .setContentText(getText(R.string.nav_service_message))
                .setSmallIcon(R.drawable.logo_no_text_plain_24x24)
                .setContentIntent(pendingIntent)
                .setTicker(getText(R.string.nav_service_ticker_text))
                .setAutoCancel(false)
                .setOngoing(true)
                .build();
        Log.v(LOG_TAG, "startForeground");
        startForeground(SERVICE_ID, notification);
    // Now start the GPS updates. Note: Permissions were requested in main activity.
    startGpsUpdates(); // My code to kick off updates.
    return START_STICKY; 

而那个Log.v条目显示出来了。

我应该在这里加入我的清单内容。

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<service android:name=".NavService" android:foregroundServiceType="location" />