PayPalMECLライブラリを使用して次のことを行っています。
- アクティビティAの[PayPalで支払う]ボタンを表示します
- アクティビティBで支払いプロセスを開始します
明らかな理由で、PayPalライブラリを2回(アクティビティごとに1回)初期化するのは望ましくありません。これには時間がかかり、ユーザーが不必要に待機するためです。
2つのアクティビティ間でライブラリへの参照を共有するにはどうすればよいですか?
これは、現時点での私のコード(アクティビティ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);
//...
}