2014-01-16 20 views
0

束可以很容易地傳遞給新的活動,意圖:在創建之前將捆綁包發送到主/啓動器活動?

Intent intent = new Intent(this, DisplayMessageActivity.class); 
Bundle b = new Bundle(); 
// add extras... 
intent.putExtras(b); 
startActivity(intent); 

是否有可能使用軟件包(或類似)將數據發送到主要活動?

應用程序類創建before任何活動,我想用它來發送數據到主要活動。 我不想讓數據全局可訪問,或者在主要活動上使用靜態方法將數據傳遞給它。

+0

不確定你在做什麼。你需要明白'Application'類只在每個進程中創建一次。這意味着,當您第一次啓動您的應用程序時,將會創建Application類,然後是您的MainActivity。現在用戶按下BACK。你的MainActivity將完成。現在用戶再次啓動應用程序。如果進程沒有被回收(殺死),那麼Android將會創建並啓動一個新的'MainActivity'實例。 **它不會再次在'Application'類中調用'onCreate()'。** –

回答

1

既然你已經對應用程序的句柄,我只想用它來創建應用程序變量 -

public class MyApplication extends Application { 

    private String someVariable; 

    public String getSomeVariable() { 
     return someVariable; 
    } 

    public void setSomeVariable(String someVariable) { 
     this.someVariable = someVariable; 
    } 
} 

您必須聲明類在您的清單如下所示:

<application android:name="MyApplication" android:icon="@drawable/icon" android:label="@string/app_name"> 

然後在接收器的活動:

// set 
((MyApplication) this.getApplication()).setSomeVariable("foo"); 

// get 
String s = ((MyApplication) this.getApplication()).getSomeVariable(); 

作爲由Jeff Gilfelt在這裏解釋: Android global variable

+1

這不是我正在尋找的。任何活動都可以通過應用程序通過getApplication()訪​​問數據,正如你所說,這基本上是一個全局變量。我不想要一個全局變量。我只希望數據可用於主要活動。 – JustcallmeDrago

+0

我的不好,你原來的帖子裏有這個。 – cgcarter1

1

您是否考慮臨時使用SharedPreferences,然後刪除新活動的onCreate中的SharedPreferences數據。

一些示例代碼:

活動1:

SharedPreferences prefs = getSharedPreferences("mydata", 0); 
     SharedPreferences.Editor editor = prefs.edit(); 
     editor.putString("secretstring", "asdasdasdqwerty"); 
     editor.commit(); 

活性2:

SharedPreferences prefs = getSharedPreferences("mydata", 0); 
String savedString = prefs.getString("secretstring", ""); 

SharedPreferences prefs = getSharedPreferences("mydata", 0); 
      SharedPreferences.Editor editor = prefs.edit(); 
      editor.putString("secretstring", "nope"); 
      editor.commit(); 

第二種可能性是使用公共變量的getter和setter,但只有正確的變量返回到您的主要是通過檢查什麼課程要求它。

希望這有助於:)。

相關問題