0

如果 RSS 提要(xml 文件)中存在任何新项目,我尝试编写一个代码来制作更新小部件(通知),因为我的应用程序是获取大学的新闻,一切都完成了,希望更新完成点击不在一段时间内!

更新小部件的快照:

在此处输入图像描述

更新服务代码(点击更新):

package com.example.testfeeds;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.IBinder;
import android.util.Log;
import android.webkit.WebView.FindListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;


public class UpdateWidgetService extends Service {

    private static final String LOG = "testwidgets";

    int numberOfItems=0;

    ArrayList<String> feedsPubDate;

      @SuppressWarnings("deprecation")
    @Override
      public void onStart(Intent intent, int startId) {
        Log.i(LOG, "Called");
        // Create some random data

        feedsPubDate=new ArrayList<String>(); 


        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this
            .getApplicationContext());

        int[] allWidgetIds = intent
            .getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS);

        ComponentName thisWidget = new ComponentName(getApplicationContext(),
            MyWidgetProvider.class);
        int[] allWidgetIds2 = appWidgetManager.getAppWidgetIds(thisWidget);
        Log.w(LOG, "From Intent" + String.valueOf(allWidgetIds.length));
        Log.w(LOG, "Direct" + String.valueOf(allWidgetIds2.length));

        for (int widgetId : allWidgetIds) {



///////////////////////////////////////////////////////////////////////////       

          RemoteViews remoteViews = new RemoteViews(this
              .getApplicationContext().getPackageName(),
              R.layout.widget_layout);

          try {
              numberOfItems=doTestFeed();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
          // Set the text
          remoteViews.setTextColor(R.id.textView1,Color.WHITE);
          remoteViews.setTextViewText(R.id.textView1,"  "+
              String.valueOf(numberOfItems));

          Log.w(LOG, String.valueOf(numberOfItems));


////////////////////////////////////////////////////////////////////////////          

          // Register an onClickListener
          Intent clickIntent = new Intent(this.getApplicationContext(),
              MyWidgetProvider.class);

          clickIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
          clickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
              allWidgetIds);

          PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, clickIntent,
              PendingIntent.FLAG_UPDATE_CURRENT);
          remoteViews.setOnClickPendingIntent(R.id.textView1, pendingIntent);
          appWidgetManager.updateAppWidget(widgetId, remoteViews);
        }
        stopSelf();

        super.onStart(intent, startId);
      }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }


    int doTestFeed() throws MalformedURLException, ParseException

    {  
        Log.d("msg"," in do test feed");

        InputStream is = null;
        int x = 0;

        URL myURL = new URL("http://yunn.yu.edu.jo/index.php?option=com_content&view=category&id=55&layout=blog&Itemid=104&format=feed&type=rss");
        try {
            URLConnection conn = myURL.openConnection();
             is = conn.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        XmlPullParserFactory pullParserFactory;

        try {
            pullParserFactory = XmlPullParserFactory.newInstance();
            XmlPullParser parser = pullParserFactory.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                parser.setInput(is, null);
                Log.d("msg","before making parsing");
                x=parseXML(parser);
                Log.d("msg","after making parsing");
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }


        Log.d("msg"," done testing");
        return x;
    }


//////////////////////////////////////////////////////////////////////////////////

    @SuppressLint("SimpleDateFormat")
    private int parseXML(XmlPullParser parser) throws XmlPullParserException,IOException, ParseException
    {

        Log.d("msg"," in parser");

        int eventType = parser.getEventType();
        int getElement=0;
        String pubDate=null;
        int numberOfItems=0;



        while (eventType != XmlPullParser.END_DOCUMENT){

            String tagName = null;


            switch (eventType){

            //----------------------------------//
            case XmlPullParser.START_DOCUMENT: 
                {
                    // do nothing
                }
                break;
           //----------------------------------//
             case XmlPullParser.START_TAG:
             { tagName = parser.getName();
                 if ("item".equals(tagName)){
                      getElement=1;
                 } else if (getElement!=0){

                      if ("pubDate".equals(tagName)){
                         pubDate= parser.nextText();
                         //String parsedPubDate [] = pubDate.split(" ");
                         feedsPubDate.add(pubDate);
                         Log.d("value",pubDate);
                     }
                 }
             }
                 break;                     
           //----------------------------------//
             case XmlPullParser.END_TAG:
             { tagName = parser.getName();
                 if (tagName.equalsIgnoreCase("item") && getElement != 0){

                 }
             }
                 break;

          //----------------------------------//


            }// end-switch.


            eventType= parser.next();

        }// end-while.

        int i=0;

        SharedPreferences sp = getSharedPreferences("tempData", 0);
        String dateStringA=sp.getString("recentPubDate", null);

        Log.d("oldest date",dateStringA);

        for(String s : feedsPubDate )

        {

        String dateStringB = feedsPubDate.get(i);
        SimpleDateFormat parserSDF = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
        Date dateA = parserSDF.parse(dateStringA);
        Date dateB = parserSDF.parse(dateStringB);
        if (dateA.compareTo(dateB) < 0) {
            Log.d("imp msg","one new item");
            numberOfItems++;
        }

        i++;

        }


        Log.d("update result", String.valueOf(numberOfItems));


      // Toast.makeText(GeneralNews.this,"The size of the list"+feedsTitles.size() , Toast.LENGTH_LONG).show();

   return numberOfItems;

    } //end xmlParser method.

//////////////////////////////////////////////////////////////////////////////////

}

小部件提供程序代码:

package com.example.testfeeds;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import java.util.Random;

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;

public class MyWidgetProvider extends AppWidgetProvider {

     private static final String LOG = "testwidgets";

      @Override
      public void onUpdate(Context context, AppWidgetManager appWidgetManager,
          int[] appWidgetIds) {

        Log.w(LOG, "onUpdate method called");
        // Get all ids
        ComponentName thisWidget = new ComponentName(context,
            MyWidgetProvider.class);
        int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

        // Build the intent to call the service
        Intent intent = new Intent(context.getApplicationContext(),
            UpdateWidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

        // Update the widgets via the service
        context.startService(intent);
      }

} 
4

1 回答 1

0

您应该创建一个小部件提供程序 xml 文件并在其中添加以下内容:

android:updatePeriodMillis="20000"
于 2013-08-18T19:13:48.663 回答