GVKun编程网logo

android – 服务中的LocationManager – 如果1分钟内没有修复需要停止

25

针对android–服务中的LocationManager–如果1分钟内没有修复需要停止这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展AlarmManager和BroadcastReceiv

针对android – 服务中的LocationManager – 如果1分钟内没有修复需要停止这个问题,本篇文章进行了详细的解答,同时本文还将给你拓展AlarmManager和BroadcastReceiver的LocalNotification未在Android O(oreo)中启动、Android Geocoder.getFromLocationName停止使用边界、Android Java-Google LocationRequest和LocationManager的问题、Android Location Manager问题等相关知识,希望可以帮助到你。

本文目录一览:

android – 服务中的LocationManager – 如果1分钟内没有修复需要停止

android – 服务中的LocationManager – 如果1分钟内没有修复需要停止

我有定期服务,每5分钟开始使用一次报警.
Service实现LocationListener以获取GPS修复并将其保存到sqlite数据库中.

我给服务1分钟,以获得最好的解决方案.如果我在此之前得到准确度<20,那就更好了. 一切正常.我也有代码检查GPS是否禁用,所以我退出服务. 我想要做的是:如果1分钟内没有修复 – 我想退出服务.目前,由于大多数逻辑(时间检查等)都在onLocationChanged中 – 我从来没有机会这样做,因为我从来没有获得位置. 是否有定时器或类似的东西我可以使用?我是Java的新手,例子会很好.我这样看:开始时我用回调创建计时器,在这个回调函数中我将清理并关闭.我不确定是否会对onLocationChanged运行产生任何影响?

一旦我进入onLocationChanged,我可以立即禁用计时器吗?

解决方法:

使用android.os.Handler:

Handler timeoutHandler = new Handler();
timeoutHandler.postDelayed(new Runnable() {
    public void run() {
        stopSelf();
    }
}, 60 * 1000);

AlarmManager和BroadcastReceiver的LocalNotification未在Android O(oreo)中启动

AlarmManager和BroadcastReceiver的LocalNotification未在Android O(oreo)中启动

在SDK 26之前,我已经在机器人上运行了本地通知

但是在Android O中我收到了以下警告,广播接收器没有被解雇.

W/broadcastQueue: Background execution not allowed: receiving Intent { act=package.name.action.LOCAL_NOTIFICATION cat=[com.category.localnotification] flg=0x14 (has extras) } to package.name/com.category.localnotifications.localnotificationReceiver

从我所看到的广播接收器在Android O中受到更多限制,但如果是这样,即使主要活动没有运行,我应该如何安排广播?

我应该使用服务而不是接收器吗?

这是AlarmManager启动代码:

