1/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.android.settings.applications;
17
18import android.content.ComponentName;
19import android.content.Context;
20import android.telephony.TelephonyManager;
21import android.text.TextUtils;
22import android.util.AttributeSet;
23
24import com.android.internal.telephony.SmsApplication;
25import com.android.internal.telephony.SmsApplication.SmsApplicationData;
26import com.android.settings.AppListPreference;
27
28import java.util.Collection;
29import java.util.Objects;
30
31public class DefaultSmsPreference extends AppListPreference {
32
33    public DefaultSmsPreference(Context context, AttributeSet attrs) {
34        super(context, attrs);
35
36        loadSmsApps();
37    }
38
39    private void loadSmsApps() {
40        Collection<SmsApplicationData> smsApplications =
41                SmsApplication.getApplicationCollection(getContext());
42
43        int count = smsApplications.size();
44        String[] packageNames = new String[count];
45        int i = 0;
46        for (SmsApplicationData smsApplicationData : smsApplications) {
47            packageNames[i++] = smsApplicationData.mPackageName;
48        }
49        setPackageNames(packageNames, getDefaultPackage());
50    }
51
52    private String getDefaultPackage() {
53        ComponentName appName = SmsApplication.getDefaultSmsApplication(getContext(), true);
54        if (appName != null) {
55            return appName.getPackageName();
56        }
57        return null;
58    }
59
60    @Override
61    protected boolean persistString(String value) {
62        if (!TextUtils.isEmpty(value) && !Objects.equals(value, getDefaultPackage())) {
63            SmsApplication.setDefaultApplication(value, getContext());
64        }
65        setSummary(getEntry());
66        return true;
67    }
68
69    public static boolean isAvailable(Context context) {
70        TelephonyManager tm =
71                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
72        return tm.isSmsCapable();
73    }
74
75}
76