简体   繁体   中英

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

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

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

Yes i have also faced this problem .

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.

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.

Thank you

你也可以使用SharedPreferences来实现这一目标

You probably want to use a Service not an activity.

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

You can try EventBus or Otto Android libraries to communicate between activities, services and fragments..

So you should create a Service to pass data and for communication between activities, fragments etc use an event bus

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM