【问题标题】:Why another service on top of IMarketBillingService?为什么要在 IMarketBillingService 之上提供另一项服务?
【发布时间】:2012-01-19 04:07:31
【问题描述】:

Google 的market_billing sample 与其他this one 一样,通过本地 服务包装器BillingService 连接到远程 服务IMarketBillingService

我知道服务有后台做事的优势,但是远程IMarketBillingService还不够吗?

在这个洋葱上再添加一层有什么好处?

如果我尝试在 UI 线程中直接从我的主要活动连接到远程 IMarketBillingService,我会失去什么?

如果不建议直接在 UI 线程中连接远程 IMarketBillingService,是否可以将本地 BillingService 替换为 main Activity 中的另一个线程?

【问题讨论】:

    标签: android android-service in-app-billing


    【解决方案1】:

    当您的活动未运行时,本地 BillingService 处理来自 IMarketBillingService 的回调。

    参考资料 (http://developer.android.com/reference/android/app/Activity.html) 说:

    "如果一个活动被暂停或停止,系统可以丢弃该活动 通过要求它完成或简单地杀死它来从内存中 过程。当它再次显示给用户时,它必须是完整的 重新启动并恢复到之前的状态。”

    例如,如果您调用 RESTORE_TRANSACTIONS 计费请求,则来自 Android Market 服务的响应可能需要一些时间才能到达。通过使用服务,您知道无论活动生命周期如何,您都会随时处理响应。

    只是为了好玩,我尝试编写一个小型测试应用程序,结果很满意。正在运行的线程可以在暂停或停止的活动上调用方法。即使活动不在前台,线程也可以修改它的 UI。运行以下应用程序,按主屏幕停止应用程序。 10秒后返回,看到TextView变了……

    package com.example.playground;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    
    public class MyActivity extends Activity {
    
        private static String TAG = MyActivity.class.getName();
    
        /**
         * Called when the activity is first created.
         */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        Thread.sleep(10000);
                        someMethod();
                    } catch (InterruptedException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            });
            t.start();
        }
    
        private void someMethod() {
            Log.d(TAG, "Some method called");
            TextView tv = (TextView) findViewById(R.id.textfield);
            tv.setText("Called later");
        }
    }
    

    【讨论】:

    • 感谢 +1 提供了很好的答案。对服务的需求在此处得到了很好的解释和举例说明但是...一项服务 (IMarketBillingService) 还不够吗?为什么是两个?为什么本地 远程?
    • 如果您查看 IMarketBillingService,它被声明为公共接口 IMarketBillingService 扩展了 android.os.IInterface。这不是一个服务,只是一个用于与远程服务通信的存根,如果我没记错的话,它实际上是在 Android 市场应用程序中运行的。 Classe 名称中的“服务”部分令人困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    相关资源
    最近更新 更多