【问题标题】:How to send data through intent in android without opening another activity?如何在不打开另一个活动的情况下通过android中的意图发送数据?
【发布时间】:2013-03-17 21:52:26
【问题描述】:

这是我按意图发送数据的代码,但我不想打开另一个活动,我只想发送数据而不打开它..

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 只是发送数据...

【问题讨论】:

  • 然后你想发送什么数据?这对我来说毫无意义。
  • @sajmon 我正在发送此数据以显示在另一个活动中,但不想通过此活动打开它,现在对你有意义吗?
  • 现在是的对不起 >:) 你现在可以将值保存到 SharedPreferences 中,然后随时检索它们。
  • @Sajmon 你可以编写小代码以通过它在另一个活动中检索来保存吗?

标签: android android-intent android-activity


【解决方案1】:

是的,我也遇到过这个问题。

许多开发人员在通过 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();

为一个好的标准添加一些检查。

谢谢

【讨论】:

    【解决方案2】:

    你打电话也用SharedPreferences来存档

    【讨论】:

      【解决方案3】:

      您可能想使用Service 而不是活动。

      阅读: http://developer.android.com/guide/components/fundamentals.html#Components

      【讨论】:

        【解决方案4】:

        您可以尝试EventBusOtto Android 库在活动、服务和片段之间进行通信..

        所以你应该创建一个服务来传递数据并在活动、片段等之间使用事件总线进行通信

        【讨论】:

          猜你喜欢
          • 2014-09-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-06
          • 1970-01-01
          • 2017-08-14
          • 1970-01-01
          相关资源
          最近更新 更多