如何在不打开其他活动的情况下通过android中的intent发送数据?

如何在不打开其他活动的情况下通过android中的intent发送数据?

问题描述:

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

here is my code for sending data by intent but i don't want open another activity i just want to send the data without opening it..

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,仅发送数据...

here i don't want to open this Searchbyitem.class just send the data...

是的,我也遇到了这个问题.

Yes i have also faced this problem .

当通过Intent或Bundle将数据从对话框传递到另一个活动时,许多开发人员也遇到了问题.在从另一个活动检索时,它返回null.

Many developers also facing problems when passing data from dialog to another activity through Intent or Bundle. It returns null at the retrieving time from another activity.

唯一的解决方案是SharedPreferences.

And the only solution is SharedPreferences.

但是您必须将其放置在关闭按钮中.(例如:确定/取消等)

But you have to place it inside the dismiss button.( ex: ok/cancel etc)

并通过相同的键轻松地从另一个活动中检索数据.请勿在广播意图之后使用任何服务.

And retrieve the data from another activity easily through the same key. Do not use any service followed by broadcast intent .

对话框活动中的代码如下:

The code in dialog activity is like this:

    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();

    }

});

然后从另一个获取数据:

And from another fetch the data like this:

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

添加一些检查以确认是否合格.

Add some checkings for a good standard.

谢谢