2013-08-17 48 views
1

什麼是’是用於startActivity()的意圖和用於sendBroadcast()方法的意圖之間的區別?在教程中,我找到了一種動態註冊廣播接收器的方法。爲此,我必須提供一個字符串作爲我的意圖名稱。如何在這種情況下選擇一個意向名稱並用於sendBroadcast()registerReceiver()android intents有什麼區別?

我應該在我的android_manifest.xml文件中添加一些東西嗎?根據教程,我目前宣佈這樣一個意圖名字:

private static final String SEARCH_ACTION = "com.example.usingwebservices.rest.SEARCH"; 
@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    unregisterReceiver(receiver); 
} 
@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 

    registerReceiver(receiver, new IntentFilter(SEARCH_ACTION)); 
} 
private BroadcastReceiver receiver = new BroadcastReceiver() { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // TODO Auto-generated method stub 
     if(progress!=null){ 
      progress.dismiss(); 
     } 
     String response = intent.getStringExtra(RestTask.HTTP_RESPONSE); 
     result.setText(response); 
    } 
}; 

回答

0

我認爲你做對了事。有兩種方法來註冊接收器,以下enter link description here

You can either dynamically register an instance of this class with Context.registerReceiver() or statically publish an implementation through the <receiver> tag in your AndroidManifest.xml. 

和消息服務也許像排隊:

Intent i = new Intent("com.example.usingwebservices.rest.SEARCH"); 
i.putExtra(RestTask.HTTP_RESPONSE, "msgdetails"); 
context.sendBroadcast(i); 

意圖的敷設渠道,參數是一個動作名稱:

Intent(String action) 

當使用startActivity時,我使用的結構:

Intent(Context packageContext, Class<?> cls) 

你可以看到參考以下here

我覺得谷歌想包最大的味精格式。

+0

因此,使用sendBroadcast()和registerReceiver()的相同操作名稱來完成廣播接收過程就足夠了嗎?或者我必須在其他地方註冊此操作名稱以獲得許可或任何其他目的。 –

+0

是的,你可以。 intent有兩個方法:setAction&setClass。但是我認爲可能將兩種類型的參數封裝到一個意圖中並不是一個好主意,除非它們實際上是同一個東西。 – BollMose