java - 如何在 BroadcastReceiver 服务中获取经纬度值?
问题描述
所以我制作了一个应用程序,如果手机的电源按钮按下 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)){
}
}
在主要活动中运行服务
startService(new Intent(getApplicationContext(), LockService.class));
我在主要活动中使用了基本的 Locationmanager 代码,该代码仅在活动打开时才有效。
解决方案
您放入活动中的任何代码当然只会在活动运行时执行。如果您的位置管理器处于活动状态且活动未运行,则您无法获取位置信息。当司机关闭引擎并去午休时,您的公共汽车将不会移动到任何地方。在活动中做任何与 Ux 无关的事情都是糟糕的设计。我不知道您的实现细节,因此很难说更多。您应该在服务中实现位置管理器并使用 Callable 或 CompletableFuture 将结果发送到活动。
推荐阅读
- ios - 如何检测何时选择了 TextView 但在它成为第一响应者之前?
- c# - 代码中没有错误,但尝试更新时表中没有发生变化
- javascript - 当 useState 更新时,map 循环在 useState 对象内部的数组中不起作用。反应js
- python - 我收到错误:django.db.utils.IntegrityError: NOT NULL constraint failed: store_customer.email
- c++ - 在命令行上生成损坏的名称
- python - 如何调用熊猫数据框应用函数返回两个变量
- javascript - SVG 文件未加载到导航栏 - 不确定原因是什么。(HTML、CSS、BOOTSTRAP、JS、SVG)
- jmeter - 在 JMeter 中随机运行样本
- c# - 尝试在winforms中制作笔记应用程序
- python - 如何使用python按类型终止进程win32mutex