/// M: Code analyze 013, fix bug, fix exception when press email add @{
  @Override
  public void startActivityForResult(Intent intent, int requestCode) {
    // requestCode >= 0 means the activity in question is a sub-activity.

    if (null != intent
        && null != intent.getData()
        && intent.getData().getScheme().equals("mailto")) {
      try {
        super.startActivityForResult(intent, requestCode);
      } catch (ActivityNotFoundException e) {
        MmsLog.w(TAG, "Failed to startActivityForResult: " + intent);
        Intent i =
            new Intent()
                .setClassName(
                    "com.android.email", "com.android.email.activity.setup.AccountSetupBasics");
        this.startActivity(i);
        finish();
      } catch (Exception e) {
        MmsLog.e(TAG, "Failed to startActivityForResult: " + intent);
        Toast.makeText(this, getString(R.string.message_open_email_fail), Toast.LENGTH_SHORT)
            .show();
      }
    } else {
      super.startActivityForResult(intent, requestCode);
    }
  }
  // update the channel list ui by channel array
  private void updateChannelUIList() {
    MmsLog.d(LOG_TAG, "updateChannelUIList start");
    mChannelListPreference.removeAll();
    int length = mChannelArray.size();
    for (int i = 0; i < length; i++) {
      Preference channel = new Preference(this);
      int keyId = mChannelArray.get(i).getKeyId();
      String channelName = mChannelArray.get(i).getChannelName();
      int channelId = mChannelArray.get(i).getChannelId();
      boolean channelState = mChannelArray.get(i).getChannelState();
      String title = channelName + "(" + String.valueOf(channelId) + ")";
      channel.setTitle(title);
      final CellBroadcastChannel oldChannel =
          new CellBroadcastChannel(keyId, channelId, channelName, channelState);
      if (channelState) {
        channel.setSummary(R.string.enable);
      } else {
        channel.setSummary(R.string.disable);
      }

      channel.setOnPreferenceClickListener(
          new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference arg0) {
              showEditChannelDialog(oldChannel);
              return false;
            }
          });
      mChannelListPreference.addPreference(channel);
    }
    MmsLog.d(LOG_TAG, "updateChannelUIList end");
  }
 // reason=true means get config when init.
 // reason=false means get config after update
 private void getCellBroadcastConfig() {
   MmsLog.d(LOG_TAG, "getCellBroadcastConfig start");
   onStarted(mLanguagePreference, true);
   SmsBroadcastConfigInfo[] info = EncapsulatedSmsManager.getCellBroadcastSmsConfig(mSlotId);
   handleGetCellBroadcastConfigResponse(info);
   MmsLog.d(LOG_TAG, "getCellBroadcastConfig end");
 }
 private boolean queryChannelFromDatabase() {
   MmsLog.d(LOG_TAG, "queryChannelFromDatabase start");
   clearChannel();
   String[] projection = new String[] {KEYID, NAME, NUMBER, ENABLE};
   Cursor cursor = null;
   try {
     cursor = this.getContentResolver().query(mUri, projection, null, null, null);
     if (cursor != null) {
       while (cursor.moveToNext()) {
         CellBroadcastChannel channel = new CellBroadcastChannel();
         channel.setChannelId(cursor.getInt(2));
         channel.setKeyId(cursor.getInt(0));
         channel.setChannelName(cursor.getString(1));
         channel.setChannelState(cursor.getInt(3) == 1);
         mChannelArray.add(channel);
       }
     }
   } catch (IllegalArgumentException e) {
     return false;
   } finally {
     cursor.close();
   }
   MmsLog.d(LOG_TAG, "queryChannelFromDatabase end");
   return true;
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (isGeminiSupport()) {
      mSlotId = getIntent().getIntExtra(EncapsulatedPhone.GEMINI_SIM_ID_KEY, -1);
      switch (mSlotId) {
        case EncapsulatedPhone.GEMINI_SIM_1:
          mUri = CHANNEL_URI;
          break;
        case EncapsulatedPhone.GEMINI_SIM_2:
          mUri = CHANNEL_URI1;
          break;
        case EncapsulatedPhone.GEMINI_SIM_3:
          mUri = CHANNEL_URI2;
          break;
        case EncapsulatedPhone.GEMINI_SIM_4:
          mUri = CHANNEL_URI3;
          break;
        default:
          MmsLog.d(LOG_TAG, "error no sim id matched with mSlotId = " + mSlotId);
          break;
      }
    }
    MmsLog.d("CellBroadcastSetting", "Sim Id : " + mSlotId);

    addPreferencesFromResource(R.xml.cell_broadcast_settings);
    initPreference();
    initLanguage();
    registerForContextMenu(this.getListView());

    IntentFilter intentFilter =
        new IntentFilter(EncapsulatedTelephonyIntents.ACTION_SIM_INFO_UPDATE);
    registerReceiver(mReceiver, intentFilter);
  }
 private void setCellBroadcastConfig(SmsBroadcastConfigInfo[] objectList) {
   MmsLog.d(LOG_TAG, "setCellBroadcastConfig start");
   onStarted(mLanguagePreference, false);
   boolean isSetConfigSuccess =
       EncapsulatedSmsManager.setCellBroadcastSmsConfig(objectList, objectList, mSlotId);
   handleSetCellBroadcastConfigResponse(isSetConfigSuccess);
   MmsLog.d(LOG_TAG, "setCellBroadcastConfig end isSetConfigSuccess =" + isSetConfigSuccess);
 }
 private void dumpConfigInfo(SmsBroadcastConfigInfo info) {
   MmsLog.d(LOG_TAG, "dump start for " + info.toString());
   MmsLog.d(
       LOG_TAG,
       "FromServiceId " + info.getFromServiceId() + "  ToServiceId " + info.getToServiceId());
   MmsLog.d(
       LOG_TAG, "FromCodeId " + info.getFromCodeScheme() + "  ToCodeId " + info.getToCodeScheme());
   MmsLog.d(LOG_TAG, "dump end for " + info.toString());
 }
 /// M: Code analyze 004, new feature, Slideshow Plugin(unknown) @{
 private void initPlugin(Context context) {
   try {
     mMmsSlideShowPlugin =
         (IMmsSlideShow)
             EncapsulatedPluginManager.createPluginObject(context, IMmsSlideShow.class.getName());
     MmsLog.d(TAG, "operator mMmsSlideShowPlugin = " + mMmsSlideShowPlugin);
   } catch (AndroidException e) {
     mMmsSlideShowPlugin = new MmsSlideShowImpl(context);
     MmsLog.d(TAG, "default mMmsSlideShowPlugin = " + mMmsSlideShowPlugin);
   }
 }
  /// M:Code analyze 011,add for setting the mms being downloading when shutdown to unrecognized
  /// after boot complete again,have to manual download @{
  public static void setNotificationIndUnstarted(final Context context) {
    MmsLog.d(MmsApp.TXN_TAG, "setNotificationIndUnstarted");
    Cursor cursor =
        SqliteWrapper.query(
            context,
            context.getContentResolver(),
            Mms.CONTENT_URI,
            new String[] {Mms._ID, Mms.STATUS},
            Mms.MESSAGE_TYPE + "=" + PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND,
            null,
            null);
    if (cursor != null) {
      try {
        int count = cursor.getCount();
        MmsLog.d(MmsApp.TXN_TAG, "setNotificationIndUnstarted: Message Size=" + count);

        if (count == 0) {
          return;
        }

        ContentValues values = null;
        int id = 0;
        int status = 0;
        while (cursor.moveToNext()) {
          id = cursor.getInt(0);
          status = cursor.getInt(1);
          MmsLog.d(
              MmsApp.TXN_TAG, "setNotificationIndUnstarted: MsgId=" + id + "; status=" + status);

          if (DownloadManager.STATE_DOWNLOADING == (status & ~DownloadManager.DEFERRED_MASK)) {
            values = new ContentValues(1);
            values.put(Mms.STATUS, PduHeaders.STATUS_UNRECOGNIZED);
            SqliteWrapper.update(
                context,
                context.getContentResolver(),
                Mms.CONTENT_URI,
                values,
                Mms._ID + "=" + id,
                null);
          }
        }
      } catch (SQLiteDiskIOException e) {
        // Ignore
        MmsLog.e(
            MmsApp.TXN_TAG, "SQLiteDiskIOException caught while set notification ind unstart", e);
      } finally {
        cursor.close();
      }
    } else {
      MmsLog.d(MmsApp.TXN_TAG, "setNotificationIndUnstarted: no pending messages.");
    }
  }
  /// M:Code analyze 009,add for setting the pending mms failed,mainly using after boot complete @{
  public static void setPendingMmsFailed(final Context context) {
    MmsLog.d(MmsApp.TXN_TAG, "setPendingMmsFailed");
    Cursor cursor =
        PduPersister.getPduPersister(context)
            .getPendingMessages(Long.MAX_VALUE /*System.currentTimeMillis()*/);
    if (cursor != null) {
      try {
        int count = cursor.getCount();
        MmsLog.d(MmsApp.TXN_TAG, "setPendingMmsFailed: Pending Message Size=" + count);

        if (count == 0) {
          return;
        }
        DefaultRetryScheme scheme = new DefaultRetryScheme(context, 100);
        ContentValues values = null;
        int columnIndex = 0;
        int columnType = 0;
        int id = 0;
        int type = 0;
        while (cursor.moveToNext()) {
          columnIndex = cursor.getColumnIndexOrThrow(PendingMessages._ID);
          id = cursor.getInt(columnIndex);

          columnType = cursor.getColumnIndexOrThrow(PendingMessages.MSG_TYPE);
          type = cursor.getInt(columnType);

          MmsLog.d(MmsApp.TXN_TAG, "setPendingMmsFailed: type=" + type + "; MsgId=" + id);

          if (type == PduHeaders.MESSAGE_TYPE_SEND_REQ) {
            values = new ContentValues(2);
            values.put(PendingMessages.ERROR_TYPE, MmsSms.ERR_TYPE_GENERIC_PERMANENT);
            values.put(PendingMessages.RETRY_INDEX, scheme.getRetryLimit());
            SqliteWrapper.update(
                context,
                context.getContentResolver(),
                PendingMessages.CONTENT_URI,
                values,
                PendingMessages._ID + "=" + id,
                null);
          }
        }
      } catch (SQLiteDiskIOException e) {
        // Ignore
        MmsLog.e(
            MmsApp.TXN_TAG, "SQLiteDiskIOException caught while set pending message failed", e);
      } finally {
        cursor.close();
      }
    } else {
      MmsLog.d(MmsApp.TXN_TAG, "setPendingMmsFailed: no pending MMS.");
    }
  }
 @SuppressWarnings("deprecation")
 @Override
 protected void onPreExecute() {
   if (CellBroadcastSettings.this.isDestroyed() || CellBroadcastSettings.this.isFinishing()) {
     MmsLog.d(LOG_TAG, "onPreExecute, activity is finished, do nothing");
     return;
   }
   updateStatus(false);
   dismissProgressDialog();
   mLoadDialog = new ProgressDialog(CellBroadcastSettings.this);
   mLoadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
   mLoadDialog.setCanceledOnTouchOutside(false);
   mLoadDialog.setOnDismissListener(
       new OnDismissListener() {
         @Override
         public void onDismiss(DialogInterface dialog) {
           /// For ALPS00949190. @{
           // May be the mCellBroadcastAsyncTask has been null after
           // Activity onStop->onStart->onResume and call
           // handleGetCellBroadcastConfigResponse.
           if (mCellBroadcastAsyncTask != null) {
             mCellBroadcastAsyncTask.cancel(true);
             mCellBroadcastAsyncTask = null;
           }
           /// @}
         }
       });
   mLoadDialog.show();
 }
  public void setAudio(Uri audio, String name, Map<String, ?> extras) {
    synchronized (this) {
      mAudioUri = audio;
    }

    mNameView.setText(name);
    mAlbumView.setText((String) extras.get("album"));
    mArtistView.setText((String) extras.get("artist"));
    String extName = name.substring(name.lastIndexOf('.') + 1);
    Bitmap bitmap =
        BitmapFactory.decodeResource(mContext.getResources(), R.drawable.ic_launcher_record_audio);
    if (extName.equals("dcf")) {
      MmsLog.i(TAG, "contain drm audio");
      if (EncapsulatedFeatureOption.MTK_DRM_APP) {
        Drawable front = getResources().getDrawable(EncapsulatedR.drawable.drm_red_lock);
        EncapsulatedDrmManagerClient drmManager = new EncapsulatedDrmManagerClient(mContext);
        Bitmap drmBitmap = drmManager.overlayBitmap(bitmap, front);
        mAudioImageView.setImageBitmap(drmBitmap);
        if (bitmap != null && !bitmap.isRecycled()) {
          bitmap.recycle();
          bitmap = null;
        }
      } else {
        mAudioImageView.setImageBitmap(bitmap);
      }
    } else {
      mAudioImageView.setImageBitmap(bitmap);
    }
  }
  private void updateChannelsWithSingleConfig(SmsBroadcastConfigInfo info) {
    int channelBeginIndex = info.getFromServiceId();
    int channelEndIndex = info.getToServiceId();
    boolean state = info.isSelected();
    MmsLog.d(LOG_TAG, "updateChannelsWithSingleConfig STATE = " + state);

    if (channelBeginIndex != -1) {
      for (int j = channelBeginIndex; j <= channelEndIndex; j++) {
        if (mCellBroadcastAsyncTask.isCancelled()) {
          break;
        }
        String jStr = String.valueOf(j);
        CellBroadcastChannel channel = getChannelObjectFromKey(jStr);
        if (channel != null) {
          channel.setChannelState(state);
        } else {
          // add a new channel to dataBase while the channel doesn't exists
          String tName = getString(R.string.cb_default_new_channel_name) + jStr;
          CellBroadcastChannel newChannel = new CellBroadcastChannel(j, tName, state);
          if (!insertChannelToDatabase(newChannel)) {
            showUpdateDBErrorInfoDialog();
          }
          mChannelArray.add(newChannel);
          mChannelMap.put(jStr, newChannel);
        }
      }
    }
  }
 private void updateLanguagesWithSingleConfig(SmsBroadcastConfigInfo info) {
   int languageBeginIndex = info.getFromCodeScheme();
   int languageEndIndex = info.getToCodeScheme();
   if (languageBeginIndex != -1 && languageBeginIndex != -2) {
     for (int j = languageBeginIndex; j <= languageEndIndex; j++) {
       if (mCellBroadcastAsyncTask.isCancelled()) {
         break;
       }
       CellBroadcastLanguage language = getLanguageObjectFromKey(String.valueOf(j));
       if (language != null) {
         language.setLanguageState(info.isSelected());
       }
     }
   } else {
     MmsLog.d(LOG_TAG, "Select all language!");
     if (languageBeginIndex == -2 && languageEndIndex == -2) {
       for (int i = 0; i < mLanguageList.size(); i++) {
         if (mCellBroadcastAsyncTask.isCancelled()) {
           break;
         }
         CellBroadcastLanguage language = (CellBroadcastLanguage) mLanguageList.get(i);
         CellBroadcastLanguage lang =
             getLanguageObjectFromKey(String.valueOf(language.getLanguageId()));
         if (lang != null) {
           lang.setLanguageState(true);
         }
       }
     }
   }
 }
 private static void handleSimHotSwap(Activity activity, int slotId) {
   List<EncapsulatedSimInfoManager> temp =
       EncapsulatedSimInfoManager.getInsertedSimInfoList(activity);
   MmsLog.d(LOG_TAG, "slot id = " + slotId);
   if (getSiminfoIdBySimSlotId(slotId, temp) == UNDEFINED_SLOT_ID) {
     activity.finish();
   }
 }
  /// @}
  /// M:Code analyze 008, add for gemini,start transaction service @{
  private static void wakeUpServiceGemini(Context context, int simId) {
    MmsLog.v(MmsApp.TXN_TAG, "wakeUpServiceGemini: start transaction service ... simId=" + simId);

    Intent it = new Intent(context, TransactionService.class);
    it.putExtra(EncapsulatedPhone.GEMINI_SIM_ID_KEY, simId);

    context.startService(it);
  }
 @Override
 public void onReceive(Context context, Intent intent) {
   String action = intent.getAction();
   MmsLog.d(LOG_TAG, "[action = " + action + "]");
   if (EncapsulatedTelephonyIntents.ACTION_SIM_INFO_UPDATE.equals(action)) {
     /// M: add for hot swap {
     handleSimHotSwap(CellBroadcastSettings.this, mSlotId);
     /// @}
   }
 }
 @Override
 protected Void doInBackground(Void... params) {
   MmsLog.d(LOG_TAG, "task is working");
   if (queryChannelFromDatabase()) {
     initChannelMap();
     updateCurrentChannelAndLanguage(mList);
   } else {
     showUpdateDBErrorInfoDialog();
   }
   return null;
 }
 private boolean updateChannelToDatabase(
     CellBroadcastChannel oldChannel, CellBroadcastChannel newChannel) {
   MmsLog.d(LOG_TAG, "updateChannelToDatabase start oldChannel =" + oldChannel);
   String[] projection = new String[] {KEYID, NAME, NUMBER, ENABLE};
   final int id = newChannel.getKeyId();
   final String name = newChannel.getChannelName();
   final boolean enable = newChannel.getChannelState();
   final int number = newChannel.getChannelId();
   ContentValues values = new ContentValues();
   values.put(KEYID, id);
   values.put(NAME, name);
   values.put(NUMBER, number);
   values.put(ENABLE, Integer.valueOf(enable ? 1 : 0));
   String where = KEYID + "=" + oldChannel.getKeyId();
   try {
     int lines = this.getContentResolver().update(mUri, values, where, null);
   } catch (IllegalArgumentException e) {
     return false;
   }
   MmsLog.d(LOG_TAG, "updateChannelToDatabase end newChannel =" + newChannel);
   return true;
 }
 public static void unRegisterForConnectionStateChanges(Context context) {
   /// M:
   MmsLog.d(MmsApp.TXN_TAG, "unRegisterForConnectionStateChanges");
   if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
     Log.v(TAG, "unRegisterForConnectionStateChanges");
   }
   if (sMmsSystemEventReceiver != null) {
     try {
       context.unregisterReceiver(sMmsSystemEventReceiver);
     } catch (IllegalArgumentException e) {
       // Allow un-matched register-unregister calls
     }
   }
 }
 private boolean insertChannelToDatabase(CellBroadcastChannel channel) {
   ContentValues values = new ContentValues();
   values.put(NAME, channel.getChannelName());
   values.put(NUMBER, channel.getChannelId());
   values.put(ENABLE, channel.getChannelState());
   try {
     Uri uri = getContentResolver().insert(mUri, values);
     int insertId = Integer.valueOf(uri.getLastPathSegment());
     channel.setKeyId(insertId);
     MmsLog.d(LOG_TAG, "insertChannelToDatabase(), insertId: " + insertId);
   } catch (IllegalArgumentException e) {
     return false;
   }
   return true;
 }
 private void setCheckedAlllanguageItem(
     final boolean[] temp, boolean isChecked, AlertDialog languageDialog) {
   boolean alllanguage = true;
   for (int i = 1; i < temp.length; ++i) {
     if (!temp[i]) {
       alllanguage = false;
       break;
     }
   }
   MmsLog.d(LOG_TAG, "All language alllanguage " + alllanguage);
   if (alllanguage) {
     ListView items = languageDialog.getListView();
     items.setItemChecked(0, isChecked);
     temp[0] = true;
   }
 }
  public static void registerForConnectionStateChanges(Context context) {
    /// M:
    MmsLog.d(MmsApp.TXN_TAG, "registerForConnectionStateChanges");
    unRegisterForConnectionStateChanges(context);

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED);
    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
      Log.v(TAG, "registerForConnectionStateChanges");
    }
    if (sMmsSystemEventReceiver == null) {
      sMmsSystemEventReceiver = new MmsSystemEventReceiver();
    }

    context.registerReceiver(sMmsSystemEventReceiver, intentFilter);
  }
 @Override
 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
   super.onCreateContextMenu(menu, v, menuInfo);
   AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
   if (info == null) {
     MmsLog.i(LOG_TAG, "onCreateContextMenu,menuInfo is null");
     return;
   }
   int position = info.position;
   if (position >= 3) {
     int index = position - 3;
     CellBroadcastChannel channel = mChannelArray.get(index);
     String channelName = channel.getChannelName();
     menu.setHeaderTitle(channelName);
     if (channel.getChannelState()) {
       menu.add(0, MENU_CHANNEL_ENABLE_DISABLE, 0, R.string.disable);
     } else {
       menu.add(0, MENU_CHANNEL_ENABLE_DISABLE, 0, R.string.enable);
     }
     menu.add(1, MENU_CHANNEL_EDIT, 0, R.string.cb_menu_edit);
     menu.add(2, MENU_CHANNEL_DELETE, 0, R.string.cb_menu_delete);
   }
 }
 @Override
 protected void onCancelled() {
   MmsLog.d(LOG_TAG, "cancel task");
   updateUI();
   super.onCancelled();
 }
  private void showLanguageSelectDialog() {
    final boolean[] temp = new boolean[LANGUAGE_NUM];
    final boolean[] temp2 = new boolean[LANGUAGE_NUM];
    boolean allLanguagesFlag = true;
    for (int i = 1; i < temp.length; i++) {
      CellBroadcastLanguage tLanguage = mLanguageList.get(i);
      if (tLanguage != null) {
        MmsLog.d(LOG_TAG, "language status " + tLanguage.getLanguageState());
        temp[i] = tLanguage.getLanguageState();
        temp2[i] = tLanguage.getLanguageState();
      } else {
        MmsLog.i(LOG_TAG, "showLanguageSelectDialog() init the language list failed when i=" + i);
      }
      if (!temp[i]) {
        allLanguagesFlag = false; // not select all languages
      }
    }
    // init "All Languages" selection
    MmsLog.d(LOG_TAG, "All language status " + allLanguagesFlag);
    mLanguageList.get(0).setLanguageState(allLanguagesFlag);
    temp[0] = allLanguagesFlag;
    temp2[0] = allLanguagesFlag;
    final AlertDialog.Builder dlgBuilder = new AlertDialog.Builder(this);
    dlgBuilder.setTitle(getString(R.string.cb_dialog_title_language_choice));
    dlgBuilder.setPositiveButton(
        R.string.ok,
        new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton) {
            int tLength = temp.length;
            // if select "all languages"
            if (temp[0]) {
              for (int i = 0; i < tLength; i++) {
                temp[i] = true;
              }
            }
            // select a language at least
            boolean flag = false;
            for (int i = 0; i < tLength; i++) {
              mLanguageList.get(i).setLanguageState(temp[i]);
              if (temp[i]) {
                flag = true;
              }
            }

            if (flag) {
              SmsBroadcastConfigInfo[] langList = makeLanguageConfigArray();
              setCellBroadcastConfig(langList);
            } else {
              displayMessage(R.string.cb_error_language_select);
              for (int i = 0; i < tLength; i++) {
                mLanguageList.get(i).setLanguageState(temp2[i]);
              }
            }
          }
        });
    dlgBuilder.setNegativeButton(R.string.cancel, null);
    DialogInterface.OnMultiChoiceClickListener multiChoiceListener =
        new DialogInterface.OnMultiChoiceClickListener() {
          public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
            temp[whichButton] = isChecked;
            AlertDialog languageDialog = null;
            if (dialog instanceof AlertDialog) {
              languageDialog = (AlertDialog) dialog;
            }
            if (whichButton == 0) {
              if (languageDialog != null) {
                for (int i = 1; i < temp.length; ++i) {
                  ListView items = languageDialog.getListView();
                  items.setItemChecked(i, isChecked);
                  temp[i] = isChecked;
                }
              }
            } else {
              if ((!isChecked) && (languageDialog != null)) {
                ListView items = languageDialog.getListView();
                items.setItemChecked(0, isChecked);
                temp[0] = false;
              } else if (isChecked && (languageDialog != null)) {
                /// M: ALPS00641361 @{
                // if select all language, the first item should be checked
                //
                // MTK add
                setCheckedAlllanguageItem(temp, isChecked, languageDialog);
                /// @}
              }
            }
          }
        };
    dlgBuilder.setMultiChoiceItems(R.array.language_list_values, temp, multiChoiceListener);
    AlertDialog languageDialog = dlgBuilder.create();
    if (languageDialog != null) {
      languageDialog.show();
    }
  }
 protected void finalize() {
   MmsLog.d(TAG, "finalize OmaDrmClient instance");
 }
 @Override
 protected void onPostExecute(Void result) {
   MmsLog.d(LOG_TAG, "task finished");
   updateUI();
 }
  @Override
  public void onReceive(Context context, Intent intent) {
    if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
      Log.v(TAG, "Intent received: " + intent);
    }
    /// M:
    MmsLog.d(MmsApp.LOG_TAG, "onReceive(): intent=" + intent.toString());
    String action = intent.getAction();
    if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
      /// M:Code analyze 003, put in a new thread @{
      final Intent mIntent = intent;
      new Thread(
              new Runnable() {
                @Override
                public void run() {
                  Uri changed = (Uri) mIntent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
                  if (changed != null) {
                    MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
                  }
                  MmsLog.d(MmsApp.TXN_TAG, "Mms.Intents.CONTENT_CHANGED_ACTION: " + changed);
                }
              })
          .start();
      /// @}
    } else if (action.equals(TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED)) {
      String state = intent.getStringExtra(EncapsulatedPhone.STATE_KEY);

      if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
        Log.v(TAG, "ANY_DATA_STATE event received: " + state);
      }
      /// M:Code analyze 004, modify the logic,if data connection change,unRegister the listener of
      /// connection changed and wake up transaction service,and add gemini logic @{
      String apnType = intent.getStringExtra(EncapsulatedPhone.DATA_APN_TYPE_KEY);

      // if (state.equals("CONNECTED")) {
      if (EncapsulatedPhone.APN_TYPE_MMS.equals(apnType)) {
        MmsLog.d(
            MmsApp.TXN_TAG,
            "TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED, type is mms.");
        // if the network is not available for mms, keep listening
        ConnectivityManager connMgr =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
        if (ni != null && !ni.isAvailable()) {
          MmsLog.d(MmsApp.TXN_TAG, "network is not available for mms, keep listening.");
          return;
        }

        unRegisterForConnectionStateChanges(context);
        // add for gemini
        if (EncapsulatedFeatureOption.MTK_GEMINI_SUPPORT) {
          // conver slot id to sim id
          SIMInfo si =
              SIMInfo.getSIMInfoBySlot(
                  context,
                  intent.getIntExtra(
                      EncapsulatedPhone.GEMINI_SIM_ID_KEY, EncapsulatedPhone.GEMINI_SIM_1));
          if (null == si) {
            MmsLog.e(
                MmsApp.TXN_TAG,
                "System event receiver: SIMInfo is null for slot "
                    + intent.getIntExtra(EncapsulatedPhone.GEMINI_SIM_ID_KEY, -1));
            return;
          }
          int simId = (int) si.getSimId();
          wakeUpServiceGemini(
              context, simId /*intent.getIntExtra(Phone.GEMINI_SIM_ID_KEY,Phone.GEMINI_SIM_1)*/);
        } else {
          wakeUpService(context);
        }
      }
      /// @}
    } else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
      /// M:Code analyze 005, mark pending msg failed after boot complete @{
      MmsLog.d(MmsApp.TXN_TAG, "Intent.ACTION_BOOT_COMPLETED");
      final Context contxt = context;
      new Thread(
              new Runnable() {
                public void run() {
                  IpMessageUtils.getIpMessagePlugin(contxt)
                      .getServiceManager(contxt.getApplicationContext())
                      .startIpService();
                  setPendingMmsFailed(contxt);
                  setNotificationIndUnstarted(contxt);
                }
              })
          .start();
      /// @}
      // We should check whether there are unread incoming
      // messages in the Inbox and then update the notification icon.
      // Called on the UI thread so don't block.
      MessagingNotification.nonBlockingUpdateNewMessageIndicator(
          context, MessagingNotification.THREAD_NONE, false);
      /// M: when power off,save the chat setting. {@
      SharedPreferences sp =
          PreferenceManager.getDefaultSharedPreferences(contxt.getApplicationContext());
      final long unSavedthreadId = sp.getLong(ChatPreferenceActivity.CHAT_THREAD_ID, -1l);
      Log.v(TAG, "unSaved chatThreadSetting: " + unSavedthreadId);
      if (unSavedthreadId > 0) {
        final boolean mNotificationEnable =
            sp.getBoolean(ChatPreferenceActivity.ENABLE_NOTIFICATION, false);
        final String mMute = sp.getString(ChatPreferenceActivity.CHAT_MUTE, "0");
        final String mRingtone =
            sp.getString(
                ChatPreferenceActivity.CHAT_RINGTONE, ChatPreferenceActivity.DEFAULT_RINGTONE);
        final boolean mVibrate = sp.getBoolean(ChatPreferenceActivity.CHAT_VIBRATE, false);
        final long mMuteStart = sp.getLong(ChatPreferenceActivity.CHAT_MUTE_START, 0);
        new Thread() {
          public void run() {
            SharedPreferences spChatThreadId =
                PreferenceManager.getDefaultSharedPreferences(contxt.getApplicationContext());
            Uri uri =
                ContentUris.withAppendedId(
                    Uri.parse(ChatPreferenceActivity.CHAT_SETTINGS_URI), unSavedthreadId);
            ContentValues values = new ContentValues();
            values.put(ThreadSettings.NOTIFICATION_ENABLE, mNotificationEnable ? 1 : 0);
            values.put(ThreadSettings.MUTE, Integer.parseInt(mMute));
            values.put(ThreadSettings.MUTE_START, mMuteStart);
            values.put(ThreadSettings.RINGTONE, mRingtone);
            values.put(ThreadSettings.VIBRATE, mVibrate ? 1 : 0);
            contxt.getContentResolver().update(uri, values, null, null);
            SharedPreferences.Editor editor = spChatThreadId.edit();
            editor.putLong(ChatPreferenceActivity.CHAT_THREAD_ID, -1l);
            editor.commit();
            if (MmsConfig.getFolderModeEnabled()) {
              MuteCache.setMuteCache(
                  unSavedthreadId, Long.parseLong(mMute), mMuteStart, mNotificationEnable);
            }
          }
        }.start();
      }
      /// M: @}
      /// M:Code analyze 006,add for listening sim setting info changed @{
    } else if (action.equals(EncapsulatedAction.SIM_SETTINGS_INFO_CHANGED)) {
      int simId = (int) intent.getLongExtra("simid", -1);
      MessageUtils.simInfoMap.remove(simId);
      MessageUtils.getSimInfo(context, simId);
      /// @}
      /// M:Code analyze 001,add for save draft mms when received event of shutdown @{
    } else if (action.equals(Intent.ACTION_SHUTDOWN)) {
      mSaveDraft = (OnShutDownListener) ComposeMessageActivity.getComposeContext();
      if (mSaveDraft != null) {
        mSaveDraft.onShutDown();
      }
      /// @}
      /// M:Code analyze 002,add for listening the changing of sim info @{
    } else if (action.equals(EncapsulatedAction.ACTION_SMS_DEFAULT_SIM_CHANGED)) {
      MmsLog.d(MmsApp.LOG_TAG, "SMS default SIM changed.");
      mSimInforChangedListener =
          (OnSimInforChangedListener) ComposeMessageActivity.getComposeContext();
      if (mSimInforChangedListener != null) {
        mSimInforChangedListener.onSimInforChanged();
      }
      mSimInforChangedListener = (OnSimInforChangedListener) ConversationList.getContext();
      if (mSimInforChangedListener != null) {
        mSimInforChangedListener.onSimInforChanged();
      }
      /// @}
      /// M:Code analyze 007,add for listening device storage full or not @{
    } else if (action.equals(Intent.ACTION_DEVICE_STORAGE_FULL)) {
      MmsConfig.setDeviceStorageFullStatus(true);
    } else if (action.equals(Intent.ACTION_DEVICE_STORAGE_NOT_FULL)) {
      MmsConfig.setDeviceStorageFullStatus(false);
      MessagingNotification.cancelNotification(
          context, SmsRejectedReceiver.SMS_REJECTED_NOTIFICATION_ID);
      /// @}
      /// M: new feature, add default quick_text @{
    } else if (action.equals(Intent.ACTION_LOCALE_CHANGED)) {
      if (MmsConfig.getInitQuickText()) {
        return;
      }
      final Context runContext = context;
      new Thread(
              new Runnable() {
                public void run() {
                  Cursor cursor =
                      runContext
                          .getContentResolver()
                          .query(
                              EncapsulatedTelephony.MmsSms.CONTENT_URI_QUICKTEXT,
                              null,
                              null,
                              null,
                              null);
                  // get delete and add ID in DB, id quick Text array
                  ArrayList<Integer> delAddID = new ArrayList<Integer>();
                  ArrayList<Integer> quickTextID = new ArrayList<Integer>();
                  if (cursor != null) {
                    try {
                      ArrayList<String> preQuickText = MmsConfig.getPreQuickText();
                      while (cursor.moveToNext()) {
                        int id = cursor.getInt(0);
                        String str = cursor.getString(1);
                        for (int i = 0; i < preQuickText.size(); i++) {
                          if (str.equals(preQuickText.get(i))) {
                            delAddID.add(new Integer(id));
                            quickTextID.add(new Integer(i));
                            break;
                          }
                        }
                      }
                    } finally {
                      cursor.close();
                    }
                  }
                  // delete old language default quick text
                  for (Integer i : delAddID) {
                    runContext
                        .getContentResolver()
                        .delete(
                            EncapsulatedTelephony.MmsSms.CONTENT_URI_QUICKTEXT,
                            _ID + "=" + i,
                            null);
                  }

                  // add new language default quick text
                  String[] default_quick_texts =
                      runContext.getResources().getStringArray(R.array.default_quick_texts);
                  for (int i = 0, j = 0; i < delAddID.size() && j < quickTextID.size(); i++, j++) {
                    ContentValues values = new ContentValues();
                    values.put(_ID, delAddID.get(i));
                    values.put("text", default_quick_texts[quickTextID.get(j)]);
                    runContext
                        .getContentResolver()
                        .insert(EncapsulatedTelephony.MmsSms.CONTENT_URI_QUICKTEXT, values);
                  }
                  MmsConfig.setPreQuickText(default_quick_texts);
                }
              })
          .start();
    }
    /// @}
  }