gpt4 book ai didi

java - 如何在BroadcastReceiver服务中获取纬度和经度值?

转载 作者:行者123 更新时间:2023-12-02 04:43:26 24 4
gpt4 key购买 nike

所以我制作了一个应用程序,如果按手机电源按钮 5 次,该应用程序将运行,例如在后台打开 url。现在的问题是我想提取当时的纬度和经度值。代码是

LockService类

public class LockService extends Service {

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

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
}

屏幕接收器

public class ScreenReceiver extends BroadcastReceiver {

LocationManager locationManager;
static int countPoweroff =0;

public static boolean wasScreenOn = true;
int lol;
@Override
public void onReceive(final Context context, final Intent intent) {

Log.e("LOB","onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here

wasScreenOn = false;
countPoweroff++;
Log.e("LOB",""+countPoweroff);
Log.e("LOB","wasScreenOn"+wasScreenOn);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
if (countPoweroff == 3){
Log.e("LOB","userpresent");
Log.e("LOB","wasScreenOn"+wasScreenOn);
String url = "http://www.stackoverflow.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setData(Uri.parse(url));
context.startActivity(i);

Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
//deprecated in API 26
vibrator.vibrate(500);
}
countPoweroff =0;

}
wasScreenOn = true;

}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){




}
}

在主要 Activity 中运行服务

startService(new Intent(getApplicationContext(), LockService.class));

我在主 Activity 中使用了基本的 Locationmanager 代码,该代码仅在 Activity 打开时才起作用。

最佳答案

您放入 Activity 中的任何代码当然只会在 Activity 运行时才会执行。如果您的位置管理器处于 Activity 状态且 Activity 未运行,则您无法获取位置。当司机关闭引擎并去午休时,您的巴士将不会移动到任何地方。在 Activity 中做任何与用户体验无关的事情都是糟糕的设计。我不知道你的实现细节,因此,很难说更多。你应该在服务中实现位置管理器,并使用 Callable 或 CompletableFuture 将结果发送到 Activity 。

关于java - 如何在BroadcastReceiver服务中获取纬度和经度值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56501568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com