Last time, I use following coding to run background service.
Intent intent = new Intent(InitActivity.this, GetService.class);
PendingIntent pintent = PendingIntent.getService(InitActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 50 * 1000, pintent);
return getZipInfo.toString();
to make better performance, I want to run my background service once device is connect WIFI/data connection. To make clear, if device is not connect wifi/data connection, my background service will not run for sure. Once connect wifi/data connection, it will run immediately.
To check the WiFi connection you can use this
ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
To execute the code whenever the Wifi is connected, you have to register Brodcast Recevier
Register the receiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
In your Receiver class do this
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION)) {
if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false)) {
//do stuff
} else {
// wifi connection was lost
}
}
And as mentioned below, dont forget to add the permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
来源:https://stackoverflow.com/questions/17063910/need-to-run-service-while-device-got-wifi-data-connection