为什么在IMarketBillingService之上提供其他服务?

时间:2012-01-15 16:43:09

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

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

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

为这个洋葱添加另一层有什么好处?

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

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

1 个答案:

答案 0 :(得分:1)

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

引用(http://developer.android.com/reference/android/app/Activity.html)说:

  

“如果活动暂停或停止,系统可以放弃活动   从记忆中要么完成要么完全杀死它   处理。当它再次显示给用户时,它必须完全显示   重新启动并恢复到之前的状态。“

例如,如果您调用RESTORE_TRANSACTIONS结算请求,则Android Market Service的响应可能需要一段时间才能到达。通过使用服务,您知道无论Activity Lifecycle如何,您都将始终处理响应。

只是为了好玩,我试着写一个小的测试应用程序并且确实感到惊讶。正在运行的线程可以在暂停或已停止的活动上调用方法。即使活动不在前台,线程也可以修改它的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");
    }
}
相关问题