繁体   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