【问题标题】:Alarm Manager not firing every 5 second警报管理器不是每 5 秒触发一次
【发布时间】:2017-09-11 12:31:59
【问题描述】:

我想每 5 或 10 秒将我当前的位置发送到服务器。但对我来说,它的警报管理器会随机触发。我已经尝试过谷歌的建议。

我试过这都是链接:

1.setRepeating() of AlarmManager repeats after 1 minute no matter what the time is set (5 seconds in this case, API 18+)

2.enteAndroid Alarm manager is repeating after 5sec

Activity.java

public class AlarmActivity extends AppCompatActivity {


    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm);


        button = (Button) findViewById(R.id.button1);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //startService(new Intent(AlarmActivity.this, CurrentLocation_Tracking.class));
                startAlert();
            }
        });
    }
    public void startAlert() {
        EditText text = (EditText) findViewById(R.id.time);
        int i = Integer.parseInt(text.getText().toString());
        Intent intent = new Intent(this, MyBroadcastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                this.getApplicationContext(), 234324243, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

       /* alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                + (i * 1000), pendingIntent);*/

        alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent);
        Toast.makeText(this, "Alarm set in " + i + " seconds", Toast.LENGTH_LONG).show();
    }
}

广播接收器

public class MyBroadcastReceiver extends BroadcastReceiver {
    MediaPlayer mp;
    @Override
    public void onReceive(Context context, Intent intent) {

        context.startService(new Intent(context, CurrentLocation_Tracking.class));

        mp= MediaPlayer.create(context, R.raw.notification);
        mp.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();
    }
}

服务类

public class CurrentLocation_Tracking extends Service {

    private static final String TAG = "BOOMBOOMTESTGPS";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 1000; // 5 seconds
    private static final float LOCATION_DISTANCE = 1f;  //30 meters
    LocationListener[] mLocationListeners;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

    String status_currenttrack = "";
    private Context mContext;

    private class LocationListener implements android.location.LocationListener {
        Location mLastLocation;

        public LocationListener(String provider) {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location) {
            Log.e(TAG, "onLocationChanged: " + location);

            Log.d("currentlocation..", "" + location.getLongitude() + " " + location.getLatitude());

             //Sent_LatLngs_currentpostion("" + location.getLatitude(), "" + location.getLongitude());

            Toast.makeText(CurrentLocation_Tracking.this, "latlongvale" + location.getLatitude() + "" + location.getLongitude(), Toast.LENGTH_LONG).show();
            mLastLocation.set(location);

            mLocationManager.removeUpdates(LocationListener.this);
        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }


    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
       // stopSelf();

         mLocationListeners = new LocationListener[]{
                new LocationListener(LocationManager.GPS_PROVIDER),
                new LocationListener(LocationManager.NETWORK_PROVIDER)
        };

        initializeLocationManager();

        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.d("failvalue", "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d("gpstages", "gps provider does not exist " + ex.getMessage());
        }

        return START_STICKY;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        mContext=this;
    }

    @Override
    public void onDestroy() {
        Log.d("Destroy", "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {

                    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.d("initialize", "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }
}

【问题讨论】:

  • 为什么要投反对票,给我建议,我会纠正它。
  • 这是您正确触发警报的地方:alarmManager.setInexactRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent); Toast.makeText(this, "警报设置在 " + i + " 秒", Toast.LENGTH_LONG).show();
  • @Anders Kink i 值我通过 Editext 作为 5 传递
  • 而不是 setInexactRepeating 尝试:setRepeating
  • 每 5 秒检查一次位置会耗尽您的用户电量 - 请注意 - 如果您现在发布此功能,Android O 不会让您继续这样。另外private static final int LOCATION_INTERVAL = 1000; // 5 seconds 实际上是 1 秒,AlarmManager 不会经常触发

标签: android service broadcastreceiver alarmmanager


【解决方案1】:

你应该只需要更改为

alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), (i * 1000), pendingIntent);

但请注意 Javadoc:

对于计时操作(滴答声、超时等),使用 Handler 更简单、更高效

从 API 19 开始,所有重复警报都是不精确的如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报

所以使用起来可能会更好:

alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + (i * 1000), pendingIntent);

如果您以 API 19 为目标,则为以下内容:

alarmManager.setExact(AlarmManager.RTC, System.currentTimeMillis() + (i * 1000), pendingIntent);

【讨论】:

  • 如果我使用Handler 工作正常,先生,但AlarmManager 不工作,为什么。
  • 因为 setInexactRepeating 允许操作系统重新调度它以提高效率
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-10
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
相关资源
最近更新 更多