我正在使用 PayPal MECL 库来:
- 在活动 A 中显示“使用 PayPal 付款”按钮
- 在活动 B 中启动付款流程
出于显而易见的原因,我不想初始化 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);
//...
}