簡體   English   中英

如何通過android中的意圖發送數據而不打開另一個活動?

[英]How to send data through intent in android without opening another activity?

這是我的意圖發送數據的代碼,但我不想打開另一個活動我只想發送數據而不打開它..

Bundle contain = new Bundle();
            contain.putString("key4", item);
            contain.putString("price", price);

Intent a  = new Intent(Searchbydate.this, Searchbyitem.class);
            a.putExtras(contain);
            startActivity(a); 

在這里我不想打開這個Searchbyitem.class只是發送數據...

是的我也遇到過這個問題。

許多開發人員在通過Intent或Bundle將數據從對話框傳遞到另一個活動時也遇到了問題。 它在檢索時從另一個活動返回null。

唯一的解決方案是SharedPreferences。

但你必須將它放在解雇按鈕內。(例如:確定/取消等)

並通過相同的密鑰輕松地從另一個活動中檢索數據。 請勿使用廣播意圖后面的任何服務。

對話框活動中的代碼如下:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setIcon(R.drawable.mailicon);
    builder.setTitle(name);
    builder.setView(view);

    builder.setPositiveButton("Send Request",new DialogInterface.OnClickListener()
    {

     @Override 
     public void onClick(DialogInterface dialog,    int which) {
     String mailID = id.getText().toString();

     //Here define all your sharedpreferences code with key and value
     SharedPreferences prefs = getSharedPreferences("my_prefs", MODE_PRIVATE);
     SharedPreferences.Editor edit = prefs.edit();
     edit.putString("MID", mailID );
     edit.commit();

    }

});

從另一個獲取這樣的數據:

    SharedPreferences bb = getSharedPreferences("my_prefs", 0);
    String m = bb.getString("NUM", "");
    Toast.makeText(this, m, Toast.LENGTH_SHORT).show();

添加一些檢查以獲得良好的標准。

謝謝

你也可以使用SharedPreferences來實現這一目標

您可能希望使用Service而不是活動。

閱讀: http//developer.android.com/guide/components/fundamentals.html#Components

您可以嘗試使用EventBusOtto Android庫在活動,服務和片段之間進行通信。

因此,您應該創建一個服務來傳遞數據,並在活動,片段等之間進行通信,使用事件總線

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM