need to run service while device got wifi/data connection

别来无恙 提交于 2019-12-04 01:58:10

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!