当互联网连接在android中丢失时暂停服务和警报

时间:2013-07-15 03:04:43

标签: android service

所有。 我有一个动态壁纸,从互联网获取天气信息。通过服务和警报获取天气信息。如何在连接丢失时暂停警报和服务(例如设备正在休眠)。我希望这个警报没有触发,并且当没有互联网时服务没有启动,并且很快互联网可以再次启动。

抱歉我的英文。

UPD:

这是闹钟接收器

public class WeatherAlarmReceiver extends BroadcastReceiver {

public static final String ACTION_REFRESH_WEATHER_ALARM = "ru.sergey.abadzhev.mslwpd.ACTION_REFRESH_WEATHER_ALARM";

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

    Intent startIntent = new Intent(context, GetWeatherService.class);
    context.startService(startIntent);
}

}

这是服务

public class GetWeatherService extends Service {

private String url, units;
private Weather weather;
private int updFreq;
SharedPreferences sPrefs;
InternetReceiver internetReceiver;
static Intent intent;

public static final String NEW_WEATHER = "ru.sergey.abadzhev.mslwpd.NEW_WEATHER";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    updFreq = Integer.parseInt(sPrefs.getString(
            WallpaperSettings.PREF_UPD_FREQ, "120"));

    int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
    long timeToRefresh = SystemClock.elapsedRealtime() + updFreq * 60
            * 1000;
    alarms.setRepeating(alarmType, timeToRefresh, updFreq * 60 * 1000,
            alarmIntent);

    sPrefs = getSharedPreferences(WallpaperActivity.PREFS, 0);
    units = sPrefs
            .getString(WallpaperSettings.PREF_MEASURE_UNITS, "metric");
    if (isOnline()) {
        getWeatherData();
    } else {
        Toast.makeText(getApplicationContext(),
                getResources().getString(R.string.no_internet_connection),
                Toast.LENGTH_SHORT).show();
        IntentFilter fFilter;
        fFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
        internetReceiver = new InternetReceiver();
        registerReceiver(internetReceiver, fFilter);
    }

    return Service.START_NOT_STICKY;
}

AlarmManager alarms;
PendingIntent alarmIntent;

@Override
public void onCreate() {
    sPrefs = getSharedPreferences(WallpaperActivity.PREFS, 0);
    alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    String ALARM_ACTION;
    ALARM_ACTION = WeatherAlarmReceiver.ACTION_REFRESH_WEATHER_ALARM;
    Intent intentToFire = new Intent(ALARM_ACTION);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
}

public void getWeatherData() {
    url = "http://api.openweathermap.org/data/2.5/weather?lat=57.1535105&lon=65.53222&units="
            + units
            + "&APPID=f9b99d6534aa4c68339db9a6d7064e50&lang="
            + getLanguage();
    WeatherGetter wg = new WeatherGetter();
    wg.execute(url);
    try {
        weather = wg.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    announceNewWeather(weather);

}

private void announceNewWeather(Weather _weather) {
    if (weather.getDescription() != null) {
        intent = new Intent(NEW_WEATHER);
        intent.putExtra("temperature", _weather.getTemp());
        intent.putExtra("humidity", _weather.getHumidity());
        intent.putExtra("speed", _weather.getSpeed());
        intent.putExtra("description", _weather.getDescription());
        intent.putExtra("time", _weather.getTime());
        intent.putExtra("pressure", _weather.getPressure());
        intent.putExtra("tempMin", _weather.getTempMin());
        intent.putExtra("tempMax", _weather.getTempMax());
        intent.putExtra("deg", _weather.getDeg());
        intent.putExtra("id", _weather.getId());
        intent.putExtra("sst", _weather.getSunSetTime());
        intent.putExtra("srt", _weather.getSunRiseTime());
        intent.putExtra("clouds", _weather.getCloud());

        sendStickyBroadcast(intent);
    }
    stopSelf();
}

@Override
public IBinder onBind(Intent arg0) {

    return null;
}

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()
            && cm.getActiveNetworkInfo().isAvailable()
            && cm.getActiveNetworkInfo().isConnected()) {
        return true;
    }
    return false;
}

public class InternetReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (isOnline()) {
            getWeatherData();
            try {
                unregisterReceiver(internetReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }

    }
}

public String getLanguage() {
    String lang;

    Configuration sysConfig = getResources().getConfiguration();
    Locale curLocale = sysConfig.locale;
    lang = curLocale.getLanguage();
    if (lang.equals("es")) {
        lang = "sp";
    } else if (lang.equals("uk")) {
        lang = "ua";
    } else if (lang.equals("sv")) {
        lang = "se";
    } else if (lang.equals("zh")) {
        if (getResources().getConfiguration().locale.getCountry().equals(
                "TW")) {
            lang = "zh_tw";
        } else if (getResources().getConfiguration().locale.getCountry()
                .equals("CN")) {
            lang = "zh_cn";
        }
    }
    return lang;
}

}

1 个答案:

答案 0 :(得分:0)

有一个braodcat(名为ConnectivityManager.CONNECTIVITY_ACTION的动作),你可以设置一个广播接收器来获取它,并切换你的服务或pendingintent。

android connect to internet event,这是类似的