public void Schedule(String aID, String aTitle, String aBody, int aNotificationCode, long aEpochTime)
{
    Bundle lExtras = new Bundle();
    lExtras.putInt("icon", f.getDefaultIcon());
    lExtras.putString("title", aTitle);
    lExtras.putString("message", aBody);
    lExtras.putString("id", aID);
    lExtras.putInt("requestcode", aNotificationCode);

    Intent lIntent = 
      new Intent(localnotificationScheduler.ACTION_NAME)
      .addCategory(NotificationsUtils.LocalNotifCategory)
      .putExtras(lExtras);

    PendingIntent lPendIntent = PendingIntent.getbroadcast(f.getApplicationContext(), aNotificationCode,
                                                           lIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager lAlarmMgr = (AlarmManager) f.getSystemService(Context.ALARM_SERVICE);
    lAlarmMgr.set(AlarmManager.RTC, 1000, lPendIntent);
}

这是接收者代码:

public class localnotificationReceiver extends broadcastReceiver {

public static native void   nativeReceivelocalnotification (String aID, String aTitle, String aMessage, boolean aOnForeground );

/** This method receives the alarms set by localnotificationScheduler,
*   notifies the CAndroidNotifications c++ class, and (if needed) ships a notification banner 
*/
@Override
public void onReceive(Context aContext, Intent aIntent)
{
    Toast.makeText(context, text, duration).show();
}

}

Android清单:

<receiver android:name="com.category.localnotifications.localnotificationReceiver">
        <intent-filter>
            <action android:name="${applicationId}.action.LOCAL_NOTIFICATION" />
            <category android:name="com.category.localnotification" />
        </intent-filter>
    </receiver>

解决方法:

Android O是迄今为止最新的.因此,我尝试消化并提供尽可能准确的信息.

从https://developer.android.com/about/versions/oreo/background.html#broadcasts起

>针对Android 8.0或更高版本的应用无法再在其清单中为隐式广播注册广播接收器.

>应用程序可以在运行时使用Context.registerReceiver()为任何广播注册接收器,无论是隐式还是显式.

>应用可以继续在其清单中注册显式广播.

此外,在https://developer.android.com/training/scheduling/alarms.html中,示例使用显式广播,并未提及有关Android O的任何特殊内容.

我建议你尝试一下如下的明确广播吗?

public static void startAlarmbroadcastReceiver(Context context, long delay) {
    Intent _intent = new Intent(context, AlarmbroadcastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getbroadcast(context, 0, _intent, 0);
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    // Remove any prevIoUs pending intent.
    alarmManager.cancel(pendingIntent);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pendingIntent);        
}

AlarmbroadcastReceiver

public class AlarmbroadcastReceiver extends broadcastReceiver {


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

}

在AndroidManifest中,只需将类定义为

<receiver android:name="org.yccheok.AlarmbroadcastReceiver" >
</receiver>

Android Geocoder.getFromLocationName停止使用边界

Android Geocoder.getFromLocationName停止使用边界

我使用Geocoder.getFromLocationName来验证用户插入的地址.我检查返回的ArrayList,如果它是exaclty一个结果一切都很好.我也使用边界,所以我只得到某个区域内的结果( Geocoder).在上周某个时候突然停止工作之前,这种情况很好.返回的结果现在总是相同的,并且始终与我作为地址名称传递的字符串无关…

当我删除边界时,它工作正常.有没有人遇到过类似的问题?谷歌是否改变了该功能的实施方式?

解决方法

我们最近也开始体验这一点.我发现有人在两天前在AOSP问题跟踪器上提交了这个错误:

https://code.google.com/p/android/issues/detail?id=75575

我还创建了一个小样本开源项目来演示这个问题:

https://github.com/barbeau/GeocoderDemo

正如您所说,如果使用边界框,无论搜索项是什么,它似乎总是返回相同的通用结果:

如果没有边界框,它会正确返回特定于搜索项的结果,尽管这些结果是全局的,没有进一步过滤也没有多大用处.

这里的主要问题是历史上谷歌将Android Geocoder issues on the AOSP issue tracker标记为“错误的论坛”,所以我对那里的支持并不过分乐观.

我发布到Android开发者论坛:

https://groups.google.com/forum/#!topic/android-developers/KuZDVRXyTc0

…和谷歌希望在那里提出问题:

https://plus.google.com/+SeanBarbeau/posts/Mm5YwzeUoZV

编辑

截至2014年10月,似乎是this issue is resolved.

Android Java-Google LocationRequest和LocationManager的问题

Android Java-Google LocationRequest和LocationManager的问题

如何解决Android Java-Google LocationRequest和LocationManager的问题?

(编辑:修复了LocationManager更新,,但是使用Google Api对话框启用GPS后,我仍然始终在onActivityResult中得到RESULT_Failed。

任何人都可以告诉我为什么如果我使用Google Api对话框启用GPS以及手动启用GPS,LocationManager位置更新为什么会停止工作?谢谢!

还有为什么我在使用Google Api对话框启用GPS(并正确启用GPS)后总是在onActivityReturn中得到RESULT_Failed?

我需要一些有关此问题的信息和帮助。

我做了一个utils类,以使用Google Dialog启用gps高精度:

<!doctype html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/layout.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Grafiek</title>
    <style>
        .red{
          background-color:red;
         }
         .blue{
          background-color:blue;
         }        
         .green{
          background-color:green;
         }

    </style>
</head>
<body>
<h1>Server Stats</h1>
<div id="maindiv">
    <div id="server1">
        <h3>(servername1)</h3>
        <div>
            Status:
        </div>

        <br>
        <div>
            Last Checked:
        </div>
        <div>
            Last Online:
        </div>
        <div>
            <button onclick="toggleStatus(''server1'',''red'')">yes</button>
        </div>
    </div>

    <div id="server2">
        <h3>(servername2)</h3>
        <div>
            Status:
        </div>
        <br>
        <div>
            Last Checked:
        </div>
        <div>
            Last Online:
        </div>
        <div>
            <button onclick="toggleStatus(''server2'',''green'')">yes</button>
        </div>
    </div>

    <div id="server3">
        <h3>(servername3)</h3>
        <div>
            Status:
        </div>
        <br>
        <div>
            Last Checked:
        </div>
        <div>
            Last Online:
        </div>
        <div>
            <button onclick="toggleStatus(''server3'',''blue'')">yes</button>
        </div>
    </div>
</div>

</body>
</html>

我还尝试将此类更改为:

public class EnableLocationCallback implements OnCompleteListener<LocationSettingsResponse> {

    // Millis Interval
    private static final long MILLIS_FASTEST_INTERVAL = 1000L;
    private static final long MILLIS_INTERVAL = MILLIS_FASTEST_INTERVAL * 0xA;

    private Activity mActivity;
    private int mRequestCode;

    public static void requestEnableLocation(Activity activity,int requestCode){
        new EnableLocationCallback(activity,requestCode).requestEnableLocation();
    }

    private EnableLocationCallback(Activity activity,int requestCode){
        mActivity = activity;
        mRequestCode = requestCode;
    }

    /** Override OnCompleteListener<LocationSettingsResponse> Methods **/
    @Override
    public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
        try {
            task.getResult(ApiException.class);
        } catch (ApiException ex){
            switch (ex.getStatusCode()){
                case LocationSettingsstatusCodes.RESOLUTION_required:
                    try {
                        ((ResolvableApiException) ex).startResolutionForResult(mActivity,mRequestCode);
                    } catch (IntentSender.SendIntentException e) {
                        openGpsEnabledSettings();
                    }
                    break;
                case LocationSettingsstatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    openGpsEnabledSettings();
                    break;
            }
        }
    }

    /** Private Methods **/
    private void requestEnableLocation(){
        getSettingsClient(mActivity)
                .checkLocationSettings(getLocationSettingsRequest())
                .addOnCompleteListener(this);
    }

    private LocationRequest getLocationRequest(){
        return LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(MILLIS_INTERVAL)
                .setFastestInterval(MILLIS_FASTEST_INTERVAL);
    }

    private LocationSettingsRequest getLocationSettingsRequest(){
        return new LocationSettingsRequest.Builder()
                .addLocationRequest(getLocationRequest())
                .setAlwaysShow(true)
                .build();
    }

    private void openGpsEnabledSettings(){
        mActivity.startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),mRequestCode);
    }

}

