我正在使用PayPal MECL库:
由于显而易见的原因,我不想初始化PayPal库两次(每次活动一次),因为这需要时间并且不必要地让用户等待。
如何在两个活动之间共享对库的引用?
这是我的代码(目前在活动A和B中)(取自PayPal示例):
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
//Show PayPal-Button
initializePayPal();
}
public void initializePayPal() {
//Time to launch the library but first we need to initialize
setSupportProgressBarIndeterminateVisibility(true);
//Create a separate thread to do the initialization
Thread libraryInitializationThread = new Thread() {
public void run() {
//Initialize the library
initLibrary();
// The library is initialized so let's launch it by notifying our handler
if (PayPal.getInstance().isLibraryInitialized()) {
hRefresh.sendEmptyMessage(INITIALIZE_SUCCESS);
}
else {
hRefresh.sendEmptyMessage(INITIALIZE_FAILURE);
}
}
};
libraryInitializationThread.start();
}
private void initLibrary() {
// This is the main initialization call that takes in your Context, the Application ID, the server you would like to connect to, and your PayPalListener
PayPal.fetchDeviceReferenceTokenWithAppID(this, CompletePaymentActivity.appID, CompletePaymentActivity.server, new ResultDelegate());
// -- These are required settings.
PayPal.getInstance().setLanguage(SharedFunctions.getCurrentLocaleString()); // Sets the language for the library.
// --
}
// This handler will allow us to properly update the UI. You cannot touch Views from a non-UI thread.
Handler hRefresh = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case INITIALIZE_SUCCESS:
//We have initialized the application, close the dialog and show the PayPal Button
setSupportProgressBarIndeterminateVisibility(false);
showPayPalButton();
break;
case INITIALIZE_FAILURE:
//Initialization failure, close the dialog, update the page and show a toast
setSupportProgressBarIndeterminateVisibility(false);
Toast.makeText(mContext, mContext.getString(R.string.paypal_initialization_failed), Toast.LENGTH_LONG).show();
finish();
break;
}
}
};
public void showPayPalButton() {
//...
PayPal pp = PayPal.getInstance();
// get the checkoutbutton
launchPayPalButton = pp.getCheckoutButton(this, PayPal.BUTTON_194x37,
CheckoutButton.TEXT_PAY);
//...
}
答案 0 :(得分:0)
制作基本活动并将其扩展到其他活动。
在基础活动中,编写用于初始化paypal进程的代码或任何你想要做的事情。
public class BaseActivity extends Activity {
.....
.....
.....
}
public class ActivityA extends BaseActivity {
.....
.....
.....
}
答案 1 :(得分:0)
使用 singleton claas,在Class的构造函数中你可以初始化paypal库,并且可以随时随地使用它,它不会再次初始化,
答案 2 :(得分:0)
我最终声明了一个扩展Application
的类,我在那里初始化了一次库,并且可以被所有活动使用。