未调用AlarmManager

时间:2019-06-21 09:30:36

标签: android android-alarms

我设置了一个警报,接收器启动了一个前台服务,该服务每隔几秒钟将数据发送到Firebase。当屏幕打开时,该服务被终止(我已经注册了屏幕接收器)。服务终止后,我会在20秒内设置另一个警报。我在服务启动或终止时发送时间戳(在onCreate()和onDestroy()方法中)。当我检查Firebase时,有6个小时的间隔根本没有发出警报。 这来自firebase数据:

2019-06-20 21:25:08开始

2019-06-20 21:25:08结束

2019-06-20 21:25:29开始

2019-06-20 21:25:29结束

2019-06-20 21:25:49开始

2019-06-20 21:35:26结束

2019-06-21 03:47:46开始

2019-06-21 08:48:02结束

2019-06-21 08:48:47开始

2019-06-21 08:55:55结束

2019-06-21 08:56:15开始

2019-06-21 08:56:15结束

AlarmReceiver.java:

if (PendingIntent.getBroadcast(context, 0, intentService, PendingIntent.FLAG_NO_CREATE) == null) {


   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          context.startForegroundService(intentService);
    } else {
          context.startService(intentService);
            }

    }

MyService.java:

public void onCreate() {
        super.onCreate();
        Log.d("created","service");
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyApp::MyWakelockTag");
        wakeLock.acquire();
        mDatabase = FirebaseDatabase.getInstance().getReference();
        username = sharedPreferences.getString("Username","invalid");

        mDatabase.child(username).child("ServiceData").push().setValue("started");


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(intent != null)
        {
            if(mReceiver!=null){
                unregisterReceiver(mReceiver);
            }

            PendingIntent pendingIntent =
                    PendingIntent.getActivity(this, 0, intent, 0);
            Notification notification =
                new NotificationCompat.Builder(this, getString(R.string.channelId))
                        .setContentTitle("CureFit")
                        .setContentText("Foreground process running")
                        .setSmallIcon(R.drawable.curefit)
                        .setContentIntent(pendingIntent)
                        .setColor(getResources().getColor(R.color.colorPrimaryDark))
                        .build();
            startForeground(1, notification);
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            if(powerManager.isScreenOn())
                stopSelf();

            initializeSensorManager();
            final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            mReceiver = new ScreenReceiver();
            registerReceiver(mReceiver, filter);
            Log.d("Started ", "foreground ");
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
            username = sharedPreferences.getString("Username","invalid");
        }
        return super.onStartCommand(intent, flags, startId);
    }
    private void initializeSensorManager() {
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        Sensor mAccelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_FASTEST);

    }


    @Override
    public void onSensorChanged(SensorEvent event) {
                //Log.d("Sensor","changed");
        if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
                if (prevValues == null
                        ||  Calendar.getInstance().getTimeInMillis()-prevTime >8000){



                        prevValues[0] = event.values[0];
                        prevValues[1] = event.values[1];
                        prevValues[2] = event.values[2];
                        Log.d("", "LOG SENSOR CHANGE");
                        Double sensorValue = MathUtil.magnitude(prevValues);
                        Calendar calendar = Calendar.getInstance();
                        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        prevTime = calendar.getTimeInMillis();
                        editor.putLong("Last_sent", calendar.getTimeInMillis());
                        editor.putFloat("Last_data_sent", (float) MathUtil.magnitude(prevValues));
                        editor.apply();
                        Log.d("accelerometer value", String.valueOf(MathUtil.magnitude(prevValues)));

                        try {
                            //String id = mDatabase.child(username).push().getKey();
                            long timestamp = calendar.getTimeInMillis();
                            Record r = new Record(timestamp, sensorValue);
                            mDatabase.child(username).child("data").push().setValue(r);
//                            myOutWriter.append(String.valueOf(timestamp));
//                            myOutWriter.append("\n");

                        } catch (Exception e) {
                            e.printStackTrace();
                            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "1st channel")
                                    .setSmallIcon(R.drawable.curefit)
                                    .setContentTitle("Sleep tracker")
                                    .setContentText(e.getMessage())
                                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
                            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);

                            notificationManager.notify(2, builder.build());
                        }
                    }



                }

    }
    @Override
    public void onAccuracyChanged(Sensor arg0, int arg1){

    }
    @Override
    public void onDestroy(){
        Log.d("killed","Service");
        if (sensorManager != null) {
            sensorManager.unregisterListener(this);
            sensorManager = null;
        }


        unregisterReceiver(mReceiver);
        Calendar calendar = Calendar.getInstance();
        mDatabase.child(username).child("ServiceData").push().setValue("ended");
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent i = new Intent(this, AlarmReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

//        am.setRepeating(AlarmManager.RTC_WAKEUP,
//                SystemClock.elapsedRealtime() + 5 * 1000,
//                5 * 1000, pi);
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + 20 * 1000 ,pi);
            am.setAlarmClock(new AlarmManager.AlarmClockInfo(Calendar.getInstance().getTimeInMillis()+20000,pi),pi);

        }
        else {
            am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime() + 20 * 1000 ,pi);
        }

        wakeLock.release();

    }

这可能是电话不允许拨打警报。可能是什么原因?

0 个答案:

没有答案