2016-01-14 111 views
-1

我有3個活動(A,B,C)和一個服務,我打電話來檢查是否從DB獲得新消息。這是一個HTTP請求。我需要每15秒發出一次請求。Android在後臺工作

Thread t = new Thread() { 

      @Override 
      public void run() { 
       try { 
        while (!isInterrupted()) { 
         Thread.sleep(15000); 
         runOnUiThread(new Runnable() { 
          @Override 
          public void run() { 
           // Here i call        
          } 
         }); 
        } 
       } catch (InterruptedException e) { 
       } 
      } 
     }; 

     t.start(); 

如何使它在我改變活動時有效?

+1

我猜你正在尋找的服務。這裏有一個創建一個指南:http://developer.android.com/intl/es/training/run-background-service/create-service.html –

+0

你有3個選擇,使其獨立於後臺工作:'服務','IntentService'和'AlarmManager' –

回答

0

選項:考慮更改設置以將三個片段作爲您的原始活動,以及一個控制重複輪詢消息到數據庫的MainActivity,以及控制片段。

0
@SuppressLint("SimpleDateFormat") 
public class AlarmService extends Service { 

    private PendingIntent pendingIntent; 
    Handler mHandler; 
    @Override 
    public IBinder onBind(Intent arg0) { 
     return null; 
    } 
    @Override 
    public void onCreate() { 
    } 

    public void f() { 
     Toast t = Toast.makeText(this, "Service is still running", 
       Toast.LENGTH_SHORT); 
     t.show(); 
    }; 
} 
    @Override 
    @Deprecated 
    public void onStart(Intent intent, int startId) { 
     Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT); 
     t.show(); 

     // TODO Auto-generated method stub 
     super.onStart(intent, startId); 

     mHandler = new Handler(); 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       f(); 
       mHandler.postDelayed(this, 20000); 
      } 
     }; 
     mHandler.postDelayed(r, 20000); 

    } 

} 

和清單使用本

<service android:name="com.example.yourservice"></service>