在两种情况下,我都启用了GPS,但GPS启用了“高精度”启用,但是... 在我的活动“ onActivityResult”上,我总是得到resultCode == -0x1(如此失败)。

我还看到,在开始使用此代码后,我正在使用此代码进行位置更新的所有零件(单个更新或多个):

public class EnableLocationCallback implements
        Googleapiclient.ConnectionCallbacks,Googleapiclient.OnConnectionFailedListener {

    // Millis Interval
    private static final long MILLIS_FASTEST_INTERVAL = Constants.MILLIS_ONE_SECOND * 0x5;
    private static final long MILLIS_INTERVAL = Constants.TIMEOUT_GET_POSITION;

    private Googleapiclient mGoogleapiclient;
    private Activity mActivity;
    private int mRequestCode;

    public static void requestEnableLocation(Activity activity,int requestCode){
        EnableLocationCallback instance = new EnableLocationCallback(activity,requestCode);
        instance.initGoogleapiclient();
        instance.initLocationSettingResultCallback();
    }

    private EnableLocationCallback(Activity activity,int requestCode){
        mActivity = activity;
        mRequestCode = requestCode;
    }

    /** Override Googleapiclient.ConnectionCallbacks Methods **/
    @Override
    public void onConnected(@Nullable Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    /** Override Googleapiclient.OnConnectionFailedListener Methods **/
    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    /** Private Methods **/
    private void initGoogleapiclient(){
        mGoogleapiclient = new Googleapiclient.Builder(mActivity)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .build();
        mGoogleapiclient.connect();
    }

    private void initLocationSettingResultCallback(){
        LocationServices.SettingsApi.checkLocationSettings(mGoogleapiclient,getLocationSettingsRequest()).setResultCallback(
                result -> {
                    final Status status = result.getStatus();
                    final LocationSettingsstates state = result.getLocationSettingsstates();
                    switch (status.getStatusCode()) {
                        case LocationSettingsstatusCodes.SUCCESS:
                            break;
                        case LocationSettingsstatusCodes.RESOLUTION_required:
                            try {
                                status.startResolutionForResult(mActivity,mRequestCode);
                            } catch (IntentSender.SendIntentException e) {
                                openGpsEnabledSettings();
                            }
                            break;
                        case LocationSettingsstatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            openGpsEnabledSettings();
                            break;
                    }
                }
        );
    }

    private void requestEnableLocation(){
        getSettingsClient(mActivity)
                .checkLocationSettings(getLocationSettingsRequest());
    }

    private LocationRequest getLocationRequest(){
        return LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(MILLIS_INTERVAL)
                .setFastestInterval(MILLIS_FASTEST_INTERVAL);
    }

    private LocationSettingsRequest getLocationSettingsRequest(){
        return new LocationSettingsRequest.Builder()
                .addLocationRequest(getLocationRequest())
                .setAlwaysShow(true)
                .build();
    }

    private void openGpsEnabledSettings(){
        mActivity.startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS),mRequestCode);
    }

}

