When I try to put my weather widget on the homescreen I want to give the user an option of choosing a city at that moment and the widget starts showing the weather for that city. For this I have made use of onEnabled method in Provider class.
So what I am doing here is just starting an activity to some preference class where I make use of string array to give the user the option to choose. And then OnSharedPreferenceChangeListener inside onEnabled again I am starting another activity with the url of city. This new acitvity class will handle the logic of weather at start up when I try to put the weather widget on the homecreen for the first time. So I am just trying to set some textFields in this new activity class so that they will appear in the widget when i put them on the screen, but I cant I dont know why its not being applied. Here is the code below of my AppWidgetProvider.
public class MyWeatherAppWidgetProvider extends AppWidgetProvider{
private String url;
@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
final Context this_context = context;
Intent intent = new Intent(context.getApplicationContext(), EditPrefs.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
OnSharedPreferenceChangeListener listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this_context);
url = prefs.getString("cities", "http://www.yr.no/place/Nepal/Bagmati/Kathmandu/forecas开发者_JAVA百科t.xml");
System.out.println(url);
Intent intent = new Intent(this_context.getApplicationContext(), VaxjoWeather.class);
intent.putExtra("city", url);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this_context.startActivity(intent);
}
};
prefs.registerOnSharedPreferenceChangeListener(listener);
url = prefs.getString("cities", "http://www.yr.no/place/Nepal/Bagmati/Kathmandu/forecast.xml");
System.out.println(url);
}
I wouldn't rely on onEnabled
to do things properly for you. As far as I know there is still a bug which allows for widgetIds to linger when widget configuration gets cancelled. This means that when you place a first widget and cancel the configuration, an Id is still stored in the system for the specific AppWidgetProvider, and thus onEnabled isn't called when you place it again since it still has a 'ghost' id already in its appWidgetProviderIds.
精彩评论