2011-11-03 93 views
0

美好的一天,我有一個活動,我從appwidget上的圖標導航到使用待定內容的活動。一切都在服務課上完成。現在,該活動有一個刷新按鈕,當它按下時,它會發送一個調用服務上的onStart()方法的意圖來更新自身並執行一些Web操作。我如何去反映活動中服務可能發生的變化,而不是臨時存在活動。刷新和重新加載活動從服務而不退出活動,Android appwidget

服務到活動:

if(intent.getExtras()!= null){ 
     appWidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID); 

     //if i get this action from my detailedinfo class add a boolean to it 

     if(intent.getAction() == refresh_action){ 

    // boolean variable to hold condition 
      my_action = true; 
     } 



Intent forecast = new Intent(this,detailedInfo.class); 
    forecast.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); 
     forecast.putExtra("cityname", city); 

PendingIntent forecastIntent = PendingIntent.getActivity(this, 0, forecast, 0); 

     /*onclick to go to detailedInfo class*/ 
     remoteView.setOnClickPendingIntent(R.id.city_image_id, forecastIntent); 


     if(my_action == true){   
      //Log.d(TAG, "my_action is true, performing pending intent"); 

      try { 
       forecastIntent.send(this, 0, forecast); 
      } catch (CanceledException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

而且在活動類:

Intent service = new Intent(this, cityService.class); 
     service.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); 
     service.setAction(refresh_action); 
     Uri data = Uri.withAppendedPath(Uri.parse(CityWidgetProvider.URI_SCHEME + "://widget/id/"), String.valueOf(appWidgetId)); 
     service.setData(data); 
       startService(service); 

我嘗試添加一個的setAction()方法來調用服務,然後使用相同的PendingIntent(意圖即使我認爲是一個長鏡頭),但他們似乎被忽略。請如何處理這個問題,以及我可能做錯了什麼?像往常一樣,任何幫助都非常感謝。謝謝。

回答

1

我不是100%清楚你想要做什麼,但最簡單的做法是在Activity onResume中註冊BroadcastReceiver(在onPause中刪除它)。當服務完成後,無論它需要做什麼,廣播該信息。

在活動

public static final String ACTION_STRING = "THE_BIG_ACTION"; 
private BroadcastReceiver receiver = new BroadcastReceiver() { 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      // Do whatever you want here 
      Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT); 

     } 
    }; 

    @Override 
    protected void onResume() { 
     super.onResume(); 
     registerReceiver(receiver, new IntentFilter(ACTION_STRING)); 
    } 

    @Override 
    protected void onPause() { 
     super.onPause(); 
     unregisterReceiver(receiver); 
    } 

在服務上,當你做了,只需撥打...

sendBroadcast(new Intent(YourActivityClass.ACTION_STRING)); 

如果你想加入一些數據,只是把它的意圖就像您在開始活動時一樣。

如果您的活動在服務完成後關閉屏幕,並且用戶返回時,您將錯過了通知。這是一個需要解決的問題。

+0

對於遲到的回覆感到抱歉。有互聯網問題。非常感謝您的幫助,我認爲這將是一條路。無論如何,我的意思是,因爲點擊小部件中的圖標可以讓我通過服務訪問活動,我想刷新/更新信息並顯示活動中的更改,而無需退出活動。如果我按下刷新按鈕,我可以看到小部件中的更改和更新的數據。但我必須返回小部件並在查看活動中的更新信息之前單擊小部件圖標。 :-) – irobotxxx