【问题标题】:getOrCreateThreadId in API 21API 21 中的 getOrCreateThreadId
【发布时间】:2017-07-13 03:23:05
【问题描述】:

我目前正在开发一个面向 API 级别 21 的相当基本的消息传递应用程序。我不能再高了。在版本 21 (Android 5.0) 中替换 Threads.getOrCreateThreadId 方法(需要 API 23)的最简单方法是什么。

我的理解是该方法的第二个参数将接受电话号码,我这样想对吗?

这样做的目的是在 JavaScriptInterface 方法中使用,因为我使用 HTML 进行布局,因为它更容易使用。我也不想使用在 Android SDK 中不可见的 API。

【问题讨论】:

    标签: java android mobile sms


    【解决方案1】:

    经过一番谷歌搜索,我发现this compatibility class 具有我需要的功能。我复制了其中两个,稍微适应了我的需要。他们在这里:

    private static long getOrCreateThreadIdInternal(Context context, Set<String> recipients) {
        Uri.Builder uriBuilder = Uri.parse("content://mms-sms/threadID").buildUpon();
        for (String recipient : recipients) {
            /*if (isEmailAddress(recipient)) {
                recipient = extractAddrSpec(recipient);
            }*/
            uriBuilder.appendQueryParameter("recipient", recipient);
        }
        Uri uri = uriBuilder.build();
        Cursor cursor = query(context.getContentResolver(), uri, new String[] {BaseColumns._ID}, null, null, null);
        if (cursor != null) {
            try {
                if (cursor.moveToFirst()) {
                    return cursor.getLong(0);
                } else {
                    Log.e("JavaScriptInterface", "getOrCreateThreadId returned no rows!");
                }
            } finally {
                cursor.close();
            }
        }
        Log.e("JavaScriptInterface", "getOrCreateThreadId failed with uri " + uri.toString());
        throw new IllegalArgumentException("Unable to find or allocate a thread ID.");
    }
    
    private static Cursor query(ContentResolver resolver, Uri uri, String[] projection,
                                String selection, String[] selectionArgs, String sortOrder) {
        try {
            return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
        } catch (Exception e) {
            Log.e("JavaScriptInterface", "Catch an exception when query: ", e);
            return null;
        }
    }
    

    我不认为这段代码有任何功劳。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-05
      • 2018-09-24
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多