0

我正在開發一個android應用程序,該應用程序將從用戶(窗體,模擬聊天)中獲取輸入並將其存儲在本地數據庫。 我已經創建了BroadcastReceiver來獲取網絡更改狀態,如果連接,我開始將數據發佈到服務器。即使應用程序已關閉,在Android中向服務器發佈數據的服務(脫機到在線)

public class NetworkChangeReceiverService extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     if (Connectivity.isConnected(context)) { 
      Logger.d("Connected to internet"); 
      // Post data to the server. 
     } else { 
      Logger.d("Not connected to internet"); 
     } 
    } 
} 

這是正確的做法。如果您指定將數據發佈到服務器的詳細信息,如果我使用AsyncTask或僅使用簡單的Retrofit事物,我希望在接收器和發佈工作時儘可能降低內存消耗在背景中。阿洛斯,如果,可能想知道同樣的WhatsApp的工作。

回答

0

您可以編寫服務和AlarmManager來執行此操作。只需在服務中註冊您的應用程序,並調用alarmMangaer.setRepeat()方法來啓動您的服務器代碼或您想要在onStart()方法服務中執行的任何其他操作。

public class MyService extends Service{ 
    Calendar cur_cal = Calendar.getInstance(); 
    @Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Intent intent = new Intent(this, MyService.class); 
    PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 
      0, intent, 0); 
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
      cur_cal.setTimeInMillis(System.currentTimeMillis()); 
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(), 
      60 * 1000*3, pintent); 
} 
@Override 
public void onStart(Intent intent, int startId) { 
    // TODO Auto-generated method stub 
    super.onStart(intent, startId); 
      // your code for background process 
    } 
} 

在AndroidManifest.xml中添加此

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 
<service 
     android:name="com.yourpackage.MyService" 
     android:enabled="true" /> 
    <receiver android:name=".BootCompletedIntentReceiver" > 
     <intent-filter> 
      <action android:name="android.intent.action.BOOT_COMPLETED" /> 
     </intent-filter> 
    </receiver> 

編輯:BootCompletedIntentReceiver.java

import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 

public class BootCompletedIntentReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) { 
      Intent pushIntent = new Intent(context, MyService.class); 
      context.startService(pushIntent); 
     } 
    } 
} 
相關問題