- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在开发一个计步器应用程序,我可以在其中计算步行的步数并在午夜将其更新到服务器。我有一个持续运行的服务来完成这一切。
这是我的服务:
public class StepCounterService extends Service implements SensorEventListener, StepListener, WebServiceInterface, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int SERVICE_ID = 27;
private static final int SEND_SESSION_REQUEST_CODE = 1;
private static final int SEND_ACTIVITY_REQUEST_CODE = 2;
private static final int MAIN_NOTIFICATION_ID = 3;
private static final int SECONDARY_NOTIFICATION_ID = 4;
private LocalBroadcastManager broadcaster;
static final public String STEP_INCREMENT = "com.app.STEP_INCREMENTED";
static final public String SESSION_COMPLETE = "com.app.SESSION_COMPLETE";
static final public String ACTIVITY_COMPLETE = "com.app.ACTIVITY_COMPLETE";
static final public String STEP_INCREMENT_KEY = "step_count";
Session session;
private StepDetector stepDetector;
private SensorManager sensorManager;
private Sensor sensor;
private int numberOfSteps = 0;
private GoogleApiClient googleApiClient;
private LocationRequest mLocationRequest;
double currentLatitude;
double currentLongitude;
ArrayList<String> arrayListLocations;
private AlarmManager sendActivityAlarmManager;
private PendingIntent activityAlarmIntent;
private NotificationManager notificationManager;
RemoteViews contentView;
PowerManager.WakeLock wl;
private String TAG = "Wake Lock Tag";
private int SET_LAST_LOCATION_REQUEST_CODE = 5;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
return START_STICKY;
}
@Override
public void onTaskRemoved(Intent rootIntent) {
// TODO Auto-generated method stub
System.out.println("---- In onTaskRemoved Function");
restartKilledService();
}
@Override
public void onDestroy() {
System.out.println("---- In onDestroy Function");
if (wl != null) {
wl.release();
}
super.onDestroy();
restartKilledService();
}
void restartKilledService() {
System.out.println("---- In restartKilledService Function");
Intent restartService = new Intent(getApplicationContext(), StepCounterService.class);
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(getApplicationContext(), StepCounterService.SERVICE_ID, restartService, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime() + 100, restartServicePI);
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
super.onCreate();
session = new Session(this);
buildGoogleApiClient();
broadcaster = LocalBroadcastManager.getInstance(this);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
stepDetector = new StepDetector();
stepDetector.registerListener(StepCounterService.this);
Context ctx = getApplicationContext();
Calendar cal = Calendar.getInstance();
AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
long interval = 1000 * 60 * 5; // 5 minutes in milliseconds
Intent serviceIntent = new Intent(ctx, StepCounterService.class);
PendingIntent servicePendingIntent = PendingIntent.getService(ctx, StepCounterService.SERVICE_ID, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), interval, servicePendingIntent);
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_FASTEST);
notificationManager = (NotificationManager) getSystemService(Activity.NOTIFICATION_SERVICE);
contentView = new RemoteViews(getPackageName(), R.layout.notification_layout);
contentView.setImageViewResource(R.id.image, R.drawable.notif_icon);
if (session.getUser() != null && !(session.getUser().getName().equals("")))
updateMainNotification(session.getTodaySteps() + "");
startAlarm();
}
protected synchronized void buildGoogleApiClient() {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
googleApiClient.connect();
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000);
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
stepDetector.updateAccel(event.timestamp, event.values[0], event.values[1], event.values[2]);
}
}
@Override
public void step(long timeNs) {
numberOfSteps = session.getTodaySteps();
numberOfSteps++;
sendStepIncrementBroadcast(numberOfSteps);
session.setTodaySteps(numberOfSteps);
if (session.getUser() != null && !(session.getUser().getName().equals("")))
updateMainNotification(numberOfSteps + "");
else {
try {
notificationManager.cancel(MAIN_NOTIFICATION_ID);
} catch (Exception e) {
}
}
}
public void sendStepIncrementBroadcast(int numberOfSteps) {
Intent intent = new Intent(STEP_INCREMENT);
intent.putExtra(STEP_INCREMENT_KEY, numberOfSteps);
broadcaster.sendBroadcast(intent);
}
@Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
public float[] getDataFromSteps(int stepsCount) {
float caloriesCount = 0;
float creditsCount = 0;
try {
double adjustedWeight = Double.parseDouble(session.getUser().getWeight()) / LinksAndKeys.weightAdjuster;
caloriesCount = Math.round(((adjustedWeight * LinksAndKeys.metValue) / LinksAndKeys.setPace) * (stepsCount / LinksAndKeys.stepsPerMile));
caloriesCount = caloriesCount * 1.2f;
creditsCount = caloriesCount / 25.4f;
} catch (Exception e) {
caloriesCount = 0;
creditsCount = 0;
}
float[] resultantFloat = {caloriesCount, creditsCount};
return resultantFloat;
}
private void startAlarm() {
sendActivityAlarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ActivityCompleteReceiver.class);
activityAlarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 58);
// calendar.set(Calendar.HOUR_OF_DAY, generateRandomTime()[0]);
// calendar.set(Calendar.MINUTE, generateRandomTime()[1]);
if (System.currentTimeMillis() > calendar.getTimeInMillis()) {
calendar.add(Calendar.DAY_OF_YEAR, 1);
}
sendActivityAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, activityAlarmIntent);
}
private void updateMainNotification(String stepsValue) {
String title = "Today: " + stepsValue + " steps - " + LinksAndKeys.decimalFormat.format(getDataFromSteps(session.getTodaySteps())[1]) + " FIMOs";
String message = "Keep Walking and Keep Earning";
contentView.setTextViewText(R.id.textViewTitle, title);
contentView.setTextViewText(R.id.textViewMessage, message);
Intent notificationIntent = new Intent(StepCounterService.this, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(StepCounterService.this, 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.running_icon)
.setContent(contentView).setContentIntent(intent);
Notification notification = mBuilder.build();
notification.flags |= Notification.FLAG_ONGOING_EVENT;
// notificationManager.notify(MAIN_NOTIFICATION_ID, notification);
startForeground(MAIN_NOTIFICATION_ID, notification);
}
private void updateReminderNotification() {
String title = "A gentle reminder";
String message = "Its time to get on track";
contentView.setTextViewText(R.id.textViewTitle, title);
contentView.setTextViewText(R.id.textViewMessage, message);
Intent notificationIntent = new Intent(StepCounterService.this, SplashActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(StepCounterService.this, 0, notificationIntent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.running_icon)
.setContent(contentView).setContentIntent(intent);
Notification notification = mBuilder.build();
notificationManager.notify(SECONDARY_NOTIFICATION_ID, notification);
}
private int[] generateRandomTime() {
int[] timeIntegers = new int[2];
final Random r = new Random();
timeIntegers[0] = r.nextInt(58 - 56) + 56;
timeIntegers[1] = r.nextInt(59 - 1) + 1;
return timeIntegers;
}
}
这是 Activity 完成接收器:
public class ActivityCompleteReceiver extends BroadcastReceiver implements WebServiceInterface {
Session session;
private LocalBroadcastManager broadcaster;
static final public String ACTIVITY_COMPLETE = "com.fimo.ACTIVITY_COMPLETE";
private static final int SEND_ACTIVITY_REQUEST_CODE = 1;
Gson gson;
MyDatabase myDatabase;
UserActivity currentUserActivity;
@Override
public void onReceive(Context context, Intent intent) {
session = new Session(context);
broadcaster = LocalBroadcastManager.getInstance(context);
myDatabase = new MyDatabase(context);
gson = new Gson();
sendActivityToServer(context, session.getUser().getId(), session.getTodaySteps());
}
private void sendActivityToServer(Context context, String id, int steps) {
Calendar c = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String date = dateFormat.format(c.getTime());
UserActivity userActivity = new UserActivity();
userActivity.setDate(date);
userActivity.setSteps(steps);
userActivity.setCalories(getDataFromSteps(steps)[0]);
userActivity.setCredits(getDataFromSteps(steps)[1]);
currentUserActivity = userActivity;
if (isNetworkAvailable(context)) {
HashMap<String, String> paramsList = new HashMap<>();
ArrayList<UserActivity> arrayListUserActivity = myDatabase.getAllUserActivities();
arrayListUserActivity.add(userActivity);
paramsList.put(LinksAndKeys.ID_KEY, id);
paramsList.put(LinksAndKeys.DATA_KEY, gson.toJson(arrayListUserActivity));
Log.d("Receiver Request ----", id + " - " + gson.toJson(arrayListUserActivity));
WebServiceController webServiceController = new WebServiceController(
context, ActivityCompleteReceiver.this);
String hitURL = LinksAndKeys.SEND_ACTIVITY_URL;
webServiceController.sendSilentRequest(false, hitURL, paramsList, SEND_ACTIVITY_REQUEST_CODE);
} else {
myDatabase.addUserActivity(currentUserActivity);
currentUserActivity = null;
Intent in = new Intent(ACTIVITY_COMPLETE);
broadcaster.sendBroadcast(in);
session.setTodaySteps(0);
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public void getResponse(int responseCode, String responseString, String requestType, int requestCode) {
if (requestCode == SEND_ACTIVITY_REQUEST_CODE && responseCode == 200) {
try {
JSONObject responseObject = new JSONObject(responseString);
String message = responseObject.getString("message");
if (message.equals("Success")) {
myDatabase.deleteAllUserActivities();
JSONObject jsonObject = responseObject.getJSONObject("data");
session.setServerCredits(Float.parseFloat(jsonObject.getString("credits")));
Intent in = new Intent(ACTIVITY_COMPLETE);
broadcaster.sendBroadcast(in);
session.setTodaySteps(0);
} else {
myDatabase.addUserActivity(currentUserActivity);
currentUserActivity = null;
Intent in = new Intent(ACTIVITY_COMPLETE);
broadcaster.sendBroadcast(in);
session.setTodaySteps(0);
}
} catch (Exception e) {
myDatabase.addUserActivity(currentUserActivity);
currentUserActivity = null;
Intent in = new Intent(ACTIVITY_COMPLETE);
broadcaster.sendBroadcast(in);
session.setTodaySteps(0);
}
} else {
if (currentUserActivity != null) {
myDatabase.addUserActivity(currentUserActivity);
currentUserActivity = null;
Intent in = new Intent(ACTIVITY_COMPLETE);
broadcaster.sendBroadcast(in);
session.setTodaySteps(0);
}
}
}
public float[] getDataFromSteps(int stepsCount) {
float caloriesCount = 0;
float creditsCount = 0;
try {
double adjustedWeight = Double.parseDouble(session.getUser().getWeight()) / LinksAndKeys.weightAdjuster;
caloriesCount = Math.round(((adjustedWeight * LinksAndKeys.metValue) / LinksAndKeys.setPace) * (stepsCount / LinksAndKeys.stepsPerMile));
caloriesCount = caloriesCount * 1.2f;
creditsCount = caloriesCount / 25.4f;
} catch (Exception e) {
caloriesCount = 0;
creditsCount = 0;
}
float[] resultantFloat = {caloriesCount, creditsCount};
return resultantFloat;
}
}
编写的代码应该以这种方式运行:
每天统计用户的步数。 -> 在 11.56-11.59 之间的特定时间午夜,将数据发送到 Activity 完成接收器 -> 接收器接收数据并尝试将其发送到服务器(如果互联网可用)。如果没有,则将其保存到本地数据库 -> 保存或发送后,将步数重置为 0,第二天服务从 0 开始重新计数。
问题是服务在给定时间的某些天实际上没有工作,并且接收者没有收到 Activity 完成的 Intent 。如果我保持电话开机并通过设置一个比当前时间晚几分钟的时间来测试它,服务就可以正常工作。但是,如果电话长时间保持不动,那么我认为这种情况会在服务停止工作时发生。这是我的猜测,实际问题可能是别的。非常感谢任何建议或解决方案。
最佳答案
从 API 级别 19 开始,使用 AlarmManager.setRepeating()
调用您的 ActivityCompleteReceiver
并不可靠准确。 Android 可以根据需要延迟发送此警报。如果您真的希望它在每天的确切时间触发,您应该执行以下操作:
使用 AlarmManager.setExact()
并为下一次触发时间设置一个警报(不是重复警报)。发送此警报后,发送您的统计信息或任何您想要的内容,然后调用 AlarmManager.setExact()
设置下一个警报(第二天)。您应该避免使用 setRepeating()
除非您绝对需要使用它。
您需要注意使用唤醒锁做什么,因为您当前的代码始终保持部分唤醒锁,这将防止设备进入休眠状态,这会耗尽电池电量。阅读有关如何优化电池使用的信息。
关于android - 一段时间后服务停止工作。需要连续工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44535567/
我在Windows 10中使用一些简单的Powershell代码遇到了这个奇怪的问题,我认为这可能是我做错了,但我不是Powershell的天才。 我有这个: $ix = [System.Net.Dn
var urlsearch = "http://192.168.10.113:8080/collective-intellegence/StoreClicks?userid=" + userId +
我有一个非常奇怪的问题,过去两天一直让我抓狂。 我有一个我试图控制的串行设备(LS 100 光度计)。使用设置了正确参数的终端(白蚁),我可以发送命令(“MES”),然后是定界符(CR LF),然后我
我目前正试图让无需注册的 COM 使用 Excel 作为客户端,使用 .NET dll 作为服务器。目前,我只是试图让概念验证工作,但遇到了麻烦。 显然,当我使用 Excel 时,我不能简单地使用与可
我开发了简单的 REST API - https://github.com/pavelpetrcz/MandaysFigu - 我的问题是在本地主机上,WildFly 16 服务器的应用程序运行正常。
我遇到了奇怪的情况 - 从 Django shell 创建一些 Mongoengine 对象是成功的,但是从 Django View 创建相同的对象看起来成功,但 MongoDB 中没有出现任何数据。
我是 flask 的新手,只编写了一个相当简单的网络应用程序——没有数据库,只是一个航类搜索 API 的前端。一切正常,但为了提高我的技能,我正在尝试使用应用程序工厂和蓝图重构我的代码。让它与 pus
我的谷歌分析 JavaScript 事件在开发者控制台中运行得很好。 但是当从外部 js 文件包含在页面上时,它们根本不起作用。由于某种原因。 例如; 下面的内容将在包含在控制台中时运行。但当包含在单
这是一本名为“Node.js 8 the Right Way”的书中的任务。你可以在下面看到它: 这是我的解决方案: 'use strict'; const zmq = require('zeromq
我正在阅读文本行,并创建其独特单词的列表(在将它们小写之后)。我可以使它与 flatMap 一起工作,但不能使它与 map 的“子”流一起工作。 flatMap 看起来更简洁和“更好”,但为什么 di
我正在编写一些 PowerShell 脚本来进行一些构建自动化。我发现 here echo $? 根据前面的语句返回真或假。我刚刚发现 echo 是 Write-Output 的别名。 写主机 $?
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 4年前关闭。 Improve thi
我将一个工作 View Controller 类从另一个项目复制到一个新项目中。我无法在新项目中加载 View 。在旧项目中我使用了presentModalViewController。在新版本中,我
我对 javascript 很陌生,所以很难看出我哪里出错了。由于某种原因,我的功能无法正常工作。任何帮助,将不胜感激。我尝试在外部 js 文件、头部/主体中使用它们,但似乎没有任何效果。错误要么出在
我正在尝试学习Flutter中的复选框。 问题是,当我想在Scaffold(body :)中使用复选框时,它正在工作。但我想在不同的地方使用它,例如ListView中的项目。 return Cente
我们当前使用的是 sleuth 2.2.3.RELEASE,我们看不到在 http header 中传递的 userId 字段没有传播。下面是我们的代码。 BaggageField REQUEST_I
我有一个组合框,其中包含一个项目,比如“a”。我想调用该组合框的 Action 监听器,仅在手动选择项目“a”完成时才调用。我也尝试过 ItemStateChanged,但它的工作原理与 Action
你能看一下照片吗?现在,一步前我执行了 this.interrupt()。您可以看到 this.isInterrupted() 为 false。我仔细观察——“这个”没有改变。它具有相同的 ID (1
我们当前使用的是 sleuth 2.2.3.RELEASE,我们看不到在 http header 中传递的 userId 字段没有传播。下面是我们的代码。 BaggageField REQUEST_I
我正在尝试在我的网站上设置一个联系表单,当有人点击发送时,就会运行一个作业,并在该作业中向所有管理员用户发送通知。不过,我在失败的工作表中不断收到此错误: Illuminate\Database\El
我是一名优秀的程序员,十分优秀!