четверг, 10 января 2013 г.

Мой погодный виджет

 Не так давно пришла зима и стало актуально заглядывать на сайты с погодой. И тут пришла идея моему мужу - написать мне виджет, который отображает текущую погоду нашего города с одного сайта. Почитала несколько статей и вот что вышло.
 Я предполагаю, что вы уже знаете как создавать проекты и поэтому переходим к созданию виджета.
AndroidManifest.xml. Просто заменяем все его содержимое на вот этот код:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 
      package="com.example.simpleactivity"
 
      android:versionCode="1"
      android:versionName="1.0">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
    <application android:icon="@drawable/fly" android:label="@string/app_name">
 
           <receiver android:name="SimpleActivity" >
                    <intent-filter>
                        <action android:name="ru.example.android.widget.ACTION_WIDGET_RECEIVER" />
                        <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                    </intent-filter>
                    <meta-data android:name="android.appwidget.provider" 
                     android:resource="@xml/manifest" />
        </receiver> 
    </application>
    <uses-sdk android:minSdkVersion="8"/>
</manifest>

SimpleActivity.java. Тут мы будем описывать реакции нашего виджета.
 
package com.example.simpleactivity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
 
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
 
public class SimpleActivity extends AppWidgetProvider {
 
 public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
 // Метод onUpdate вызывается при обновлении виджета. 
 @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
   //Создаем новый RemoteViews
         RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
 
         //Подготавливаем Intent для Broadcast
         Intent active = new Intent(context, SimpleActivity.class);
         active.setAction(ACTION_WIDGET_RECEIVER);
         //connect
         String msg = "";
         try {
   msg = GetDegree();
   } catch (Throwable e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   msg = "Error";
   }
         active.putExtra("msg", msg);
 
         //создаем наше событие
         PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
 
         //регистрируем наше событие
         remoteViews.setOnClickPendingIntent(R.id.button1, actionPendingIntent);
         remoteViews.setTextViewText(R.id.button1,msg+" C");
 
         //обновляем виджет
         appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
    } 
 
 //А в методе onReceive ловим наше «событие» и обрабатываем
 @Override
    public void onReceive(Context context, Intent intent) {
         //Ловим наш Broadcast, проверяем и выводим сообщение
         final String action = intent.getAction();
         if (ACTION_WIDGET_RECEIVER.equals(action)) {
              String msg = "null";
              try {
               msg = GetDegree();
              } catch(Throwable e) {
                    Log.e("Error", "msg = null");
                    msg = "empty";               
              }
              RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.main);
              updateViews.setTextViewText(R.id.button1,msg+" C");
//              
              ComponentName myComponentName = new ComponentName(context, SimpleActivity.class);
              AppWidgetManager manager = AppWidgetManager.getInstance(context);
              manager.updateAppWidget(myComponentName, updateViews);
         } 
 
         super.onReceive(context, intent);
    }
 
 //получить погоду
 protected String GetDegree() throws Throwable {
  String str_degree = "";
  String URL = "http://dove.opsb.ru/files/weather.js";
 
 //объект моего класса, который осуществляет интернет-запросы
  String [] res = new ConnectHttpGet().executeHttpGet(URL);
  if (res[1] == "200") {
   //pars
   int pos = res[0].indexOf(""");
   str_degree = res[0].substring(pos+1, res[0].length()-2);
  }else{
   str_degree = res[1];
  }
  return str_degree;
 }
}

Manifest.xml.  Теперь опишем наш виджет. Cоздаем папку "xml" в папке "res". В папке "xml" создаем файл manifest.xml, открываем его в редакторе и пишем следующий код:
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="294dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="1800000"
    android:initialLayout="@layout/main">
</appwidget-provider>
 
updatePeriodMillis - период обновления виджета в миллисекундах. 
Каждый раз по истечении этого промежутка времени срабатывает onUpdate метод.
 
Main.xml. Создаем шаблон виджета в папке "res/layout":
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/Widget" 
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="horizontal"
     android:gravity="center_vertical"
    >
 
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Погода" />
 
</RelativeLayout>
Вот и все. Полезные статьи:
http://habrahabr.ru/post/114515/
http://ondroid.info/delaem-vidzhet-dlya-rabochego-stola/
http://developer.android.com/guide/practices/ui_guidelines/widget_design.html http://developer.android.com/guide/topics/appwidgets/index.html

суббота, 5 января 2013 г.