在内容提供商中调用API以进行全局搜索

Dar*_*ian 6 android android-tv

我们正试图连接我们的AndroidTV应用程序,以将结果附加到全局搜索中.我遇到了一个问题,我无法通过api调用来获取结果,因为系统在主线程上调用了我的内容提供程序.

@Override
public Cursor query(Uri uri, String[] projection, String search, String[] selectionArgs, String searchOrder) {

    ... Logic here that calls the API using RxJava / Retrofit

    return cursor;
}


<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="@string/foo"
android:searchSettingsDescription="@string/foo_results"
android:includeInGlobalSearch="true"
android:searchSuggestAuthority="com.foo.search.provider"
android:searchSuggestIntentAction="android.intent.action.VIEW" />

<provider
   android:authorities="com.foo.search.provider"
   android:name=".search.GlobalSearchProvider"
   android:exported="true"/>
Run Code Online (Sandbox Code Playgroud)

当我进行全局搜索时,我可以看到ContentProvider#查询被调用.如果我尝试在当前线程上进行api调用,我会得到一个networkonmainthreadexception.

我试图通知数据已经改变的光标,但也没有成功.

getContext().getContentResolver().notifyChange(Uri.parse("content://com.foo.test"), null);
...
cursor.setNotificationUri(getContext().getContentResolver(), Uri.parse("content://com.foo.test"));
Run Code Online (Sandbox Code Playgroud)

无论如何,我可以强制操作系统在单独的线程上调用内容提供程序,或者至少通知搜索光标有新内容?

谢谢

nan*_*esh 6

其中一个解决方案是设置内容提供商流程

android:process:":androidtv"
Run Code Online (Sandbox Code Playgroud)

并在进行网络呼叫之前将ThreadPolicy设置为LAX

ThreadPolicy tp = ThreadPolicy.LAX;
StrictMode.setThreadPolicy(tp);
Run Code Online (Sandbox Code Playgroud)

通过在不同的进程中运行contentprovider,即使查询在主线程上运行,它也不会影响您的UI操作