我正在尝试使用来自google的apk扩展来下载我托管的扩展文件。我也在使用sampledownloadactivity中的代码来实现这一点,尽管它经过了一些修改以适合我的应用程序。
我的问题是下载从未启动过。在实现idownloadclient的类中,调用了onstart(),但没有调用onServiceConnectioned()。
我在DownloaderClientMarshaller中找到了这一行:

if( c.bindService(bindIntent, mConnection, Context.BIND_DEBUG_UNBIND) ) {

这总是返回false,因此服务没有绑定。
我在tabhost中使用调用活动,这给其他人带来了问题。他们说不能传递tabhost上下文,而应该将应用程序上下文传递给connect函数。我做了以下改变:
mDownloaderClientStub.connect(getApplicationContext());

而不是:
mDownloaderClientStub.connect(this);

但没用,我还是会弄错。如果有什么不同的话,我会在模拟器上做所有的测试。
我真的要把头发拉出来了。如果有人有任何想法,我将非常感激!

最佳答案

在大多数情况下,如果服务未在应用程序的清单文件中声明,bindService()方法返回false
在我的例子中,问题是我给了DownloaderClientMarshaller.CreateStub()方法错误的类对象。我不小心用了DownloaderService.class而不是MyDownloaderService.class
使用下载程序api时,请确保传递扩展baseDownloaderService的正确类对象。
我建议使用Better APK Expansion包中包含的更新的下载程序库。它修复了这个问题和其他问题,还提供了简化的api,最大限度地减少了向自己开枪的机会。
要接收下载进度,您只需扩展BroadcastDownloaderClient

public class SampleDownloaderActivity extends AppCompatActivity {
    private final DownloaderClient mClient = new DownloaderClient(this);

    // ...

    @Override
    protected void onStart() {
        super.onStart();
        mClient.register(this);
    }

    @Override
    protected void onStop() {
        mClient.unregister(this);
        super.onStop();
    }

    // ...

    class DownloaderClient extends BroadcastDownloaderClient {

        @Override
        public void onDownloadStateChanged(int newState) {
            if (newState == STATE_COMPLETED) {
                // downloaded successfully...
            } else if (newState >= 15) {
                // failed
                int message = Helpers.getDownloaderStringResourceIDFromState(newState);
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onDownloadProgress(DownloadProgressInfo progress) {
            if (progress.mOverallTotal > 0) {
                // receive the download progress
                // you can then display the progress in your activity
                String progress = Helpers.getDownloadProgressPercent(
                        progress.mOverallProgress, progress.mOverallTotal);
                Log.i("SampleDownloaderActivity", "downloading progress: " + progress);
            }
        }
    }

}

查看图书馆page的完整文档。

10-07 12:45
查看更多