【发布时间】:2019-06-07 21:47:35
【问题描述】:
所以我制作了一个应用程序,如果按下手机的电源按钮 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 代码,该代码仅在活动打开时才有效。
【问题讨论】:
标签: java android geolocation gps broadcastreceiver