我試圖運行它在後臺運行,每20秒一個Android服務和用戶的經緯度長數據發送到服務器進行查殺應用程序不重新啓動跟蹤。這是我第一次啓動我的應用程序。現在,如果我點擊主頁按鈕,它仍然在後臺運行。但是,現在如果我使用主頁按鈕從應用程序列表中殺死我的應用程序。然後用啓動器圖標重新啓動我的應用程序。現在服務不啓動。我每20秒使用一次Alarm Manager來觸發我的服務。但在重新啓動時,我的鬧鐘已設置,但未在廣播接收器上註冊,因爲未調用我的服務。 下面是我的代碼: - MyFragment.java的onCreateView()我在哪裏設置我的報警: -使用AlarmManager每20秒後,運行的是Android服務從應用列表
Intent alarm = new Intent(mContext, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(mContext, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if (alarmRunning == false) {
Log.e("In OnCreateView DDFrag", "AlarmRunning == False");
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 20000, pendingIntent);
} else{
Log.e("In OnCreateView DDFrag", "AlarmRunning == True");
}
AlarmReceiver.class: -
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, MyService.class);
Log.e("AlarmReceiver", "Broadcasr Receiver started");
context.startService(background);
}
}
MyService.class : -
public class MyService extends Service {
public boolean isServiceRunning;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
this.isServiceRunning = false;
}
@Override
public void onDestroy() {
this.isServiceRunning = false;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isServiceRunning) {
sendDataToServer();
this.isServiceRunning = true;
}
return START_STICKY;
}
private void sendDataToServer() {
// Performing my operation in this method..
// On Success of the method performed I am calling the below method and setting the below variables:
stopSelf();
this.isServiceRunning = false;
}
}
此外我定義我的服務和接收器在manifest.xml文件爲: -
<service android:name="com.mypackagename.services.MyService" />
<receiver android:name="com.mypackagename.services.AlarmReceiver" />
請幫我解決問題,或點我我在做什麼wroung。 至於第一次。因爲我的鬧鐘管理器沒有設置,它會設置並在20秒後調用服務appropiatley。但是,如果我殺了我的應用程序並重新啓動它,那麼我的鬧鐘已設置爲不啓動或重新設置。現在我的AlarmReceiver類永遠不會收到Alarm BroadcastReceiver。
你測試什麼設備? –
@DavidWasser我對聯想A6010插槽 –
測試你有沒有加入你的應用程序,以「保護應用」或應用程序列表中允許在後臺運行的名單?在聯想應該有像「設置 - >電源 - >後臺應用程序管理」。請嘗試找到它並將您的應用程序添加到列表中。讓我知道你發現了什麼。 –