2016-01-13 67 views
0

我想創建一個服務,該服務定期執行某個功能並在符合某些要求時調用另一個功能。所有這些都應該發生在後臺進程中。當android中的應用程序未處於活動狀態時運行後臺服務

這是我的主要acivity的的onPause方法從何講起這是應該執行所需的任務服務:

@Override 
    protected void onPause() { 
     super.onPause(); 
     stopLocationUpdates(); 
     if(alarm){ 
      bgIntent = new Intent(this, bgAlarmService.class); 
      startService(bgIntent); 
      alarmHostIsService = true; 
     } 

    } 

onStartCommand我的服務:

@Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 



     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       if (mGoogleApiClient == null) { 
        mGoogleApiClient = new GoogleApiClient.Builder(bgAlarmService.this) 
          .addConnectionCallbacks(bgAlarmService.this) 
          .addOnConnectionFailedListener(bgAlarmService.this) 
          .addApi(LocationServices.API) 
          .build(); 
       } 

       mGoogleApiClient.connect(); 
      } 
     }; 

     Thread bgThread = new Thread(r); 
     bgThread.start(); 
     return START_NOT_STICKY; 
    } 

但當的onPause方法被調用並且應用程序變爲非活動狀態,該服務不會繼續工作。我如何在後臺運行此服務?

回答

3

使用服務和廣播接收機來做到這一點。 在修復時間間隔使用以下代碼發送brodcast。

Calendar calendar = Calendar.getInstance(); 
long currentDateTime=calendar.getTimeInMillis(); 
calendar.setTime(new Date(currentDateTime+(5*60*1000)));// 5 minutes timeout 
Intent myIntent = new Intent(this,YourReceiver.class); 
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0); 
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); 

在你的廣播接收器裏面現在在onStartCommand裏面啓動服務。

Intent yourService= new Intent(context, YourService.class); 
context.startService(Intent yourService= new Intent(context, YourService.class); 
+0

哦天哪,爲什麼5分鐘滯後計算如此複雜?:) – Vyacheslav

+0

如果您知道更簡單的PLZ評論,我有這一個,我會將其添加到我的知識庫中。 – Krishna

+0

使用'System.currentTimeMillis()+ 5 * 60 * 1000';)而不是如此巨大的計算。 – Vyacheslav

相關問題