简体   繁体   中英

Receiving value from an intent (Bundle) in a non activity class

I have two classes. A is a non-activity class, and B is an activity.

In Class A, I have declared

Intent intent = new Intent(xxxx.context, PDFRenderer.class);         
Bundle b = new Bundle();
b.putString("file", filePath);
intent.putExtras(b);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
xxxxx.context.startActivity(intent);

Then in Class B, i've put in a method that returns a boolean. I've put this in the OnCreate() method.

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    ama = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
    manager = getPackageManager();
    RenderPeeDeeEff(getIntent().getStringExtra("file"));

    i = new Intent(this, RenderPdf.class);
    Bundle b = new Bundle();
    b.putBoolean("returnValue", pdfCrashed);
    b.putString("pdfResult", pdfresult);
    i.putExtras(b);

    this.finish();
}

How do I pass the value of Bundle b back into class A even though I cannot use getIntent() since it's not an activity?

在您的情况下,我更喜欢使用SharedPreference :)

Couldn't you just have a method in class A such as setBundle(Bundle bundle) that you pass the bundle into? It really depends on the relationship that A and B have.

Somebody suggested SharedPreference, which might be good but the problem is your ClassA is not notified about the change made (assuming your ClassB is sort of Dialog). There are alternatives, such as registering a BroadcastReceiver in your ClassA, and in ClassB:

i = new Intent(this, ACTION_CLASSB_FINISH);
Bundle b = new Bundle();
b.putBoolean("returnValue", pdfCrashed);
b.putString("pdfResult", pdfresult);
i.putExtras(b);
this.sendBroadcast(i);

If you want to go for SharedPreference, you can register a Listener to listen to a change in the returnValue too. Notice both of the case you still need to have the Context in ClassA in order to register and also unregister if needed.

您可以在A类中有一个重载构造函数,该构造函数接受Bundle,使用该构造函数可以检索所需的值。

Use startActivityForResult.

In the Activity whose context you're using to call startActivityForResult, implement onActivityResult.

In onActivityResult, pass the Bundle from the returned Intent to A

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