所有这些部分停止工作。 我使用gps更新对话框无法启用GPS,如果我手动启用它也将无法使用!

您能解释一下并告诉我如何解决吗?

我还将希望看到有关“ Google SettingsClient”,“ GoogleApi ”的漂亮文档和用法示例。 我搜索了但没有找到任何好的文档。

例如... google页面仅告诉您一些信息,我没有告诉您扩展类后应该传递给超级构造函数的东西,以及许多其他事情:/

非常感谢您, 祝您编码愉快,并祝您愉快:D

#EDIT: 我通过使用“ FusedLocationManager”和正确的LocationListener进行位置更新来修复了LocationManager更新。 但是在使用对话框正确启用GPS后,我仍然总是会得到RESULT_FAILED。 我现在的课程是:

mLocationManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,mUserPositionListener,null);

我从这里使用@Janishar Ali的答案来改善我的课程: Janishar Ali Answer Link

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

Android Location Manager问题

Android Location Manager问题

从以下代码中,我可以获得当前位置.

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltituderequired(false);
criteria.setbearingrequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
GlobalLocation = locationManager.getLastKNownLocation(provider);
locationManager.requestLocationUpdates(provider, 2000, 10, locationListener);

获取位置后,我会在Google地图上绘制位置叠加图,然后从位置提供者确定位置叠加图的颜色.这是下面的代码,它们根据位置提供程序决定颜色.

    Serviceprovider = GlobalLocation.getProvider();
    if(Serviceprovider.equals("network"))
    {
         positionOverlay.iColor = 2;
    }//End if
    else if(Serviceprovider.equals("gps"))
    {
         positionOverlay.iColor = 1;
    }//End else if

室外一切正常,但是问题是,如果我在GPS不稳定的室内使用我的应用程序.提供者不使用网络.仅当GPS关闭时,网络提供商才会执行.如果GPS不稳定,您能指导我如何确定网络的跳跃.

解决方法:

这已经回答过了.您需要添加两个不同的位置侦听器.一种用于GPS,另一种用于网络位置.基于蜂窝网络的位置侦听器.

GPS只能在户外工作,但是蜂窝网络可以在有信号的任何地方工作,但是它不像GPS那样精确.

locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            locationListener = new MyLocationListener();
            locationListener2 = new MyLocationListener();               
            locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
            locationManager.requestLocationUpdates(locationManager.NETWORK_PROVIDER, 0, 0, locationListener2);

关于android – 服务中的LocationManager – 如果1分钟内没有修复需要停止的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于AlarmManager和BroadcastReceiver的LocalNotification未在Android O(oreo)中启动、Android Geocoder.getFromLocationName停止使用边界、Android Java-Google LocationRequest和LocationManager的问题、Android Location Manager问题等相关知识的信息别忘了在本站进行查找喔。

本文标签: