Android 如何将温度值(从服务)检索到AppWidgetProvider

Android 如何将温度值(从服务)检索到AppWidgetProvider,android,android-widget,android-service,Android,Android Widget,Android Service,大家好,我是android小部件的新手,我搜索了一个示例来检索appwidget提供的温度(它在服务中),但我并没有弄清楚这一点。因此,我启动了一项服务来获取温度细节 这是我的服务(这里我得到了临时值)需要知道我想如何将此详细信息传递给AppWidgetProvider class MainService extends Service { private SharedPreferences sharedPref; private static final String Sync

大家好,我是android小部件的新手,我搜索了一个示例来检索appwidget提供的温度(它在服务中),但我并没有弄清楚这一点。因此,我启动了一项服务来获取温度细节

这是我的服务(这里我得到了临时值)需要知道我想如何将此详细信息传递给AppWidgetProvider

class MainService extends Service {
    private SharedPreferences sharedPref;
    private static final String Sync_My_Settings = "SyncSettings";
    private Button tempbut;
    public static ArrayList<HashMap<String, String>> mDataFetchList;

    private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

    @Override
    public void onCreate() {
        super.onCreate();

        sharedPref = MainService.this.getSharedPreferences(Sync_My_Settings, Context.MODE_PRIVATE);

        setCurrentLocation();

        Log.e("edgar","Started Service");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void setCurrentLocation() {
        String myLat= "myLat",myLong="myLong";
        loc1 = new GeoLocationUtil(this).getCurrentLocation(this);
        if (loc1 != null) {
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString(myLat,  String.valueOf(loc1.getLatitude()));
            editor.putString(myLong, String.valueOf(loc1.getLongitude()));
            editor.commit();
            System.out.println("PWF Latitude = " + String.valueOf(loc1.getLatitude()) + "Longitude = " + String.valueOf(loc1.getLongitude()));

            JSONWeatherTask task = new JSONWeatherTask();
            task.execute("", sharedPref.getString(myLat, "0"), sharedPref.getString(myLong, "0"));
            try {
                int myTemp = (int) task.get().temperature.getTemp();
                String City =task.get().location.getCity();

                //System.out.println("SWF HH display fd=" + result);
                mDataFetchList = new ArrayList<HashMap<String, String>>();
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("Temp", City);
                mDataFetchList.add(map);
                Intent widgetUpdateIntent = new Intent();
                widgetUpdateIntent.setAction(MyProvider.DATA_FETCHED);
                widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                sendBroadcast(widgetUpdateIntent);
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
        }
    }

    private class JSONWeatherTask extends AsyncTask<String, Void, Weather> {
        @Override
        protected Weather doInBackground(String... params) {
            Weather weather = new Weather();
            String data = ( (new WeatherHttpClient()).getWeatherData(params[0], params[1], params[2]));
            try {
                weather = JSONWeatherParser.getWeather(data);

                // Let's retrieve the icon
                weather.iconData = ( (new WeatherHttpClient()).getImage(weather.currentCondition.getIcon()));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return weather;
        }

        @Override
        protected void onPostExecute(Weather weather) {         
            super.onPostExecute(weather);
            if (weather.iconData != null && weather.iconData.length > 0) {
                Bitmap img = BitmapFactory.decodeByteArray(weather.iconData, 0, weather.iconData.length);
                imgView.setImageBitmap(img);
            }
            String City =weather.location.getCity();
            String Cloudy =(weather.currentCondition.getCondition() + "(" + weather.currentCondition.getDescr() + ")");
            String temper ="" + weather.temperature.getTemp()  + "\u00B0C";
        }
    }
}
类MainService扩展服务{
私人SharedReferences SharedRef;
私有静态最终字符串Sync\u My\u Settings=“SyncSettings”;
私人按钮;
公共静态ArrayList mDataFetchList;
private int appWidgetId=AppWidgetManager.INVALID\u APPWIDGET\u ID;
@凌驾
public void onCreate(){
super.onCreate();
sharedPref=MainService.this.getSharedReferences(同步\我的\设置,上下文.模式\私有);
setCurrentLocation();
Log.e(“edgar”,“已启动服务”);
}
@可空
@凌驾
公共IBinder onBind(意向){
返回null;
}
public void setCurrentLocation(){
字符串myLat=“myLat”,myLong=“myLong”;
loc1=新的GeoLocationUtil(this).getCurrentLocation(this);
如果(loc1!=null){
SharedPreferences.Editor=sharedPref.edit();
editor.putString(myLat,String.valueOf(loc1.getLatitude());
putString(myLong,String.valueOf(loc1.getLongitude());
commit();
System.out.println(“PWF Latitude=“+String.valueOf(loc1.getLatitude())+”Longitude=“+String.valueOf(loc1.getLongitude()));
JSONWeatherTask task=新的JSONWeatherTask();
task.execute(“,sharedPref.getString(myLat,“0”),sharedPref.getString(myLong,“0”);
试一试{
int myTemp=(int)task.get().temperature.getTemp();
字符串City=task.get().location.getCity();
//System.out.println(“SWF HH display fd=“+结果”);
mDataFetchList=newarraylist();
HashMap=newHashMap();
地图放置(“临时”,城市);
mDataFetchList.add(映射);
Intent widgetUpdateIntent=新Intent();
widgetUpdateIntent.setAction(MyProvider.DATA_获取);
widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA\u APPWIDGET\u ID,appWidgetId);
发送广播(WidgetUpdateContent);
}捕获(中断异常|执行异常e){
e、 printStackTrace();
}
}否则{
Toast.makeText(此“错误”,Toast.LENGTH_SHORT).show();
}
}
私有类JSONWeatherTask扩展了AsyncTask{
@凌驾
受保护的天气背景(字符串…参数){
天气=新天气;
字符串数据=((新的WeatherHttpClient()).getWeatherData(参数[0],参数[1],参数[2]);
试一试{
weather=JSONWeatherParser.getWeather(数据);
//让我们检索图标
weather.iconda=((新的WeatherHttpClient()).getImage(weather.currentCondition.getIcon());
}捕获(JSONException e){
e、 printStackTrace();
}
回归天气;
}
@凌驾
执行后受保护的空(天气){
super.onPostExecute(天气);
如果(weather.iconda!=null&&weather.iconda.length>0){
位图img=BitmapFactory.decodeByteArray(weather.iconda,0,weather.iconda.length);
设置图像位图(img);
}
字符串City=weather.location.getCity();
字符串Cloudy=(weather.currentCondition.getCondition()+”(“+weather.currentCondition.getDescr()+”);
字符串tempt=“+weather.temperature.getTemp()+”\u00B0C”;
}
}
}
还有我的应用程序

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int count = appWidgetIds.length;

    for (int i = 0; i < count; i++) {
        final Intent intentt = new Intent(context, MainService.class);
        intentt.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
        context.startService(intentt);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

@Override
public void onEnabled(Context context) {
    // TODO Auto-generated method stub
    super.onEnabled(context);
}

@Override
public void onDisabled(Context context) {
    // TODO Auto-generated method stub
    super.onDisabled(context);
}

private RemoteViews updateWidgetListView(Context context, int appWidgetId) {
    // which layout to show on widget
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.simple_widgett);

    // RemoteViews Service needed to provide adapter for ListView
    Intent svcIntent = new Intent(context, MainService.class);

    // passing app widget id to that RemoteViews Service
    svcIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

    // setting a unique Uri to the intent
    if (MainService.mDataFetchList != null) {
        svcIntent.putExtra("data", MainService.mDataFetchList);
        remoteViews.setTextViewText(R.id.btn1, "Temp");
    }
    remoteViews.setRemoteAdapter(appWidgetId, R.id.btn1, svcIntent);
    remoteViews.setTextViewText(R.id.am, am.format(new Date()));
    Intent toastIntent = new Intent(context, MyProvider.class);
    toastIntent.setAction(MyProvider.TOAST_ACTION);
    toastIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    PendingIntent toastPendingIntent = PendingIntent.getBroadcast(context, 0, toastIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setPendingIntentTemplate(R.id.date, toastPendingIntent);
    return remoteViews;
}

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

    if (intent.getAction().equals(DATA_FETCHED)) {
        int appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        RemoteViews remoteViews = updateWidgetListView(context, appWidgetId);

        // update and notify widget when data arrives
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.date);
    }
}
public void onUpdate(上下文上下文,AppWidgetManager AppWidgetManager,int[]appWidgetIds){
最终整数计数=appWidgetIds.length;
for(int i=0;i            Intent intent = new Intent(this, MyProvider.class);
            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra("City", City);
            intent.putExtra("Temp", myTemp);
            sendBroadcast(intent);
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    Bundle bundle = intent.getExtras();

    if (bundle != null) {
         City = bundle.getString("City");
        Temperature = bundle.getInt("Temp");


        int appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
        AppWidgetManager appWidgetManager = AppWidgetManager
                .getInstance(context);
        RemoteViews remoteViews = updateWidgetListView(context, appWidgetId);

        appWidgetManager.updateAppWidget(currentWidgetId, remoteViews);

        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId,
                R.id.date);

    }