13

Context.startService安卓:啓動服務與Context.startService VS PendingIntent.getService

Intent intent = new Intent(context, MyService.class); 
context.startService(intent); 

PendingIntent.getService

Intent intent = new Intent(context, MyService.class); 
PendingIntent pi = PendingIntent.getService(context, 0, intent, 0); 
pi.send(); 


問題

  1. 什麼時候可以使用Context.startService和PendingIntent啓動服務?
  2. 爲什麼你會用另一個呢?

回答

18

確實沒有區別。

具體來說,上下文方法用於直接啓動它,因爲PendingIntent通常與通知一起使用,以便在用戶點擊該對象時激發此意圖,這會延遲到用戶點擊它(通常爲止)。然而;你通常不會直接發送PendingIntent,因爲這不是它的目的。

PendingIntent是一個意圖掛起,掛起,這意味着它的不是現在應該發生,但在不久的將來。而用意圖,它是在當下發送的。

如果PendingIntent在使用時沒有掛起,那麼它不再是PendingIntent,它實際上是一個Intent。 完全擊敗目的

+0

那麼,你有沒有想過用PendingIntent啓動服務? – 2012-02-07 23:19:18

+2

如果您想在不久的將來啓動服務,這將是理想的情況。假設我有一個通知,顯示用戶帳戶可用的新更新。理想情況下,會有一個掛起的意圖,建立連接到服務器並下載此信息。我希望在用戶點擊通知後立即完成,這樣我就等待用戶的方便,或者如果用戶不關心他們可以取消通知,並且下一個新更新將以同樣的方式作出反應。 – JoxTraex 2012-02-08 00:01:10

+0

很好的解釋,謝謝! – damluar 2014-06-02 11:22:11

1

PendinIntents非常用於小部件。由於正在運行的窗口小部件的佈局不屬於您的代碼,但它是在系統的控制下,您不能直接單擊監聽器來分配界面元素。相反,你指定的PendingIntent這些元素(如按鈕),因此當用戶觸摸它們時,是的PendingIntent「執行」,是這樣的:

// get the widget layout 
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.id.widget_layout); 

// prepare to listen the clicks on the refresh button 
Intent active = new Intent(context, WidgetCode.UpdateService.class); 
PendingIntent refreshPendingIntent = PendingIntent.getService(context, 0, active, 0); 
remoteViews.setOnClickPendingIntent(R.id.buttonWidgetRefresh, refreshPendingIntent); 

// send the changes to the widget 
AppWidgetManager.getInstance(context).updateAppWidget(appwidgetid, remoteViews); 

在這種情況下,在小部件的按鈕啓動的服務。通常你會在putExtras()中加入額外的信息,這樣服務將獲得任何需要的信息來完成它的工作。

+0

只需注意您必須在清單 中添加您的服務並添加export =「true」屬性其重要 – Lior 2017-12-28 21:57:39