Android Send data in the background when connected
android, service
Solution
You can use a `broadcast receiver` for this purpose. See this question on SO.
You can check if internet connection has been established, there is no need to check after regular intervals.
(Quoting from the link I have mentioned earlier)
<receiver android:name=".ReceiverName" >
<intent-filter >
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
And
public class ReceiverName extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
if (cm == null)
return;
if (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected()) {
// Send here
} else {
// Do nothing or notify user somehow
}
}
}
Hope this helps!
Problem
Basicly I need that my app sends some data to a server when the connection to the network is established and it has to be in the background. That's it. Is there a way that my service is automaticly started when connection is made? Or should I use regular Service which tests the connection and run this service in something like 30min intervals? Should I use something like the AlarmManager to check for the connection? This seems as a waste of the resources and as far as I'm aware Android can stop services if resources are needed. Any suggestions or even better - samples on what is the optimal way? Thank you.