我正在編寫一個應用程序來跟蹤Google地圖上的路線歷史記錄。它將每5分鐘獲取設備的當前位置並通過web服務將數據發送到服務器。設備睡眠時BroacastReceiver不工作?
此代碼從MainActivity
manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
intent.putExtra("USERNAME", mUsername);
intent.putExtra("DB_NAME", mDBName);
intent.putExtra("DB_IP", mDBIP);
intent.putExtra("DB_USER", mDBUsername);
intent.putExtra("DB_PASS", mDBPassword);
intent.putExtra("SERVER_IP", mServerIP);
mAlarmIntent = PendingIntent.getActivity(getApplicationContext(), REQUEST_CODE, intent, 0);
int mTimeRepeat = 300 * 1000; // repeat every 5 minutes
int mTimeStart = 5 * 1000;
manager.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + mTimeStart, mTimeRepeat, mAlarmIntent);
調用廣播接收器在廣播接收器,我得到的LAT-長,並調用Web服務。
public class AlarmReceiver extends BroadcastReceiver {
private static final String TAG = "Alarm Receiver";
private String mUsername = "";
private String mDBName = "";
private String mDBIP = "";
private String mDBUsername = "";
private String mDBPassword = "";
private String mServerIP = "";
private Context context;
private static AsyncHttpClient sClient = new AsyncHttpClient();
@Override
public void onReceive(final Context context, Intent intent) {
this.context = context;
mUsername = intent.getStringExtra("USERNAME");
mDBIP = intent.getStringExtra("DB_IP");
mDBName = intent.getStringExtra("DB_NAME");
mDBUsername = intent.getStringExtra("DB_USER");
mDBPassword = intent.getStringExtra("DB_PASS");
mServerIP = intent.getStringExtra("SERVER_IP");
if (Utility.checkLocationPermission(context)) {
try {
GPSTracker mGPS = new GPSTracker(context);
// check if GPS enabled
if (mGPS.canGetLocation()) {
double latitude = mGPS.getLatitude();
double longitude = mGPS.getLongitude();
// more code here
問題是應用程序工作正常,當我讓我的手機保持清醒,如果手機睡覺,它沒有工作。即使手機在睡眠,我也希望發送數據,我該怎麼做?
嘗試使用標誌'AlarmManager.ELAPSED_REALTIME_WAKEUP' –
由於棉花糖,你應該實現你的應用程序,它可以兼容打盹模式。 https://developer.android.com/training/monitoring-device-state/doze-standby.html檢查也https://stackoverflow.com/a/35657522/1196752 – Vektor88
AlarmManager已過時,並不適用於高於21的設備 使用Job scheduler而不是 –