2013-08-31 101 views
0

每隔一小時我有使用報警管理器的更新我的服務有問題,因爲我不知道真正的位置,把這個代碼豌豆:如何使用報警管理器更新服務的Android

SharedPreferences sp = getSharedPreferences("updateOptions", 0); 
     int updatePeriod=sp.getInt("UpdatePeriod", -1); 


     Calendar cal = Calendar.getInstance(); 

     Intent i = new Intent(this, UpdateWidgetService.class); 
     PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); 

     AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

     alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), updatePeriod, pintent); 

在事實上我的任務是通過新項目的總數如果在XML文件新項目(新聞源)來更新我的應用程序插件:

enter image description here

來執行我用2類:

1- UpdateWidgetService:

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.Calendar; 
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.AlarmManager; 
import android.app.PendingIntent; 
import android.app.Service; 
import android.appwidget.AppWidgetManager; 
import android.content.ComponentName; 
import android.content.Context; 
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 { 

    public static int numberOfItems=0; 



    //numberOfItems=0; 
    private static String LOG = "testwidgets"; 



    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>(); 


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


     SharedPreferences sp = getSharedPreferences("updateOptions", 0); 
     int updatePeriod=sp.getInt("UpdatePeriod", -1); 


     Calendar cal = Calendar.getInstance(); 

     Intent i = new Intent(this, UpdateWidgetService.class); 
     PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0); 

     AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE); 

     alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), updatePeriod, pintent); 





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


     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) { 
      // Create some random data 



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

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

      Log.d("numberOfItems intially", String.valueOf(numberOfItems)); 

       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.title3,Color.WHITE); 
      remoteViews.setTextViewText(R.id.title3," "+ 
       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.title3, 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; 






     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(); 

         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. 

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

} 

2- MyWidgetProvider:

package com.example.testfeeds; 

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

import java.util.Calendar; 
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); 
     } 

} 

結果是不正確:問題1 - >每秒更新服務被調用,而更新週期爲3600000毫秒! 問題2 - >一旦更新服務被稱爲「numberOfItems」加1!即使沒有項目的日期最新爲我的應用程序! 其實我不能指出邏輯錯誤!報警管理器的使用位置是問題嗎?

回答

2

只需使用Handler,見下圖:

private int mSampleDurationTime = 3600000; // 1 hour 
private boolean continueToRun = true; 

Handler mHandler = new Handler(); 

mHandler.postDelayed(mRunnable, mSampleDurationTime); 

其中mRunnable是你的任務:

private final Runnable mRunnable = new Runnable() { 

//... 
public void run() { 

    // do your stuff here, like update 
    // this block of code you going to reach every 1 hour 

    if(continueToRun == true){ 
    mHandler.postDelayed(mRunnable, mSampleDurationTime); 
    } 

} 
    ... 
}; 

你打電話postDelayed並調用new Runnable()第一次。之後,如果你想繼續, 調用相同的方法進run()

+0

在任何班級我應該把這個豌豆代碼?我如何通過使用此代碼更新小部件? – Akari

+1

您可以在主Activity或Service中使用處理程序。處理程序就像定時器,你可以在一段時間後運行任何命令 –

1

問題1 - >每秒更新服務被稱爲同時 更新週期是3600000毫秒

確定即

int updatePeriod = sp.getInt(「UpdatePeriod」,-1);

返回3600000?如果返回-1,這意味着你的UpdatePeriod已調用服務之前正確保存和setRepeating會被稱爲每cal.getTimeInMillis()意味着無休止地

problem 2 --> once the update service is called the "numberOfItems" incremented by one !! even if there are no items its dates newest for my app !! 嘗試,而不是這個

if (dateA.compareTo(dateB) <= 0) 

if (dateA.compareTo(dateB) < 0) 

和你一樣,我會用一個鬧鐘來調用AppWdiget的接收器。但是,如果計算時間存在錯誤(正如您所遇到的那樣),我使用Alarm#set而不是setRepeating來避免問題。 因此,每次我收到我的第一次報警的意圖,我設置了另外1個報警發生在now()+interval

+0

是它的-1 ...如何解決問題<<問題#1與此代碼 – Akari

+1

只是爲了測試你的報警管理器,如果它的工作與否,你可以使用int updatePeriod = sp.getInt(「UpdatePeriod」,3600000);所以如果UpdatePeriod首選項不存在,它將返回3600000 – ccheneson