1/*
2 * Copyright (C) 2008 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 */
16
17package com.android.settings;
18
19import android.app.Activity;
20import android.app.Dialog;
21import android.app.ProgressDialog;
22import android.content.BroadcastReceiver;
23import android.content.ContentResolver;
24import android.content.ContentUris;
25import android.content.ContentValues;
26import android.content.Context;
27import android.content.Intent;
28import android.content.IntentFilter;
29import android.database.Cursor;
30import android.net.Uri;
31import android.os.Bundle;
32import android.os.Handler;
33import android.os.HandlerThread;
34import android.os.Looper;
35import android.os.Message;
36import android.os.PersistableBundle;
37import android.os.UserHandle;
38import android.os.UserManager;
39import android.provider.Telephony;
40import android.support.v7.preference.Preference;
41import android.support.v7.preference.PreferenceGroup;
42import android.support.v7.preference.PreferenceScreen;
43import android.telephony.CarrierConfigManager;
44import android.telephony.SubscriptionInfo;
45import android.telephony.SubscriptionManager;
46import android.telephony.TelephonyManager;
47import android.text.TextUtils;
48import android.util.Log;
49import android.view.Menu;
50import android.view.MenuInflater;
51import android.view.MenuItem;
52import android.view.MotionEvent;
53import android.widget.TextView;
54import android.widget.Toast;
55
56import com.android.internal.logging.MetricsProto.MetricsEvent;
57import com.android.internal.telephony.PhoneConstants;
58import com.android.internal.telephony.TelephonyIntents;
59import com.android.internal.telephony.dataconnection.ApnSetting;
60import com.android.internal.telephony.uicc.IccRecords;
61import com.android.internal.telephony.uicc.UiccController;
62import com.android.settingslib.RestrictedLockUtils.EnforcedAdmin;
63
64import java.util.ArrayList;
65
66public class ApnSettings extends RestrictedSettingsFragment implements
67        Preference.OnPreferenceChangeListener {
68    static final String TAG = "ApnSettings";
69
70    public static final String EXTRA_POSITION = "position";
71    public static final String RESTORE_CARRIERS_URI =
72        "content://telephony/carriers/restore";
73    public static final String PREFERRED_APN_URI =
74        "content://telephony/carriers/preferapn";
75
76    public static final String APN_ID = "apn_id";
77    public static final String SUB_ID = "sub_id";
78    public static final String MVNO_TYPE = "mvno_type";
79    public static final String MVNO_MATCH_DATA = "mvno_match_data";
80
81    private static final int ID_INDEX = 0;
82    private static final int NAME_INDEX = 1;
83    private static final int APN_INDEX = 2;
84    private static final int TYPES_INDEX = 3;
85    private static final int MVNO_TYPE_INDEX = 4;
86    private static final int MVNO_MATCH_DATA_INDEX = 5;
87
88    private static final int MENU_NEW = Menu.FIRST;
89    private static final int MENU_RESTORE = Menu.FIRST + 1;
90
91    private static final int EVENT_RESTORE_DEFAULTAPN_START = 1;
92    private static final int EVENT_RESTORE_DEFAULTAPN_COMPLETE = 2;
93
94    private static final int DIALOG_RESTORE_DEFAULTAPN = 1001;
95
96    private static final Uri DEFAULTAPN_URI = Uri.parse(RESTORE_CARRIERS_URI);
97    private static final Uri PREFERAPN_URI = Uri.parse(PREFERRED_APN_URI);
98
99    private static boolean mRestoreDefaultApnMode;
100
101    private UserManager mUserManager;
102    private RestoreApnUiHandler mRestoreApnUiHandler;
103    private RestoreApnProcessHandler mRestoreApnProcessHandler;
104    private HandlerThread mRestoreDefaultApnThread;
105    private SubscriptionInfo mSubscriptionInfo;
106    private UiccController mUiccController;
107    private String mMvnoType;
108    private String mMvnoMatchData;
109
110    private String mSelectedKey;
111
112    private IntentFilter mMobileStateFilter;
113
114    private boolean mUnavailable;
115
116    private boolean mHideImsApn;
117    private boolean mAllowAddingApns;
118
119    public ApnSettings() {
120        super(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS);
121    }
122
123    private final BroadcastReceiver mMobileStateReceiver = new BroadcastReceiver() {
124        @Override
125        public void onReceive(Context context, Intent intent) {
126            if (intent.getAction().equals(
127                    TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
128                PhoneConstants.DataState state = getMobileDataState(intent);
129                switch (state) {
130                case CONNECTED:
131                    if (!mRestoreDefaultApnMode) {
132                        fillList();
133                    } else {
134                        showDialog(DIALOG_RESTORE_DEFAULTAPN);
135                    }
136                    break;
137                }
138            }
139        }
140    };
141
142    private static PhoneConstants.DataState getMobileDataState(Intent intent) {
143        String str = intent.getStringExtra(PhoneConstants.STATE_KEY);
144        if (str != null) {
145            return Enum.valueOf(PhoneConstants.DataState.class, str);
146        } else {
147            return PhoneConstants.DataState.DISCONNECTED;
148        }
149    }
150
151    @Override
152    protected int getMetricsCategory() {
153        return MetricsEvent.APN;
154    }
155
156    @Override
157    public void onCreate(Bundle icicle) {
158        super.onCreate(icicle);
159        final Activity activity = getActivity();
160        final int subId = activity.getIntent().getIntExtra(SUB_ID,
161                SubscriptionManager.INVALID_SUBSCRIPTION_ID);
162
163        mMobileStateFilter = new IntentFilter(
164                TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
165
166        setIfOnlyAvailableForAdmins(true);
167
168        mSubscriptionInfo = SubscriptionManager.from(activity).getActiveSubscriptionInfo(subId);
169        mUiccController = UiccController.getInstance();
170
171        CarrierConfigManager configManager = (CarrierConfigManager)
172                getSystemService(Context.CARRIER_CONFIG_SERVICE);
173        PersistableBundle b = configManager.getConfig();
174        mHideImsApn = b.getBoolean(CarrierConfigManager.KEY_HIDE_IMS_APN_BOOL);
175        mAllowAddingApns = b.getBoolean(CarrierConfigManager.KEY_ALLOW_ADDING_APNS_BOOL);
176        mUserManager = UserManager.get(activity);
177    }
178
179    @Override
180    public void onActivityCreated(Bundle savedInstanceState) {
181        super.onActivityCreated(savedInstanceState);
182
183        getEmptyTextView().setText(R.string.apn_settings_not_available);
184        mUnavailable = isUiRestricted();
185        setHasOptionsMenu(!mUnavailable);
186        if (mUnavailable) {
187            setPreferenceScreen(new PreferenceScreen(getPrefContext(), null));
188            getPreferenceScreen().removeAll();
189            return;
190        }
191
192        addPreferencesFromResource(R.xml.apn_settings);
193    }
194
195    @Override
196    public void onResume() {
197        super.onResume();
198
199        if (mUnavailable) {
200            return;
201        }
202
203        getActivity().registerReceiver(mMobileStateReceiver, mMobileStateFilter);
204
205        if (!mRestoreDefaultApnMode) {
206            fillList();
207        }
208    }
209
210    @Override
211    public void onPause() {
212        super.onPause();
213
214        if (mUnavailable) {
215            return;
216        }
217
218        getActivity().unregisterReceiver(mMobileStateReceiver);
219    }
220
221    @Override
222    public void onDestroy() {
223        super.onDestroy();
224
225        if (mRestoreDefaultApnThread != null) {
226            mRestoreDefaultApnThread.quit();
227        }
228    }
229
230    @Override
231    public EnforcedAdmin getRestrictionEnforcedAdmin() {
232        final UserHandle user = UserHandle.of(mUserManager.getUserHandle());
233        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS, user)
234                && !mUserManager.hasBaseUserRestriction(UserManager.DISALLOW_CONFIG_MOBILE_NETWORKS,
235                        user)) {
236            return EnforcedAdmin.MULTIPLE_ENFORCED_ADMIN;
237        }
238        return null;
239    }
240
241    private void fillList() {
242        final TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
243        final String mccmnc = mSubscriptionInfo == null ? ""
244            : tm.getSimOperator(mSubscriptionInfo.getSubscriptionId());
245        Log.d(TAG, "mccmnc = " + mccmnc);
246        StringBuilder where = new StringBuilder("numeric=\"" + mccmnc +
247                "\" AND NOT (type='ia' AND (apn=\"\" OR apn IS NULL)) AND user_visible!=0");
248
249        if (mHideImsApn) {
250            where.append(" AND NOT (type='ims')");
251        }
252
253        Cursor cursor = getContentResolver().query(Telephony.Carriers.CONTENT_URI, new String[] {
254                "_id", "name", "apn", "type", "mvno_type", "mvno_match_data"}, where.toString(),
255                null, Telephony.Carriers.DEFAULT_SORT_ORDER);
256
257        if (cursor != null) {
258            IccRecords r = null;
259            if (mUiccController != null && mSubscriptionInfo != null) {
260                r = mUiccController.getIccRecords(SubscriptionManager.getPhoneId(
261                        mSubscriptionInfo.getSubscriptionId()), UiccController.APP_FAM_3GPP);
262            }
263            PreferenceGroup apnList = (PreferenceGroup) findPreference("apn_list");
264            apnList.removeAll();
265
266            ArrayList<ApnPreference> mnoApnList = new ArrayList<ApnPreference>();
267            ArrayList<ApnPreference> mvnoApnList = new ArrayList<ApnPreference>();
268            ArrayList<ApnPreference> mnoMmsApnList = new ArrayList<ApnPreference>();
269            ArrayList<ApnPreference> mvnoMmsApnList = new ArrayList<ApnPreference>();
270
271            mSelectedKey = getSelectedApnKey();
272            cursor.moveToFirst();
273            while (!cursor.isAfterLast()) {
274                String name = cursor.getString(NAME_INDEX);
275                String apn = cursor.getString(APN_INDEX);
276                String key = cursor.getString(ID_INDEX);
277                String type = cursor.getString(TYPES_INDEX);
278                String mvnoType = cursor.getString(MVNO_TYPE_INDEX);
279                String mvnoMatchData = cursor.getString(MVNO_MATCH_DATA_INDEX);
280
281                ApnPreference pref = new ApnPreference(getPrefContext());
282
283                pref.setKey(key);
284                pref.setTitle(name);
285                pref.setSummary(apn);
286                pref.setPersistent(false);
287                pref.setOnPreferenceChangeListener(this);
288
289                boolean selectable = ((type == null) || !type.equals("mms"));
290                pref.setSelectable(selectable);
291                if (selectable) {
292                    if ((mSelectedKey != null) && mSelectedKey.equals(key)) {
293                        pref.setChecked();
294                    }
295                    addApnToList(pref, mnoApnList, mvnoApnList, r, mvnoType, mvnoMatchData);
296                } else {
297                    addApnToList(pref, mnoMmsApnList, mvnoMmsApnList, r, mvnoType, mvnoMatchData);
298                }
299                cursor.moveToNext();
300            }
301            cursor.close();
302
303            if (!mvnoApnList.isEmpty()) {
304                mnoApnList = mvnoApnList;
305                mnoMmsApnList = mvnoMmsApnList;
306
307                // Also save the mvno info
308            }
309
310            for (Preference preference : mnoApnList) {
311                apnList.addPreference(preference);
312            }
313            for (Preference preference : mnoMmsApnList) {
314                apnList.addPreference(preference);
315            }
316        }
317    }
318
319    private void addApnToList(ApnPreference pref, ArrayList<ApnPreference> mnoList,
320                              ArrayList<ApnPreference> mvnoList, IccRecords r, String mvnoType,
321                              String mvnoMatchData) {
322        if (r != null && !TextUtils.isEmpty(mvnoType) && !TextUtils.isEmpty(mvnoMatchData)) {
323            if (ApnSetting.mvnoMatches(r, mvnoType, mvnoMatchData)) {
324                mvnoList.add(pref);
325                // Since adding to mvno list, save mvno info
326                mMvnoType = mvnoType;
327                mMvnoMatchData = mvnoMatchData;
328            }
329        } else {
330            mnoList.add(pref);
331        }
332    }
333
334    @Override
335    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
336        if (!mUnavailable) {
337            if (mAllowAddingApns) {
338                menu.add(0, MENU_NEW, 0,
339                        getResources().getString(R.string.menu_new))
340                        .setIcon(android.R.drawable.ic_menu_add)
341                        .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
342            }
343            menu.add(0, MENU_RESTORE, 0,
344                    getResources().getString(R.string.menu_restore))
345                    .setIcon(android.R.drawable.ic_menu_upload);
346        }
347
348        super.onCreateOptionsMenu(menu, inflater);
349    }
350
351    @Override
352    public boolean onOptionsItemSelected(MenuItem item) {
353        switch (item.getItemId()) {
354        case MENU_NEW:
355            addNewApn();
356            return true;
357
358        case MENU_RESTORE:
359            restoreDefaultApn();
360            return true;
361        }
362        return super.onOptionsItemSelected(item);
363    }
364
365    private void addNewApn() {
366        Intent intent = new Intent(Intent.ACTION_INSERT, Telephony.Carriers.CONTENT_URI);
367        int subId = mSubscriptionInfo != null ? mSubscriptionInfo.getSubscriptionId()
368                : SubscriptionManager.INVALID_SUBSCRIPTION_ID;
369        intent.putExtra(SUB_ID, subId);
370        if (!TextUtils.isEmpty(mMvnoType) && !TextUtils.isEmpty(mMvnoMatchData)) {
371            intent.putExtra(MVNO_TYPE, mMvnoType);
372            intent.putExtra(MVNO_MATCH_DATA, mMvnoMatchData);
373        }
374        startActivity(intent);
375    }
376
377    @Override
378    public boolean onPreferenceTreeClick(Preference preference) {
379        int pos = Integer.parseInt(preference.getKey());
380        Uri url = ContentUris.withAppendedId(Telephony.Carriers.CONTENT_URI, pos);
381        startActivity(new Intent(Intent.ACTION_EDIT, url));
382        return true;
383    }
384
385    public boolean onPreferenceChange(Preference preference, Object newValue) {
386        Log.d(TAG, "onPreferenceChange(): Preference - " + preference
387                + ", newValue - " + newValue + ", newValue type - "
388                + newValue.getClass());
389        if (newValue instanceof String) {
390            setSelectedApnKey((String) newValue);
391        }
392
393        return true;
394    }
395
396    private void setSelectedApnKey(String key) {
397        mSelectedKey = key;
398        ContentResolver resolver = getContentResolver();
399
400        ContentValues values = new ContentValues();
401        values.put(APN_ID, mSelectedKey);
402        resolver.update(PREFERAPN_URI, values, null, null);
403    }
404
405    private String getSelectedApnKey() {
406        String key = null;
407
408        Cursor cursor = getContentResolver().query(PREFERAPN_URI, new String[] {"_id"},
409                null, null, Telephony.Carriers.DEFAULT_SORT_ORDER);
410        if (cursor.getCount() > 0) {
411            cursor.moveToFirst();
412            key = cursor.getString(ID_INDEX);
413        }
414        cursor.close();
415        return key;
416    }
417
418    private boolean restoreDefaultApn() {
419        showDialog(DIALOG_RESTORE_DEFAULTAPN);
420        mRestoreDefaultApnMode = true;
421
422        if (mRestoreApnUiHandler == null) {
423            mRestoreApnUiHandler = new RestoreApnUiHandler();
424        }
425
426        if (mRestoreApnProcessHandler == null ||
427            mRestoreDefaultApnThread == null) {
428            mRestoreDefaultApnThread = new HandlerThread(
429                    "Restore default APN Handler: Process Thread");
430            mRestoreDefaultApnThread.start();
431            mRestoreApnProcessHandler = new RestoreApnProcessHandler(
432                    mRestoreDefaultApnThread.getLooper(), mRestoreApnUiHandler);
433        }
434
435        mRestoreApnProcessHandler
436                .sendEmptyMessage(EVENT_RESTORE_DEFAULTAPN_START);
437        return true;
438    }
439
440    private class RestoreApnUiHandler extends Handler {
441        @Override
442        public void handleMessage(Message msg) {
443            switch (msg.what) {
444                case EVENT_RESTORE_DEFAULTAPN_COMPLETE:
445                    Activity activity = getActivity();
446                    if (activity == null) {
447                        mRestoreDefaultApnMode = false;
448                        return;
449                    }
450                    fillList();
451                    getPreferenceScreen().setEnabled(true);
452                    mRestoreDefaultApnMode = false;
453                    removeDialog(DIALOG_RESTORE_DEFAULTAPN);
454                    Toast.makeText(
455                        activity,
456                        getResources().getString(
457                                R.string.restore_default_apn_completed),
458                        Toast.LENGTH_LONG).show();
459                    break;
460            }
461        }
462    }
463
464    private class RestoreApnProcessHandler extends Handler {
465        private Handler mRestoreApnUiHandler;
466
467        public RestoreApnProcessHandler(Looper looper, Handler restoreApnUiHandler) {
468            super(looper);
469            this.mRestoreApnUiHandler = restoreApnUiHandler;
470        }
471
472        @Override
473        public void handleMessage(Message msg) {
474            switch (msg.what) {
475                case EVENT_RESTORE_DEFAULTAPN_START:
476                    ContentResolver resolver = getContentResolver();
477                    resolver.delete(DEFAULTAPN_URI, null, null);
478                    mRestoreApnUiHandler
479                        .sendEmptyMessage(EVENT_RESTORE_DEFAULTAPN_COMPLETE);
480                    break;
481            }
482        }
483    }
484
485    @Override
486    public Dialog onCreateDialog(int id) {
487        if (id == DIALOG_RESTORE_DEFAULTAPN) {
488            ProgressDialog dialog = new ProgressDialog(getActivity()) {
489                public boolean onTouchEvent(MotionEvent event) {
490                    return true;
491                }
492            };
493            dialog.setMessage(getResources().getString(R.string.restore_default_apn));
494            dialog.setCancelable(false);
495            return dialog;
496        }
497        return null;
498    }
499}
500