如何在应用计费中创建单独的线程

时间:2017-06-08 16:47:20

标签: java android multithreading

我正在关注它所声明的android in app billing tutorial

  

警告:不要在主线程上调用getSkuDetails方法。调用此方法会触发可能阻止主线程的网络请求。相反,创建一个单独的线程并从该线程内部调用getSkuDetails方法。

代码如下:

 IInAppBillingService mService;

ServiceConnection mServiceConn = new ServiceConnection() {
    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
    }

    @Override
    public void onServiceConnected(ComponentName name,
                                   IBinder service) {
        mService = IInAppBillingService.Stub.asInterface(service);
        Intent serviceIntent =
                new Intent("com.android.vending.billing.InAppBillingService.BIND");
        serviceIntent.setPackage("com.android.vending");
        getActivity().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
        ArrayList<String> skuList = new ArrayList<String>();
        skuList.add("iap_one");
        Bundle querySkus = new Bundle();
        querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
        try {
            Bundle skuDetails = mService.getSkuDetails(3,
                    getActivity().getPackageName(), "inapp", querySkus);
            int response = skuDetails.getInt("RESPONSE_CODE");
            if (response == 0) {
                ArrayList<String> responseList
                        = skuDetails.getStringArrayList("DETAILS_LIST");

                for (String thisResponse : responseList) {
                    try {
                        JSONObject object = new JSONObject(thisResponse);
                        String sku = object.getString("productId");
                        String price = object.getString("price");
                        Log.d("Test Price", price);
                    } catch (JSONException e){
                        Log.e("MYAPP", "unexpected JSON exception", e);
                    }
                }
            }

        } catch (RemoteException e) {
            Log.e("MYAPP", "unexpected Remote exception", e);
        }

    }
};

1 个答案:

答案 0 :(得分:0)

您需要创建实现runnable的类,并通过构造函数插入所需的变量或使用asynctask类

class ImplementsRunnable implements Runnable {
  private myvar;

  public ImplementsRunnable(String myvar){
    this.myvar=myvar;
  } 

  public void run() {
     System.out.println("ImplementsRunnable : myvar: " + myvar);
  }

}