【问题标题】:Service stops working after sometime. Needed to work continuously服务在一段时间后停止工作。需要连续工作
【发布时间】:2017-06-14 04:39:22
【问题描述】:

我正在开发一个计步器应用程序,我在其中计算步行的步数并在午夜将其更新到服务器。我有一个持续运行的服务来完成这一切。

这是我的服务:

    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;
    }
}

这是活动完成接收器:

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 之间的特定时间午夜,将数据发送到活动完成接收器 -> 如果互联网可用,接收器接收数据并尝试将其发送到服务器。如果没有,则将其保存到本地数据库->保存或发送后,将步骤重置为0,服务从0重新开始计数。

问题是服务在给定时间的某些天实际上并没有工作,并且接收者没有收到活动完整的意图。如果我保持手机开机并通过设置距当前时间几分钟的时间进行测试,则服务可以正常工作。但是如果手机长时间保持不动,那么我认为这种情况会随着服务停止工作而发生。这是我的猜测,实际问题可能是其他问题。任何建议或解决方案都非常感谢。

【问题讨论】:

  • 请将服务切换到manifest中的进程并尝试。或尝试前台服务。服务可能会在一段时间后停止
  • Android 会在设备内存不足时关闭服务,您可以在服务的 onTerminate() 上启动服务,也可以在服务的 onDestroy() 上发送广播并使用接收器启动服务再次。
  • this question 有帮助吗?
  • 供一般人使用。它将进入游戏商店。
  • 当您的Service 运行时,您持有部分唤醒锁。设备将永远无法进入睡眠状态,您将耗尽电池电量。用户将立即卸载您的应用。

标签: android broadcastreceiver android-service alarmmanager


【解决方案1】:

从 API 级别 19 开始,使用 AlarmManager.setRepeating() 来调用 ActivityCompleteReceiver 并不可靠。如果愿意,Android 可以延迟此警报的传递。如果您真的希望在每天的准确时间触发此功能,您应该执行以下操作:

使用AlarmManager.setExact() 并为下一次触发时间设置一个警报(不是重复警报)。当此警报发出时,发送您的统计数据或任何您想要的,然后致电AlarmManager.setExact() 设置下一个警报(第二天)。除非绝对需要,否则应避免使用setRepeating()

您需要注意您对唤醒锁的操作,因为您当前的代码始终保持部分唤醒锁,这将防止设备进入睡眠状态,从而耗尽电池电量。阅读有关如何优化电池使用的信息。

【讨论】:

    【解决方案2】:

    您似乎遇到了打瞌睡模式限制,在 Android 6.0 中引入,并在 Android 7.0 中分为 Light 和 Deep Doze:

    当设备使用电池供电并且屏幕已关闭一段时间后,设备会进入打盹并应用第一个限制子集:它会关闭应用网络访问,并推迟作业和同步。如果设备在进入打盹后静止一段时间,系统会将其余的打盹限制应用于 PowerManager.WakeLock、AlarmManager 警报、GPS 和 Wi-Fi 扫描。无论是应用部分还是全部打盹限制,系统都会在短暂的维护窗口中唤醒设备,在此期间应用程序可以访问网络并可以执行任何延迟的作业/同步。

    因此,即使您设法发出警报,例如使用setAndAllowWhileIdle(),您仍然无法访问网络。通常的建议是使用JobScheduler 或类似的东西,例如Firebase JobDispatcherEvernote Android-Job。这些框架允许配置将在网络可用时运行的作业,例如与JobInfo.Builder.setRequiredNetworkType()。时间将取决于 Doze 何时进入其“空闲维护”窗口,但至少您知道当它发生时您将拥有网络访问权限。

    如果需要对时间进行更多控制,可以设置一个在空闲时唤醒的闹钟,然后使用 GCM/FCM 高优先级消息强制网络访问。不过,我不确定您是如何在 Firebase 端获取这些内容的——这取决于您的服务器端代码。

    【讨论】:

      【解决方案3】:

      •已启动的服务可以使用 startForeground(int, Notification) API 将服务置于前台状态,在该状态下系统认为它是用户主动意识到的,因此在低电量时不适合杀死记忆。 (理论上,在当前前台应用程序的极端内存压力下,服务仍然可能被终止,但实际上这应该不是问题。

      1:使用 startForeground 使用服务启动通知。

      2:从 OnCommandStart 返回 START_STICKY。

       private void showLocationNotification()
          {
              Notification notification = new Notification.Builder(this)
                      .setContentTitle("Service")
                      .setContentText("Service Started Successfully")
                      .setSmallIcon(R.mipmap.ic_launcher)
                      .build();
      
              startForeground(1, notification);
          }
      

      在 Create Call Above 方法上

      3.Manifest 文件在你的服务标签中放这个android:stopWithTask="false"

      【讨论】:

      • stopWithTask的默认值为false。
      【解决方案4】:

      将您的服务设为Foreground service 并显示持续通知。它几乎永远不会被杀死。出于同样的原因,所有可靠的计步器应用程序都会显示持续通知。音乐播放器也可以。

      【解决方案5】:

      从 Android 6.0 开始引入了打盹模式,通过在设备长时间不使用时延迟应用的后台 CPU 和网络活动来减少电池消耗。

      要确认打盹模式是服务不运行的原因,请使用下面的命令强制让你的手机进入打盹模式并检查服务是否运行(通过将时间设置为几分钟后)

          $ adb shell dumpsys deviceidle force-idle
      

      我们还可以通过将应用程序从打盹模式列入白名单来进行测试。在设置 > 电池 > 电池优化中手动配置白名单并选择您的应用。 https://developer.android.com/training/monitoring-device-state/doze-standby.html

      【讨论】:

      • 如果问题是打盹模式,该过程将在几分钟或不超过一小时后停止。问题是 Android 不是服务器操作系统,并且不能 100% 保证服务不会被杀死。服务在最初的几个小时内被杀死的可能性很低,但在 2 或 3 天后变得非常高。
      【解决方案6】:

      我认为您的主要问题是 Android 不是一个旨在连续运行的系统。

      即使使用服务,甚至使用 startForeground,也不能保证您的进程在任何时候都不会被系统杀死。

      Android 不是服务器操作系统。服务在最初几个小时内被杀死的可能性很低,但在 2 或 3 天后变得非常高

      Android 的一个主要优先事项是节省电池而不是保持某些服务运行。

      此外,通过您的设计,很明显,您的应用程序在耗电应用程序中的得分非常高,因为您的意图不允许设备进入深度睡眠,并且用户肯定必须每天为电池充电一次以上.

      我认为你应该改变你的设计并将你的运行时间限制在有限的时间段内,就像典型的体育应用一样。

      【讨论】:

        猜你喜欢
        • 2013-11-19
        • 2019-03-04
        • 2010-11-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-20
        相关资源
        最近更新 更多