为什么IMarketBillingService之上的其他服务?

Bil*_*Ape 6 android android-service in-app-billing

谷歌的market_billing样品,只是像其他人一样为这一个,连接到远程服务IMarketBillingService,通过一个本地服务的包装,BillingService.

我知道服务具有在后台执行操作的优势,但IMarketBillingService不够远吗?

在洋葱上添加另一层有什么好处?

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

如果不建议IMarketBillingService直接在UI线程中连接到远程,可以BillingService用主活动中的另一个线程替换本地吗?

Gle*_*ech 1

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

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

“如果某个活动暂停或停止,系统可以通过要求其完成或简单地终止其进程来从内存中删除该活动。当它再次显示给用户时,它必须完全重新启动并恢复到之前的状态”。

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

只是为了好玩,我尝试编写一个小型测试应用程序,结果很惊讶。正在运行的线程可以调用暂停或停止的活动上的方法。即使 Activity 不在前台,线程也可以修改其 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");
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢+1 已经给出了很好的答案。对服务的需求在这里得到了很好的解释和例证*但是...*一个服务(`IMarketBillingService`)还不够吗?为什么是两个?为什么本地*和*远程? (2认同)