设备获得wifi /数据连接时需要运行服务

时间:2013-06-12 11:07:26

标签: android service android-wifi

上次,我使用以下编码来运行后台服务。

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();

为了获得更好的性能,我想在设备连接WIFI /数据连接后运行我的后台服务。要说清楚,如果设备没有连接wifi /数据连接,我的后台服务将无法运行。连接wifi /数据连接后,它将立即运行。

1 个答案:

答案 0 :(得分:5)

要检查WiFi连接,您可以使用此

ConnectivityManager connManager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (mWifi.isConnected()) {
// Do whatever
}

要在连接Wifi时执行代码,您必须注册Brodcast Recevier

注册接收器

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
registerReceiver(broadcastReceiver, intentFilter);

在Receiver课程中执行此操作

@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
    }
}

如下所述,不要忘记在AndroidManifest.xml中添加权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />