0

全部。我有一个从互联网获取天气信息的动态壁纸。通过服务和警报获取天气信息。连接丢失时如何暂停警报和服务(例如设备正在睡眠)。我希望在没有互联网的情况下没有触发警报并且没有启动服务,并且一旦互联网可用,一切都会重新开始。

对不起我的英语不好。

升级版:

这是警报接收器

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

}

4

1 回答 1

0

there is a braodcat (Action named ConnectivityManager.CONNECTIVITY_ACTION), u can set a broadcast receiver to get it, and switch your service or pendingintent.

android connect to internet event ,this is similar

于 2013-07-15T03:15:05.347 回答