com.sentaroh.android.TaskAutomation.Config.ActivityMain.java Source code

Java tutorial

Introduction

Here is the source code for com.sentaroh.android.TaskAutomation.Config.ActivityMain.java

Source

package com.sentaroh.android.TaskAutomation.Config;
/*
The MIT License (MIT)
Copyright (c) 2011-2013 Sentaroh
    
Permission is hereby granted, free of charge, to any person obtaining a copy of 
this software and associated documentation files (the "Software"), to deal 
in the Software without restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to 
the following conditions:
    
The above copyright notice and this permission notice shall be included in all copies or 
substantial portions of the Software.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
    
*/

import static com.sentaroh.android.TaskAutomation.Common.CommonConstants.*;
import static com.sentaroh.android.TaskAutomation.Config.QuickTaskConstants.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;

import com.sentaroh.android.TaskAutomation.ActivityRestartScheduler;
import com.sentaroh.android.TaskAutomation.ActivityTaskStatus;
import com.sentaroh.android.TaskAutomation.CommonUtilities;
import com.sentaroh.android.TaskAutomation.DevAdmReceiver;
import com.sentaroh.android.TaskAutomation.GlobalParameters;
import com.sentaroh.android.TaskAutomation.ISchedulerCallback;
import com.sentaroh.android.TaskAutomation.ISchedulerClient;
import com.sentaroh.android.TaskAutomation.R;
import com.sentaroh.android.TaskAutomation.SchedulerService;
import com.sentaroh.android.TaskAutomation.Common.EnvironmentParms;
import com.sentaroh.android.TaskAutomation.Common.ProfileGroupListItem;
import com.sentaroh.android.TaskAutomation.Common.ProfileListItem;
import com.sentaroh.android.TaskAutomation.Log.LogFileManagementFragment;
import com.sentaroh.android.Utilities.LocalMountPoint;
import com.sentaroh.android.Utilities.NotifyEvent;
import com.sentaroh.android.Utilities.NotifyEvent.NotifyEventListener;
import com.sentaroh.android.Utilities.ContextMenu.CustomContextMenu;
import com.sentaroh.android.Utilities.ContextMenu.CustomContextMenuItem.CustomContextMenuOnClickListener;
import com.sentaroh.android.Utilities.Dialog.CommonDialog;
import com.sentaroh.android.Utilities.Widget.CustomSpinnerAdapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

public class ActivityMain extends FragmentActivity {

    private static boolean DEBUG_ENABLE = true;

    private GlobalParameters mGlblParms = null;
    private boolean mIsApplicationTerminated = false;

    private String mApplicationVersion = "";

    private boolean mApplicationRunFirstTime = false;
    private static int mRestartStatus = 0;

    private EnvironmentParms mEnvParms = null;

    private ProfileMaintenance mProfMaint = null;

    private TabHost mTabHost = null;

    private ArrayList<String> mAndroidApplicationList = null;

    private Context mContext = null;
    private Activity mActivity = null;

    private ISchedulerCallback mSvcClientCallback = null;
    private ServiceConnection mSvcConnScheduler = null;
    private ISchedulerClient mSvcServer = null;

    @Override
    final protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onSaveInstanceState entered");
    };

    @Override
    final protected void onRestoreInstanceState(Bundle savedState) {
        super.onRestoreInstanceState(savedState);
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onRestoreInstanceState entered");
        mRestartStatus = 2;
    };

    //   private void getOverflowMenu() {
    //      http://stackoverflow.com/questions/9739498/android-action-bar-not-showing-overflow   
    //        try {
    //           ViewConfiguration config = ViewConfiguration.get(this);
    //           Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
    //           if(menuKeyField != null) {
    //               menuKeyField.setAccessible(true);
    //               menuKeyField.setBoolean(config, false);
    //           }
    //       } catch (Exception e) {
    //           e.printStackTrace();
    //       }
    //   };

    @SuppressLint("NewApi")
    @Override
    final public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //       StrictMode.enableDefaults();
        //        if (Build.VERSION.SDK_INT<=10) 
        //           requestWindowFeature(Window.FEATURE_NO_TITLE); 

        mContext = this;
        mActivity = this;
        mGlblParms = (GlobalParameters) this.getApplication();
        mGlblParms.initialyzeRequired = false;
        mGlblParms.frgamentMgr = getSupportFragmentManager();
        mGlblParms.context = mContext;
        mEnvParms = new EnvironmentParms();
        mGlblParms.envParms = mEnvParms;
        mApplicationRunFirstTime = initSettingParms();
        mGlblParms.ccMenu = new CustomContextMenu(this.getResources(), getSupportFragmentManager());

        //      if (CommonUtilities.isKeyguardEffective(mContext)) {
        //         Window win = getWindow();
        //         win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER |
        //            WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
        //            WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
        //         );
        //      };
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 14)
            this.getActionBar().setHomeButtonEnabled(false);
        //      getOverflowMenu();

        mGlblParms.commonDlg = new CommonDialog(mContext, getSupportFragmentManager());
        mRestartStatus = 0;
        mApplicationVersion = setApplVersionName();
        if (mEnvParms.settingDebugLevel == 0)
            DEBUG_ENABLE = false;
        else
            DEBUG_ENABLE = true;
        mGlblParms.util = new CommonUtilities(mContext.getApplicationContext(), "Main", mEnvParms);
        mGlblParms.util.startScheduler();

        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onCreate entered");
        mGlblParms.util.addDebugMsg(1, "I",
                "initSettingParms " + "applicationRunFirstTime=" + mApplicationRunFirstTime + ", localRootDir="
                        + mEnvParms.localRootDir + ", settingDebugLevel=" + mEnvParms.settingDebugLevel
                        + ", settingLogMsgDir=" + mEnvParms.settingLogMsgDir + ", settingLogOption="
                        + mEnvParms.settingLogOption + ", settingEnableScheduler="
                        + mEnvParms.settingEnableScheduler + ", settingExitClean=" + mEnvParms.settingExitClean);
        mGlblParms.util.addDebugMsg(1, "I", "Android SDK=" + Build.VERSION.SDK_INT);
        mProfMaint = new ProfileMaintenance(mEnvParms, mGlblParms);
        createMainTabView();
        mGlblParms.profileAdapter = new AdapterProfileList(mContext, R.layout.task_profile_list_view_item,
                new ArrayList<ProfileListItem>());
        mGlblParms.profileGroupAdapter = new AdapterProfileGroupList(mContext,
                R.layout.task_profile_group_list_view_item, new ArrayList<ProfileGroupListItem>());
        //        startSchedulerService();
        if (mEnvParms.settingDeviceAdmin)
            switchDeviceAdminStatus(mEnvParms.settingDeviceAdmin);

    };

    @Override
    final public void onStart() {
        super.onStart();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onStart entered");
    };

    @Override
    final public void onRestart() {
        super.onStart();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onRestart entered");
    };

    @Override
    final public void onResume() {
        super.onResume();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onResume entered, restartStatus=" + mRestartStatus);

        if (mRestartStatus != 1) {
            NotifyEvent ntfy = new NotifyEvent(this);
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(Context c, Object[] o) {
                    mGlblParms.svcServer = mSvcServer;
                    if (mRestartStatus == 1)
                        return;
                    if (mRestartStatus == 0) {
                        mGlblParms.util.addLogMsg("I",
                                String.format(getString(R.string.msgs_main_started), mApplicationVersion));
                        mGlblParms.profileAdapter
                                .setDataList(ProfileMaintenance.getProfileListFromService(mGlblParms));
                        mGlblParms.profileListView.setAdapter(mGlblParms.profileAdapter);
                        mGlblParms.profileGroupListView.setAdapter(mGlblParms.profileGroupAdapter);
                    } else if (mRestartStatus == 2) {
                        mGlblParms.util.addLogMsg("I", getString(R.string.msgs_main_restarted));
                        mGlblParms.commonDlg.showCommonDialog(false, "W", getString(R.string.msgs_main_restarted),
                                "", null);
                        mGlblParms.profileListView.setAdapter(mGlblParms.profileAdapter);
                        mGlblParms.profileGroupListView.setAdapter(mGlblParms.profileGroupAdapter);
                        restoreTaskData();
                        deleteTaskData();
                        mGlblParms.profileAdapter
                                .setDataList(ProfileMaintenance.getProfileListFromService(mGlblParms));
                        mGlblParms.profileListView.setAdapter(mGlblParms.profileAdapter);

                    }
                    createProfileGroupList();
                    setProfileGroupSelectorListener();
                    setProfileGroupTabListClickListener();
                    setProfileGroupTabListLongClickListener();
                    setProfileFilterSelectorListener();

                    refreshActiveTaskStatus(1);
                    setSchedulerStatus();
                    setMainViewButtonListener();

                    setProfileItemClickListner();
                    setProfilelistLongClickListener();

                    setControlTabListener();

                    refreshOptionMenu();

                    mRestartStatus = 1;
                }

                @Override
                public void negativeResponse(Context c, Object[] o) {
                }
            });
            bindSchedulerService(ntfy);
        } else {
            deleteTaskData();
            mEnvParms.loadSettingParms(mContext);
            setSchedulerStatus();
            //         quickTask.initializeQuickTaskView();
            //         setProfileItemClickListner();
            //         setProfilelistLongClickListener();
            refreshOptionMenu();
        }
    };

    @Override
    final public void onPause() {
        super.onPause();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onPause entered");

        if (!mIsApplicationTerminated)
            saveTaskData();
    };

    @Override
    final public void onStop() {
        super.onStop();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onStop entered");
    };

    @Override
    final public void onDestroy() {
        super.onDestroy();
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "onDestroy entered");

        // Application process is follow

        if (mIsApplicationTerminated) {
            if (mProfMaint != null)
                ProfileMaintenance.releaseMediaPlayer(mGlblParms);
            unsetCallbackListener();
            unbindScheduler();
            mIsApplicationTerminated = false;
            deleteTaskData();

            mGlblParms.initParms();
            mGlblParms = null;
            mProfMaint = null;
            mTabHost = null;
            mAndroidApplicationList = null;
            mContext = null;
            mActivity = null;
            mSvcClientCallback = null;
            mSvcConnScheduler = null;
            mSvcServer = null;

            if (mEnvParms.settingExitClean) {
                System.gc();
                android.os.Process.killProcess(android.os.Process.myPid());
            } else {
                mEnvParms = null;
                System.gc();
            }
        } else {
            unbindScheduler();
        }
    };

    @Override
    final public void onConfigurationChanged(final Configuration newConfig) {
        // Ignore orientation change to keep activity from restarting
        super.onConfigurationChanged(newConfig);
        mGlblParms.util.addDebugMsg(1, "I", "onConfigurationChanged Entered");
        refreshOptionMenu();
    };

    @Override
    final public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_top, menu);
        return true;
    };

    @Override
    final public boolean onPrepareOptionsMenu(Menu menu) {
        setControlTabListener();
        if (LocalMountPoint.isExternalStorageAvailable()) {
            //         menu.findItem(R.id.menu_top_export_profile).setVisible(true);
            //         menu.findItem(R.id.menu_top_import_profile).setVisible(true);
            if (mGlblParms.util.isLogFileExists()) {
                menu.findItem(R.id.menu_top_browse_logfile).setVisible(true);
            } else {
                menu.findItem(R.id.menu_top_browse_logfile).setVisible(false);
            }
        } else {
            //         menu.findItem(R.id.menu_top_export_profile).setVisible(false);
            //         menu.findItem(R.id.menu_top_import_profile).setVisible(false);
            menu.findItem(R.id.menu_top_browse_logfile).setVisible(false);
        }
        if (mEnvParms.settingEnableScheduler) {
            menu.findItem(R.id.menu_top_toggle_scheduler).setIcon(R.drawable.scheduler_off_32);
            menu.findItem(R.id.menu_top_toggle_scheduler).setTitle(R.string.msgs_menu_toggle_scheduler_disable);
        } else {
            menu.findItem(R.id.menu_top_toggle_scheduler).setIcon(R.drawable.scheduler_on_32);
            menu.findItem(R.id.menu_top_toggle_scheduler).setTitle(R.string.msgs_menu_toggle_scheduler_enable);
        }
        super.onPrepareOptionsMenu(menu);
        return true;
    };

    @Override
    final public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.menu_top_show_history:
            showHistory();
            return true;
        //         case R.id.menu_top_export_profile:
        //            profMaint.exportProfileDlg(profileAdapter, mGlblParms.profileListView);
        //            return true;         
        //         case R.id.menu_top_import_profile:
        //            importProfile(profileAdapter, mGlblParms.profileListView);
        //            return true;         
        case R.id.menu_top_settings:
            invokeSettingsActivity();
            return true;
        case R.id.menu_top_browse_logfile:
            invokeLogFileBrowser();
            return true;
        case R.id.menu_top_toggle_scheduler:
            mEnvParms.setSettingEnableScheduler(mContext, !mEnvParms.settingEnableScheduler);
            try {
                mSvcServer.aidlCancelAllActiveTask();
                mSvcServer.aidlResetScheduler();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
            refreshOptionMenu();
            setSchedulerStatus();
            return true;
        //         case R.id.menu_top_quick_task:
        //              NotifyEvent ntfy=setQuickTaskListener();
        //              QuickTaskMaintenance quickTask=new QuickTaskMaintenance(context,util, commonDlg, 
        //                     profMaint, profileAdapter, ntfy);
        //              quickTask.initializeQuickTaskView();
        //            return true;         
        case R.id.menu_top_about:
            aboutTaskAutomation();
            return true;
        //         case R.id.menu_top_send_logfile:
        //            sendTaskAutomationLogFile();
        //            return true;         
        case R.id.menu_top_uninstall:
            uninstallApplication();
            return true;
        //         case R.id.menu_top_quit:
        //            finish();
        //            return true;         
        }
        return false;
    };

    final private void setControlTabListener() {
        final Button btn_export_profile = (Button) findViewById(R.id.control_tab_view_export);
        final Button btn_import_profile = (Button) findViewById(R.id.control_tab_view_import);
        final Button btn_quick_task_settings = (Button) findViewById(R.id.control_tab_view_quick_task_settings);
        final Button btn_logfile_send = (Button) findViewById(R.id.control_tab_view_send_log_file);
        final Button btn_log_option = (Button) findViewById(R.id.control_tab_view_log_option);
        final Button btn_logfile_rotate = (Button) findViewById(R.id.control_tab_view_rotate_log_file);
        final Button btn_logfile_delete = (Button) findViewById(R.id.control_tab_view_delete_log_file);
        final Button btn_logfile_manage = (Button) findViewById(R.id.control_tab_view_manage_log_file);
        final Button btn_quick_task_switch = (Button) findViewById(R.id.control_tab_view_quick_task_switch);

        btn_export_profile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ProfileMaintenance.exportProfileDlg(mGlblParms, mGlblParms.profileAdapter,
                        mGlblParms.profileListView);
            }
        });
        btn_import_profile.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                importProfile(mGlblParms.profileAdapter, mGlblParms.profileListView);
            }
        });
        btn_quick_task_settings.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                NotifyEvent ntfy = setQuickTaskListener();
                QuickTaskMaintenance quickTask = new QuickTaskMaintenance(mContext, mGlblParms.util,
                        mGlblParms.commonDlg, mProfMaint, mGlblParms.profileAdapter, ntfy);
                quickTask.initializeQuickTaskView();
            }
        });

        btn_logfile_send.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                confirmSendLog();
                //            mGlblParms.util.sendLogFileToDeveloper(mEnvParms.settingLogMsgDir+mEnvParms.settingLogMsgFilename);
            }
        });

        btn_log_option.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmSettingsLogOption(!mGlblParms.util.getSettingsLogOption(), btn_logfile_rotate,
                        btn_log_option);
            }
        });

        btn_logfile_rotate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                confirmLogFileRotation();
            }
        });

        btn_logfile_delete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                confirmLogFileDelete(btn_logfile_delete, btn_logfile_send);
            }
        });

        btn_logfile_manage.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mGlblParms.util.resetLogReceiver();
                LogFileManagementFragment lfmf = LogFileManagementFragment.newInstance(true,
                        mGlblParms.context.getString(R.string.msgs_log_management_title));
                lfmf.showDialog(mGlblParms.frgamentMgr, lfmf, mGlblParms);
            }
        });

        btn_quick_task_switch.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                confirmQuickTaskSwitch(btn_quick_task_switch);
            }
        });
        setControlTabBtnStatus();
    };

    private void confirmSendLog() {
        mGlblParms.util.flushLog();
        createTempLogFile();

        final Dialog dialog = new Dialog(mContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.confirm_send_log_dlg);

        final Button btn_ok = (Button) dialog.findViewById(R.id.confirm_send_log_dlg_ok_btn);
        final Button btn_cancel = (Button) dialog.findViewById(R.id.confirm_send_log_dlg_cancel_btn);
        final Button btn_preview = (Button) dialog.findViewById(R.id.confirm_send_log_dlg_preview);

        CommonDialog.setDlgBoxSizeLimit(dialog, false);

        btn_preview.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse("file://" + mEnvParms.settingLogMsgDir + "temp_log.txt"),
                        "text/plain");
                startActivity(intent);
            }
        });

        btn_ok.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mGlblParms.util.sendLogFileToDeveloper(mEnvParms.settingLogMsgDir + "temp_log.txt");
                dialog.dismiss();
            }
        });

        btn_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });

        dialog.setOnCancelListener(new OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                btn_cancel.performClick();
            }
        });

        dialog.show();

    };

    private void createTempLogFile() {
        File olf = new File(mEnvParms.settingLogMsgDir + "temp_log.txt");
        File ilf = new File(mEnvParms.settingLogMsgDir + mEnvParms.settingLogMsgFilename);
        try {
            FileInputStream fis = new FileInputStream(ilf);
            FileOutputStream fos = new FileOutputStream(olf);
            byte[] buff = new byte[1024 * 256];
            int rc = 0;
            while ((rc = fis.read(buff)) > 0) {
                fos.write(buff, 0, rc);
            }
            fis.close();
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    final private void setControlTabBtnStatus() {
        //      final Button btn_export_profile=(Button)findViewById(R.id.control_tab_view_export);
        //      final Button btn_import_profile=(Button)findViewById(R.id.control_tab_view_import);
        //      final Button btn_quick_task_settings=(Button)findViewById(R.id.control_tab_view_quick_task_settings);
        final Button btn_logfile_send = (Button) findViewById(R.id.control_tab_view_send_log_file);
        final Button btn_log_option = (Button) findViewById(R.id.control_tab_view_log_option);
        final Button btn_logfile_rotate = (Button) findViewById(R.id.control_tab_view_rotate_log_file);
        final Button btn_logfile_delete = (Button) findViewById(R.id.control_tab_view_delete_log_file);
        //      final Button btn_logfile_manage=(Button)findViewById(R.id.control_tab_view_manage_log_file);
        final Button btn_quick_task_switch = (Button) findViewById(R.id.control_tab_view_quick_task_switch);

        if (mGlblParms.util.isLogFileExists()) {
            btn_logfile_send.setEnabled(true);
            btn_logfile_rotate.setEnabled(true);
            btn_logfile_delete.setEnabled(true);
        } else {
            btn_logfile_delete.setEnabled(false);
            btn_logfile_send.setEnabled(false);
            btn_logfile_rotate.setEnabled(false);
        }

        if (mGlblParms.util.getSettingsLogOption()) {
            btn_log_option.setText(getString(R.string.msgs_control_tab_log_option_enabled));
            if (mGlblParms.util.isLogFileExists())
                btn_logfile_rotate.setEnabled(true);
            else
                btn_logfile_rotate.setEnabled(false);
        } else {
            btn_log_option.setText(getString(R.string.msgs_control_tab_log_option_disabled));
        }

        boolean qt = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                QUICK_TASK_GROUP_NAME);
        if (qt)
            btn_quick_task_switch.setText(getString(R.string.msgs_control_tab_quick_task_switch_enabled));
        else
            btn_quick_task_switch.setText(getString(R.string.msgs_control_tab_quick_task_switch_disabled));

    }

    final private void confirmQuickTaskSwitch(final Button btn_quick_task_switch) {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                boolean qt = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                        QUICK_TASK_GROUP_NAME);
                ProfileUtilities.setProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                        QUICK_TASK_GROUP_NAME, !qt);
                ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, true);
                createProfileGroupList();
                setSchedulerStatus();
                if (qt)
                    btn_quick_task_switch
                            .setText(c.getString(R.string.msgs_control_tab_quick_task_switch_disabled));
                else
                    btn_quick_task_switch.setText(c.getString(R.string.msgs_control_tab_quick_task_switch_enabled));
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }

        });
        boolean qt = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                QUICK_TASK_GROUP_NAME);
        String msg = "";
        if (qt) {
            msg = getString(R.string.msgs_control_tab_confirm_quick_task_switch_disable);
        } else {
            msg = getString(R.string.msgs_control_tab_confirm_quick_task_switch_enaable);
        }
        mGlblParms.commonDlg.showCommonDialog(true, "W", msg, "", ntfy);
    };

    final private void confirmLogFileDelete(final Button btn_logfile_delete, final Button btn_logfile_send) {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                mGlblParms.util.deleteLogFile();
                Handler hndl = new Handler();
                hndl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //                  if (!mGlblParms.util.isLogFileExists()) {
                        //                     btn_logfile_delete.setEnabled(false);
                        //                     btn_logfile_send.setEnabled(false);
                        //                  }
                        setControlTabBtnStatus();
                    }
                }, 100);
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }
        });
        mGlblParms.commonDlg.showCommonDialog(true, "W", getString(R.string.msgs_control_tab_confirm_log_delete),
                "", ntfy);
    };

    final private void confirmLogFileRotation() {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                mGlblParms.util.rotateLogFile();
                Handler hndl = new Handler();
                hndl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setControlTabBtnStatus();
                    }
                }, 100);
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }

        });
        mGlblParms.commonDlg.showCommonDialog(true, "W", getString(R.string.msgs_control_tab_confirm_log_rotate),
                "", ntfy);
    };

    final private void confirmSettingsLogOption(final boolean enabled, final Button btn_logfile_rotate,
            final Button btn_log_option) {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                btn_logfile_rotate.setEnabled(true);
                if (enabled)
                    btn_log_option.setText(getString(R.string.msgs_control_tab_log_option_disabled));
                else
                    btn_log_option.setText(getString(R.string.msgs_control_tab_log_option_enabled));
                mGlblParms.util.setSettingsLogOption(enabled);
                applySettingParms();
                Handler hndl = new Handler();
                hndl.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setControlTabBtnStatus();
                    }
                }, 100);
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }
        });
        String msg = "";
        if (enabled)
            msg = getString(R.string.msgs_control_tab_confirm_log_option_change_enable);
        else
            msg = getString(R.string.msgs_control_tab_confirm_log_option_change_disable);
        mGlblParms.commonDlg.showCommonDialog(true, "W", msg, "", ntfy);
    };

    final private void uninstallApplication() {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            public void positiveResponse(Context c, Object[] o) {
                switchDeviceAdminStatus(false);
                getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_device_admin), false).commit();

                Uri uri = Uri.fromParts("package", getPackageName(), null);
                Intent intent = new Intent(Intent.ACTION_DELETE, uri);
                startActivity(intent);
            }

            @Override
            public void negativeResponse(Context c, Object[] o) {
            }
        });
        if (mEnvParms.settingDeviceAdmin) {
            mGlblParms.commonDlg.showCommonDialog(true, "W", getString(R.string.msgs_menu_uninstall_subtitle),
                    getString(R.string.msgs_menu_uninstall_message), ntfy);
        } else
            ntfy.notifyToListener(true, null);
    };

    @SuppressLint("NewApi")
    final private void refreshOptionMenu() {
        if (Build.VERSION.SDK_INT >= 11) {
            mActivity.invalidateOptionsMenu();
        }
    };

    @SuppressLint("NewApi")
    final private void aboutTaskAutomation() {
        // common ??
        final Dialog dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.about_dialog);
        ((TextView) dialog.findViewById(R.id.about_dialog_title))
                .setText(getString(R.string.msgs_about_dlg_title) + " Ver " + getApplVersionName());
        final WebView func_view = (WebView) dialog.findViewById(R.id.about_dialog_function);
        //       func_view.setWebViewClient(new WebViewClient());
        //       func_view.getSettings().setJavaScriptEnabled(true); 
        func_view.getSettings().setSupportZoom(true);
        //      func_view.setVerticalScrollbarOverlay(true);
        func_view.setBackgroundColor(Color.LTGRAY);
        //      func_view.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        func_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
        func_view.setVerticalScrollBarEnabled(true);
        func_view.setScrollbarFadingEnabled(false);
        if (Build.VERSION.SDK_INT > 10) {
            func_view.getSettings().setDisplayZoomControls(true);
            func_view.getSettings().setBuiltInZoomControls(true);
        } else {
            func_view.getSettings().setBuiltInZoomControls(true);
        }
        func_view.loadUrl("file:///android_asset/" + getString(R.string.msgs_about_dlg_func_html));

        final WebView change_view = (WebView) dialog.findViewById(R.id.about_dialog_change_history);
        if (Build.VERSION.SDK_INT > 10) {
            func_view.getSettings().setDisplayZoomControls(true);
            func_view.getSettings().setBuiltInZoomControls(true);
        } else {
            func_view.getSettings().setBuiltInZoomControls(true);
        }
        change_view.loadDataWithBaseURL("file:///android_asset/", getString(R.string.msgs_about_dlg_change_desc),
                "text/html", "UTF-8", "");
        change_view.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        change_view.getSettings().setSupportZoom(true);
        if (Build.VERSION.SDK_INT > 10) {
            change_view.getSettings().setDisplayZoomControls(true);
            change_view.getSettings().setBuiltInZoomControls(true);
        } else {
            change_view.getSettings().setBuiltInZoomControls(true);
        }

        final Button btnFunc = (Button) dialog.findViewById(R.id.about_dialog_btn_show_func);
        final Button btnChange = (Button) dialog.findViewById(R.id.about_dialog_btn_show_change);
        final Button btnOk = (Button) dialog.findViewById(R.id.about_dialog_btn_ok);

        func_view.setVisibility(TextView.VISIBLE);
        change_view.setVisibility(TextView.GONE);
        btnChange.setBackgroundResource(R.drawable.button_back_ground_color_selector);
        btnFunc.setBackgroundResource(R.drawable.button_back_ground_color_selector);
        btnChange.setTextColor(Color.DKGRAY);
        btnFunc.setTextColor(Color.GREEN);
        btnFunc.setEnabled(false);

        CommonDialog.setDlgBoxSizeLimit(dialog, true);

        // func?
        btnFunc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                change_view.setVisibility(TextView.GONE);
                func_view.setVisibility(TextView.VISIBLE);
                CommonDialog.setDlgBoxSizeLimit(dialog, true);
                btnFunc.setTextColor(Color.GREEN);
                btnChange.setTextColor(Color.DKGRAY);
                btnChange.setEnabled(true);
                btnFunc.setEnabled(false);
            }
        });

        // change?
        btnChange.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                change_view.setVisibility(TextView.VISIBLE);
                func_view.setVisibility(TextView.GONE);
                CommonDialog.setDlgBoxSizeLimit(dialog, true);
                btnChange.setTextColor(Color.GREEN);
                btnFunc.setTextColor(Color.DKGRAY);
                btnChange.setEnabled(false);
                btnFunc.setEnabled(true);
            }
        });

        // OK?
        btnOk.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        // Cancel?
        dialog.setOnCancelListener(new Dialog.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                btnOk.performClick();
            }
        });
        //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
        //      dialog.setCancelable(false);
        dialog.show();

    };

    final private String getApplVersionName() {
        try {
            String packegeName = getPackageName();
            PackageInfo packageInfo = getPackageManager().getPackageInfo(packegeName, PackageManager.GET_META_DATA);
            return packageInfo.versionName;
        } catch (NameNotFoundException e) {
            return "";
        }
    };

    final private void createMainTabView() {
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        //getTabHost();
        mTabHost.setup();

        View childview2 = new CustomTabContentView(this, getString(R.string.msgs_main_tab_name_profile_group));
        TabSpec tabSpec = mTabHost.newTabSpec("Grp").setIndicator(childview2)
                .setContent(R.id.main_profile_group_tab);
        mTabHost.addTab(tabSpec);

        View childview5 = new CustomTabContentView(this, getString(R.string.msgs_main_tab_name_profile));
        tabSpec = mTabHost.newTabSpec("Prof").setIndicator(childview5).setContent(R.id.main_profedit_tab);
        mTabHost.addTab(tabSpec);

        View childview6 = new CustomTabContentView(this, getString(R.string.msgs_main_tab_name_control));
        tabSpec = mTabHost.newTabSpec("Ctrl").setIndicator(childview6).setContent(R.id.main_control_tab);
        mTabHost.addTab(tabSpec);

        //      if (isFirstStart) tabHost.setCurrentTab(0);
        mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
            @Override
            public void onTabChanged(String tabId) {
                if (DEBUG_ENABLE)
                    mGlblParms.util.addDebugMsg(1, "I", "onTabchanged entered. tab=" + tabId);
                if (tabId.equals("Grp"))
                    createProfileGroupList();
                else if (tabId.equals("Ctrl"))
                    setControlTabListener();
            };
        });
        mGlblParms.profileGroupListView = (ListView) findViewById(R.id.main_profile_group_listview);
        mGlblParms.profileListView = (ListView) findViewById(R.id.main_profedit_listview);
        mGlblParms.profileListView = mGlblParms.profileListView;
    };

    final private void importProfile(AdapterProfileList pfla, ListView pflv) {
        NotifyEvent ntfy = new NotifyEvent(mContext);
        // set importProfileDlg response 
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                applySettingParms();
                createProfileGroupList();
                setProfileGroupSelectorListener();
                setSchedulerStatus();
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }
        });
        ProfileMaintenance.importProfileDlg(mGlblParms, ntfy, pfla, pflv);
    };

    final private String setApplVersionName() {
        String ver = "";
        String packegeName = getPackageName();
        PackageInfo packageInfo;
        try {
            packageInfo = getPackageManager().getPackageInfo(packegeName, PackageManager.GET_META_DATA);
            ver = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return ver;
    };

    final private SharedPreferences getPrefsMgr() {
        return CommonUtilities.getPrefMgr(mContext);
    };

    final private boolean initSettingParms() {
        boolean initialized = false;
        if (getPrefsMgr().getString(getString(R.string.settings_main_log_level), "-1").equals("-1")) {
            //first time
            PackageInfo packageInfo;
            String ddl = "0";
            try {
                packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
                int flags = packageInfo.applicationInfo.flags;
                if ((flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0)
                    ddl = "2";

            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
            getPrefsMgr().edit().putString(getString(R.string.settings_main_log_level), ddl).commit();
            getPrefsMgr().edit().putString(getString(R.string.settings_main_scheduler_max_task_count), "20")
                    .commit();
            getPrefsMgr().edit().putString(getString(R.string.settings_main_scheduler_thread_pool_count), "5")
                    .commit();
            getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_enable_scheduler), true).commit();
            getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_restart_scheduler), false).commit();
            getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_device_admin), true).commit();
            getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_sample_recreate), false).commit();
            getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_scheduler_monitor), false).commit();

            getPrefsMgr().edit()
                    .putString(mContext.getString(R.string.settings_main_log_dir),
                            Environment.getExternalStorageDirectory().toString() + "/" + APPLICATION_TAG + "/")
                    .commit();

            getPrefsMgr().edit()
                    .putString(getString(R.string.settings_main_light_sensor_monitor_interval_time), "1000")
                    .commit();
            getPrefsMgr().edit().putString(getString(R.string.settings_main_light_sensor_monitor_active_time), "10")
                    .commit();
            getPrefsMgr().edit().putString(getString(R.string.settings_main_light_sensor_detect_thresh_hold), "30")
                    .commit();
            getPrefsMgr().edit().putString(getString(R.string.settings_main_light_sensor_ignore_time), "2")
                    .commit();

            initialized = true;
        }
        mEnvParms.loadSettingParms(mContext);
        return initialized;
    };

    final private void applySettingParms() {
        try {
            boolean restart_scheduler = false;
            if (getPrefsMgr().getBoolean(getString(R.string.settings_main_restart_scheduler), false)) {
                getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_restart_scheduler), false)
                        .commit();
                restart_scheduler = true;
            }
            boolean pms = mEnvParms.settingEnableScheduler;
            boolean p_admin = mEnvParms.settingDeviceAdmin;
            int p_tpc = mEnvParms.settingTaskExecThreadPoolCount;
            String p_intvl = mEnvParms.settingSleepOption;
            boolean p_light_sensor_thread = mEnvParms.settingLightSensorUseThread;

            mEnvParms.loadSettingParms(mContext);
            if (mEnvParms.settingLogMsgDir.equals("")) {
                mEnvParms.settingLogMsgDir = Environment.getExternalStorageDirectory().toString() + "/"
                        + APPLICATION_TAG + "/";
                getPrefsMgr().edit()
                        .putString(mContext.getString(R.string.settings_main_log_dir), mEnvParms.settingLogMsgDir)
                        .commit();
            } else {
                if (!mEnvParms.settingLogMsgDir.endsWith("/")) {
                    mEnvParms.settingLogMsgDir += "/";
                    getPrefsMgr().edit().putString(mContext.getString(R.string.settings_main_log_dir),
                            mEnvParms.settingLogMsgDir).commit();
                }
            }

            int n_tpc = mEnvParms.settingTaskExecThreadPoolCount;

            String n_intvl = mEnvParms.settingSleepOption;

            if (mEnvParms.settingDebugLevel == 0)
                DEBUG_ENABLE = false;
            else
                DEBUG_ENABLE = true;

            if (isBooleanDifferent(p_admin, mEnvParms.settingDeviceAdmin))
                switchDeviceAdminStatus(mEnvParms.settingDeviceAdmin);

            mGlblParms.util.addDebugMsg(1, "I", "initSettingParms ");
            mGlblParms.util.addDebugMsg(1, "I", "  localRootDir=" + mEnvParms.localRootDir);
            mGlblParms.util.addDebugMsg(1, "I", "  settingDebugLevel=" + mEnvParms.settingDebugLevel);
            mGlblParms.util.addDebugMsg(1, "I", "  settingLogMsgDir=" + mEnvParms.settingLogMsgDir);
            mGlblParms.util.addDebugMsg(1, "I", "  settingLogOption=" + mEnvParms.settingLogOption);
            mGlblParms.util.addDebugMsg(1, "I", "  settingEnableScheduler=" + mEnvParms.settingEnableScheduler);
            mGlblParms.util.addDebugMsg(1, "I", "  settingMaxTaskCount=" + mEnvParms.settingMaxTaskCount);
            mGlblParms.util.addDebugMsg(1, "I",
                    "  settingThreadPoolCount=" + mEnvParms.settingTaskExecThreadPoolCount);
            mGlblParms.util.addDebugMsg(1, "I", "  settingRestartScheduler=" + restart_scheduler);
            mGlblParms.util.addDebugMsg(1, "I", "  settingEnableMonitor=" + mEnvParms.settingEnableMonitor);
            mGlblParms.util.addDebugMsg(1, "I", "  settingForceWakeLockUse=" + mEnvParms.settingForceWakeLockUse);
            mGlblParms.util.addDebugMsg(1, "I", "  settingHeartBeatIntervalTime=" + mEnvParms.settingSleepOption);
            mGlblParms.util.addDebugMsg(1, "I", "  settingExitClean=" + mEnvParms.settingExitClean);

            mGlblParms.util.resetLogReceiver();

            if (getPrefsMgr().getBoolean(getString(R.string.settings_main_sample_recreate), false)) {
                getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_sample_recreate), false).commit();
                boolean sample = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                        "Sample");
                boolean bsh = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                        "BeanShell API Sample");
                ProfileUtilities.deleteProfileGroup(mGlblParms.util, mGlblParms.profileAdapter, "Sample");
                ProfileUtilities.deleteProfileGroup(mGlblParms.util, mGlblParms.profileAdapter,
                        "BeanShell API Sample");
                SampleProfile.addSampleProfile(mGlblParms.profileAdapter, true, true);

                mGlblParms.profileAdapter.sort();
                mGlblParms.profileAdapter.updateShowList();
                mGlblParms.profileAdapter.notifyDataSetChanged();
                if (sample || bsh)
                    ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, true);
                else
                    ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, false);

                createProfileGroupList();
                setProfileGroupSelectorListener();
                setProfileGroupTabListClickListener();
                setProfileGroupTabListLongClickListener();
                setProfileFilterSelectorListener();

            }

            if (restart_scheduler || p_tpc != n_tpc || !p_intvl.equals(n_intvl)
                    || isBooleanDifferent(p_light_sensor_thread, mEnvParms.settingLightSensorUseThread)) {
                if (!pms && mEnvParms.settingEnableScheduler)
                    mGlblParms.util.startScheduler();
                //            mGlblParms.util.restartScheduler();
                Intent in_b = new Intent(mContext.getApplicationContext(), ActivityRestartScheduler.class);
                in_b.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(in_b);
            } else {
                if (!pms && mEnvParms.settingEnableScheduler)
                    mGlblParms.util.startScheduler();
                mSvcServer.aidlResetScheduler();
            }

            setSchedulerStatus();
            setControlTabListener();
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    };

    @SuppressLint("NewApi")
    final private void setSchedulerStatus() {
        TextView tv_msg = (TextView) findViewById(R.id.main_msg);
        String msg_text = "", msg_pref = "";
        if (Build.VERSION.SDK_INT >= 14)
            this.getActionBar().setLogo(R.drawable.main_icon);
        if (!mEnvParms.settingEnableScheduler) {
            msg_text = msg_pref + getString(R.string.msgs_main_task_scheduler_not_running);
            msg_pref = "\n";
            if (Build.VERSION.SDK_INT >= 14)
                this.getActionBar().setLogo(R.drawable.main_icon_stop);
        }
        if (!isActiveProfileGroupExists()) {
            msg_text += msg_pref + getString(R.string.msgs_main_task_scheduler_no_valid_profile);
            msg_pref = "\n";
            if (Build.VERSION.SDK_INT >= 14)
                this.getActionBar().setLogo(R.drawable.main_icon_stop);
        }
        if (msg_text.equals("")) {
            tv_msg.setVisibility(TextView.GONE);
        } else {
            tv_msg.setVisibility(TextView.VISIBLE);
            tv_msg.setText(msg_text);
        }
    };

    final private boolean isActiveProfileGroupExists() {
        boolean result = false;
        for (int i = 0; i < mGlblParms.profileAdapter.getDataListCount(); i++) {
            if (mGlblParms.profileAdapter.getDataListItem(i).isProfileGroupActivated()) {
                result = true;
                break;
            }
        }
        return result;
    };

    final static private boolean isBooleanDifferent(boolean p1, boolean p2) {
        boolean result = true;
        if (p1 && p2)
            result = false;
        else if (!p1 && !p2)
            result = false;
        return result;
    };

    final private void switchDeviceAdminStatus(boolean activate) {
        DevicePolicyManager dpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        final ComponentName darcn = new ComponentName(mContext, DevAdmReceiver.class);
        if (activate && !dpm.isAdminActive(darcn)) {
            NotifyEvent ntfy = new NotifyEvent(mContext);
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(Context c, Object[] o) {
                    Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
                    intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, darcn);
                    startActivityForResult(intent, 10);
                }

                @Override
                public void negativeResponse(Context c, Object[] o) {
                }
            });
            if (mApplicationRunFirstTime) {
                mGlblParms.commonDlg.showCommonDialog(false, "I",
                        mContext.getString(R.string.msgs_main_screen_lock_confirm_title),
                        mContext.getString(R.string.msgs_main_screen_lock_confirm_msg), ntfy);
            } else
                ntfy.notifyToListener(true, null);

        } else if (!activate)
            dpm.removeActiveAdmin(darcn);
    };

    final private void invokeLogFileBrowser() {
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "Invoke log file browser.");
        mGlblParms.util.resetLogReceiver();
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
        //      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | 
        //            Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.setDataAndType(Uri.parse("file://" + mEnvParms.settingLogMsgDir + mEnvParms.settingLogMsgFilename),
                "text/plain");
        startActivity(intent);
    };

    final private void invokeSettingsActivity() {
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "Invoke Settings.");
        Intent intent = new Intent(this, ActivitySettings.class);
        //      intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivityForResult(intent, 0);
    };

    final private void showHistory() {
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I", "Invoke show history.");
        Intent intent = new Intent(this, ActivityTaskStatus.class);
        startActivity(intent);
    };

    final protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (DEBUG_ENABLE)
            mGlblParms.util.addDebugMsg(1, "I",
                    "Return from External activity. ID=" + requestCode + ", result=" + resultCode);
        if (requestCode == 0) {
            applySettingParms();
        } else if (requestCode == 10) {
            if (resultCode != Activity.RESULT_OK) {
                getPrefsMgr().edit().putBoolean(getString(R.string.settings_main_device_admin), false).commit();
                mEnvParms.settingDeviceAdmin = false;
            }
        }
    };

    final public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
        case KeyEvent.KEYCODE_BACK:
            confirmTerminateApplication();
            return true;
        // break;
        default:
            return super.onKeyDown(keyCode, event);
        // break;
        }
    };

    final private void confirmTerminateApplication() {
        //      NotifyEvent ntfy=new NotifyEvent(this);
        //      ntfy.setListener(new NotifyEventListener() {
        //         @Override
        //         public void negativeResponse(Context arg0, Object[] arg1) {}
        //         @Override
        //         public void positiveResponse(Context arg0, Object[] arg1) {
        //            mGlblParms.util.addLogMsg("I",getString(R.string.msgs_main_termination));
        //            mIsApplicationTerminated=true;
        //            finish();
        //         }
        //      });
        //      mGlblParms.commonDlg.showCommonDialog(true,"W",
        //            getString(R.string.msgs_main_terminate_appl),"",ntfy);
        mGlblParms.util.addLogMsg("I", getString(R.string.msgs_main_termination));
        mIsApplicationTerminated = true;
        finish();
    };

    final private void bindSchedulerService(final NotifyEvent p_ntfy) {
        if (mSvcServer != null)
            return;
        mGlblParms.util.addDebugMsg(1, "I", "bindScheduler entered");

        mSvcConnScheduler = new ServiceConnection() {
            final public void onServiceConnected(ComponentName name, IBinder service) {
                mGlblParms.util.addDebugMsg(1, "I", "Callback onServiceConnected entered");
                mSvcServer = ISchedulerClient.Stub.asInterface(service);
                setCallbackListener();
                if (p_ntfy != null)
                    p_ntfy.notifyToListener(true, null);
            }

            final public void onServiceDisconnected(ComponentName name) {
                mGlblParms.util.addDebugMsg(1, "I", "Callback onServiceDisconnected entered");
                mSvcServer = null;
            }
        };
        Intent intent = new Intent(mContext, SchedulerService.class);
        intent.setAction("Main");
        bindService(intent, mSvcConnScheduler, BIND_AUTO_CREATE);
    };

    final private void unbindScheduler() {
        mGlblParms.util.addDebugMsg(1, "I", "unbindScheduler entered");
        if (mSvcClientCallback != null) {
            try {
                if (mSvcServer != null)
                    mSvcServer.removeCallBack(mSvcClientCallback);
                mSvcClientCallback = null;
            } catch (RemoteException e) {
                e.printStackTrace();
                mGlblParms.util.addLogMsg("E", "removeListener error :" + e.toString());
            }
        }
        unbindService(mSvcConnScheduler);
    };

    private Handler handler = new Handler();

    final private void setCallbackListener() {
        mGlblParms.util.addDebugMsg(1, "I", "setCallbackListener entered");
        mSvcClientCallback = new ISchedulerCallback.Stub() {
            final public void notifyToClient(String resp_time, final String resp, final String grp,
                    final String task, final String action, String dialog_id, final int atc, final int resp_cd,
                    final String msg) throws RemoteException {
                if (mEnvParms.settingDebugLevel >= 2)
                    mGlblParms.util.addDebugMsg(2, "I", "Notify received ", "Resp=", resp, ", Task=", task,
                            ", action=", action, ", " + "dialog_id=", dialog_id);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        refreshActiveTaskStatus(atc);
                    }
                });
            }
        };
        try {
            mSvcServer.setCallBack(mSvcClientCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
            mGlblParms.util.addLogMsg("E", "setCallbackListener error :" + e.toString());
        }
    };

    final private void unsetCallbackListener() {
        try {
            mSvcServer.removeCallBack(mSvcClientCallback);
        } catch (RemoteException e) {
            e.printStackTrace();
            mGlblParms.util.addLogMsg("E", "unsetCallbackListener error :" + e.toString());
        }
    };

    final private String[] getActiveTaskList() {
        String[] atl = null;
        //      String[] all_task=null;
        try {
            atl = mSvcServer.aidlGetActiveTaskList();
            //         all_task=svcServer.aidlGetTaskList();
        } catch (RemoteException e) {
            e.printStackTrace();
            mGlblParms.util.addLogMsg("E", "aidlGetActiveTaskList error :" + e.toString());
        }
        return atl;
    };

    final private void refreshActiveTaskStatus(int atc) {
        if (mGlblParms.profileAdapter == null)
            return;
        String[] atl = null;
        if (atc != 0)
            atl = getActiveTaskList();
        //      if (atl!=null) for (int i=0;i<atl.length;i++) Log.v("","atl="+atl[i]);
        boolean active_task_exists = false;
        for (int j = 0; j < mGlblParms.profileAdapter.getDataListCount(); j++) {
            if (mGlblParms.profileAdapter.getDataListItem(j).getProfileType().equals(PROFILE_TYPE_TASK)) {
                ProfileListItem tl = mGlblParms.profileAdapter.getDataListItem(j);
                tl.setTaskActive(false);
                if (atl != null && atl.length != 0) {
                    for (int k = 0; k < atl.length; k++) {
                        String[] atn = atl[k].split("\t");
                        if (mGlblParms.profileAdapter.getDataListItem(j).getProfileGroup().equals(atn[0])
                                && mGlblParms.profileAdapter.getDataListItem(j).getProfileName().equals(atn[2])) {
                            tl.setTaskActive(true);
                        }
                    }
                }
                //            mGlblParms.profileAdapter.replaceDataListItem(j, tl);
                if (tl.isTaskActive())
                    active_task_exists = true;
            }
        }
        mGlblParms.profileAdapter.notifyDataSetChanged();

        Button btn_cancel = (Button) findViewById(R.id.main_task_cancel);
        if (active_task_exists) {
            //         btn_cancel.setEnabled(true);
            btn_cancel.setVisibility(Button.VISIBLE);
        } else {
            //         btn_cancel.setEnabled(false);
            btn_cancel.setVisibility(Button.GONE);
        }
    };

    final private void setMainViewButtonListener() {
        Button btn_cancel = (Button) findViewById(R.id.main_task_cancel);

        btn_cancel.setOnClickListener(new OnClickListener() {
            @Override
            final public void onClick(View v) {
                cancelAllActiveTask(mGlblParms.profileAdapter);
            }
        });
    };

    private NotifyEvent setQuickTaskListener() {
        final NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                mGlblParms.profileAdapter.updateShowList();
                createProfileGroupList();
                setProfileGroupSelectorListener();
                ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, true);
                //            profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
                //            mGlblParms.util.reBuildTaskExecList();
                setSchedulerStatus();
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }
        });
        return ntfy;
    };

    final private void createProfileGroupList() {
        String c_grp = "";
        int no_task = 0, no_action = 0, no_time = 0;
        mGlblParms.profileGroupAdapter.clear();
        if (mGlblParms.profileAdapter.getDataListCount() > 0) {
            c_grp = mGlblParms.profileAdapter.getDataListItem(0).getProfileGroup();
            boolean activated = mGlblParms.profileAdapter.getDataListItem(0).isProfileGroupActivated();
            for (int i = 0; i < mGlblParms.profileAdapter.getDataListCount(); i++) {
                if (!mGlblParms.profileAdapter.getDataListItem(i).getProfileGroup().equals(c_grp)) {
                    mGlblParms.profileGroupAdapter
                            .add(new ProfileGroupListItem(c_grp, activated, no_task, no_action, no_time));
                    activated = mGlblParms.profileAdapter.getDataListItem(i).isProfileGroupActivated();
                    c_grp = mGlblParms.profileAdapter.getDataListItem(i).getProfileGroup();
                    no_task = no_action = no_time = 0;
                    if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType().equals(PROFILE_TYPE_TASK)) {
                        no_task++;
                    } else if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType()
                            .equals(PROFILE_TYPE_ACTION)) {
                        no_action++;
                    } else if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType()
                            .equals(PROFILE_TYPE_TIME)) {
                        no_time++;
                    }

                } else {// Count up
                    if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType().equals(PROFILE_TYPE_TASK)) {
                        no_task++;
                    } else if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType()
                            .equals(PROFILE_TYPE_ACTION)) {
                        no_action++;
                    } else if (mGlblParms.profileAdapter.getDataListItem(i).getProfileType()
                            .equals(PROFILE_TYPE_TIME)) {
                        no_time++;
                    }
                }
            }
            mGlblParms.profileGroupAdapter
                    .add(new ProfileGroupListItem(c_grp, activated, no_task, no_action, no_time));
            mGlblParms.profileGroupAdapter.sort();
        }
        mGlblParms.profileGroupAdapter.notifyDataSetChanged();
    };

    final private void setProfileGroupSelectorListener() {
        mGlblParms.spinnerProfileGroupSelector = (Spinner) findViewById(R.id.main_profedit_profile_group_spinner);
        mGlblParms.adapterProfileGroupSelector = new CustomSpinnerAdapter(mContext,
                R.layout.custom_simple_spinner_item);
        mGlblParms.adapterProfileGroupSelector.setTextColor(Color.BLACK);
        mGlblParms.adapterProfileGroupSelector
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mGlblParms.spinnerProfileGroupSelector
                .setPrompt(mContext.getString(R.string.msgs_profile_group_select_profile_group));
        mGlblParms.spinnerProfileGroupSelector.setAdapter(mGlblParms.adapterProfileGroupSelector);
        mGlblParms.adapterProfileGroupSelector.clear();

        for (int i = 0; i < mGlblParms.profileGroupAdapter.getCount(); i++) {
            mGlblParms.adapterProfileGroupSelector
                    .add(mGlblParms.profileGroupAdapter.getItem(i).getProfileGroupName());
        }
        ;

        mGlblParms.spinnerProfileGroupSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            final public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                if (!mGlblParms.spinnerProfileGroupSelector.getSelectedItem().toString()
                        .equals(mGlblParms.profileAdapter.getShowedProfileGroupName())) {
                    String c_grp = mGlblParms.spinnerProfileGroupSelector.getSelectedItem().toString();
                    ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, c_grp, mGlblParms.profileAdapter,
                            mGlblParms.profileListView);
                    mGlblParms.profileAdapter.setShowedProfileGroupName(c_grp);
                    mGlblParms.profileAdapter.updateShowList();
                }
            }

            @Override
            final public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        mGlblParms.spinnerProfileGroupSelector.setSelected(true);
    };

    final private void setProfileFilterSelectorListener() {
        mGlblParms.spinnerProfileFilterSelector = (Spinner) findViewById(R.id.main_profedit_filter_spinner);
        mGlblParms.adapterProfileFilterSelector = new CustomSpinnerAdapter(mContext,
                R.layout.custom_simple_spinner_item);
        mGlblParms.adapterProfileFilterSelector.setTextColor(Color.BLACK);
        mGlblParms.adapterProfileFilterSelector
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mGlblParms.spinnerProfileFilterSelector.setPrompt(mContext.getString(R.string.msgs_filter_select_filter));
        mGlblParms.spinnerProfileFilterSelector.setAdapter(mGlblParms.adapterProfileFilterSelector);
        mGlblParms.adapterProfileFilterSelector.clear();

        final String flt_type_none = getString(R.string.msgs_filter_type_none);
        final String flt_type_task = getString(R.string.msgs_filter_type_task_profile);
        final String flt_type_action = getString(R.string.msgs_filter_type_action_profile);
        final String flt_type_time = getString(R.string.msgs_filter_type_time_profile);
        final String flt_type_time_event = getString(R.string.msgs_filter_type_time_event_task);

        mGlblParms.adapterProfileFilterSelector.add(flt_type_none);
        mGlblParms.adapterProfileFilterSelector.add(flt_type_task);
        mGlblParms.adapterProfileFilterSelector.add(flt_type_action);
        mGlblParms.adapterProfileFilterSelector.add(flt_type_time);
        mGlblParms.adapterProfileFilterSelector.add(flt_type_time_event);
        ArrayList<String> bevt = ProfileUtilities.buildBuiltinEventList();
        for (int i = 0; i < bevt.size(); i++)
            mGlblParms.adapterProfileFilterSelector.add(bevt.get(i));
        mGlblParms.spinnerProfileFilterSelector.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            final public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                String sel = mGlblParms.spinnerProfileFilterSelector.getSelectedItem().toString();
                String sel_id = "";
                if (sel.equals(flt_type_none))
                    mGlblParms.profileAdapter.setSelectedFilter("");
                else {
                    if (sel.equals(flt_type_task))
                        sel_id = PROFILE_TYPE_TASK;
                    else if (sel.equals(flt_type_action))
                        sel_id = PROFILE_TYPE_ACTION;
                    else if (sel.equals(flt_type_time))
                        sel_id = PROFILE_TYPE_TIME;
                    else if (sel.equals(flt_type_time_event))
                        sel_id = PROFILE_FILTER_TIME_EVENT_TASK;
                    else
                        sel_id = sel;
                    mGlblParms.profileAdapter.setSelectedFilter(sel_id);
                }
                mGlblParms.profileAdapter.updateShowList();
            }

            @Override
            final public void onNothingSelected(AdapterView<?> arg0) {
            }
        });
        mGlblParms.spinnerProfileFilterSelector.setSelected(true);
        mGlblParms.spinnerProfileFilterSelector.setSelection(0);
    };

    final private void setProfileGroupTabListClickListener() {
        mGlblParms.profileGroupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
                mTabHost.setCurrentTabByTag("Prof");
                for (int i = 0; i < mGlblParms.adapterProfileGroupSelector.getCount(); i++) {
                    if (mGlblParms.profileGroupAdapter.getItem(pos).getProfileGroupName()
                            .equals(mGlblParms.adapterProfileGroupSelector.getItem(i))) {
                        mGlblParms.spinnerProfileGroupSelector.setSelection(i);
                        break;
                    }
                }
            }
        });
    };

    final private void setProfileGroupTabListLongClickListener() {
        mGlblParms.profileGroupListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                createProfileGroupContextMenu(arg2);
                return true;
            }
        });
    };

    final private void createProfileGroupContextMenu(final int pos) {
        final String grp_name = mGlblParms.profileGroupAdapter.getItem(pos).getProfileGroupName();
        if (!mGlblParms.profileGroupAdapter.getItem(pos).isProfileGroupActivated()) {
            mGlblParms.ccMenu
                    .addMenuItem(mContext.getString(R.string.msgs_profile_group_activate_profile_group) + " - "
                            + grp_name, R.drawable.menu_group_activated)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            ProfileUtilities.setProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                                    grp_name, true);
                            ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, true);
                            //                 profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
                            createProfileGroupList();
                            //                 mGlblParms.util.reBuildTaskExecList();
                            setSchedulerStatus();
                        }
                    });
        } else {
            mGlblParms.ccMenu
                    .addMenuItem(mContext.getString(R.string.msgs_profile_group_deactivate_profile_group) + " - "
                            + grp_name, R.drawable.menu_group_deactivated)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        public void onClick(CharSequence menuTitle) {
                            ProfileUtilities.setProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter,
                                    grp_name, false);
                            ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, true);
                            //                 profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
                            createProfileGroupList();
                            //                 mGlblParms.util.reBuildTaskExecList();
                            setSchedulerStatus();
                        }
                    });
        }
        mGlblParms.ccMenu.addMenuItem(mContext.getString(R.string.msgs_profile_group_create_new_profile_group),
                R.drawable.menu_group_add).setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        createNewProfileGroup();
                    }
                });
        if (!grp_name.startsWith("*")) {
            mGlblParms.ccMenu.addMenuItem(mContext.getString(R.string.msgs_profile_group_rename_profile_group),
                    R.drawable.menu_rename).setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            renameProfileGroupDlg(grp_name);
                        }
                    });
        }
        mGlblParms.ccMenu.addMenuItem(mContext.getString(R.string.msgs_profile_group_copy_profile_group),
                R.drawable.menu_copy).setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        copyProfileGroupDlg(grp_name);
                    }
                });
        if (!grp_name.startsWith("*")) {
            mGlblParms.ccMenu.addMenuItem(mContext.getString(R.string.msgs_profile_group_delete_profile_group),
                    R.drawable.menu_trash).setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            deleteProfileGroupDlg(grp_name);
                        }
                    });
        }
        mGlblParms.ccMenu.createMenu();
    };

    final private void createNewProfileGroup() {
        // ??
        final Dialog dialog = new Dialog(mContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //      dialog.getWindow().setSoftInputMode(
        //                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog.setContentView(R.layout.single_item_input_dlg);
        final TextView dlg_title = (TextView) dialog.findViewById(R.id.single_item_input_title);
        final EditText dlg_et_name = (EditText) dialog.findViewById(R.id.single_item_input_dir);
        //      final TextView dlg_msg = (TextView) dialog.findViewById(R.id.single_item_input_msg);
        final Button btnCancel = (Button) dialog.findViewById(R.id.single_item_input_cancel_btn);
        final Button btnOK = (Button) dialog.findViewById(R.id.single_item_input_ok_btn);
        btnOK.setEnabled(false);

        dlg_title.setText(mContext.getString(R.string.msgs_profile_group_create_new_profile_group));

        CommonDialog.setDlgBoxSizeCompact(dialog);

        dlg_et_name.addTextChangedListener(new TextWatcher() {
            @Override
            final public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    //                dlg_et_name.selectAll();
                    String newgrp = dlg_et_name.getText().toString();
                    if (!newgrp.startsWith("*")) {
                        btnOK.setEnabled(true);
                        for (int i = 0; i < mGlblParms.profileGroupAdapter.getCount(); i++) {
                            if (mGlblParms.profileGroupAdapter.getItem(i).getProfileGroupName().equals(newgrp)) {
                                btnOK.setEnabled(false);
                                break;
                            }
                        }
                    } else
                        btnOK.setEnabled(false);
                } else
                    btnOK.setEnabled(false);
            }

            @Override
            final public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            final public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

        final NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                dlg_et_name.selectAll();
                String newloc = dlg_et_name.getText().toString();
                mGlblParms.profileGroupAdapter.add(new ProfileGroupListItem(newloc, false, 0, 0, 0));
                mGlblParms.profileGroupAdapter.sort();
                mGlblParms.profileGroupAdapter.notifyDataSetChanged();

                ProfileListItem tpli = new ProfileListItem();
                tpli.setTaskEntry(PROFILE_VERSION_CURRENT, newloc, false, System.currentTimeMillis(), "",
                        mContext.getString(R.string.msgs_no_profile_entry), "", "", "", "", null, null);
                mGlblParms.profileAdapter.addDataListItem(tpli);
                mGlblParms.profileAdapter.updateShowList();

                setProfileGroupSelectorListener();
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }

        });

        // CANCEL?
        btnCancel.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                dialog.dismiss();
            }
        });
        // OK?
        btnOK.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                ntfy.notifyToListener(POSITIVE, null);
                dialog.dismiss();
            }
        });
        // Cancel?
        dialog.setOnCancelListener(new Dialog.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                btnCancel.performClick();
            }
        });
        //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
        //      dialog.setCancelable(false);
        dialog.show();
    };

    final private void renameProfileGroupDlg(final String old_loc) {
        // ??
        final Dialog dialog = new Dialog(mContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //      dialog.getWindow().setSoftInputMode(
        //                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog.setContentView(R.layout.single_item_input_dlg);
        final TextView dlg_title = (TextView) dialog.findViewById(R.id.single_item_input_title);
        final EditText dlg_et_name = (EditText) dialog.findViewById(R.id.single_item_input_dir);
        //      final TextView dlg_msg = (TextView) dialog.findViewById(R.id.single_item_input_msg);
        final Button btnCancel = (Button) dialog.findViewById(R.id.single_item_input_cancel_btn);
        final Button btnOK = (Button) dialog.findViewById(R.id.single_item_input_ok_btn);
        btnOK.setEnabled(false);

        dlg_title.setText(mContext.getString(R.string.msgs_profile_group_rename_profile_group));

        CommonDialog.setDlgBoxSizeCompact(dialog);

        dlg_et_name.setText(old_loc);
        dlg_et_name.addTextChangedListener(new TextWatcher() {
            @Override
            final public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    //                dlg_et_name.selectAll();
                    String newgrp = dlg_et_name.getText().toString();
                    if (!newgrp.startsWith("*")) {
                        btnOK.setEnabled(true);
                        for (int i = 0; i < mGlblParms.profileGroupAdapter.getCount(); i++) {
                            if (mGlblParms.profileGroupAdapter.getItem(i).getProfileGroupName().equals(newgrp)) {
                                btnOK.setEnabled(false);
                                break;
                            }
                        }
                    } else
                        btnOK.setEnabled(false);
                } else
                    btnOK.setEnabled(false);
            }

            @Override
            final public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            final public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

        final NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                dlg_et_name.selectAll();
                String new_loc = dlg_et_name.getText().toString();
                renameProfileGroup(true, old_loc, new_loc);
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }

        });

        // CANCEL?
        btnCancel.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                dialog.dismiss();
            }
        });
        // OK?
        btnOK.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                ntfy.notifyToListener(POSITIVE, null);
                dialog.dismiss();
            }
        });
        // Cancel?
        dialog.setOnCancelListener(new Dialog.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                btnCancel.performClick();
            }
        });
        //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
        //      dialog.setCancelable(false);
        dialog.show();
    };

    final private void renameProfileGroup(boolean update_req, String old_loc, String new_loc) {
        mGlblParms.util.addDebugMsg(2, "I",
                "renameProfileGroup entered, update=" + update_req + ", old=" + old_loc + ", new=" + new_loc);
        boolean pga = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter, old_loc);
        for (int i = mGlblParms.profileAdapter.getDataListCount() - 1; i >= 0; i--) {
            ProfileListItem pli = mGlblParms.profileAdapter.getDataListItem(i);
            if (pli.getProfileGroup().equals(old_loc)) {
                pli.setProfileGroup(new_loc);
                pli.setProfileUpdateTime(System.currentTimeMillis());
            }
        }
        mGlblParms.profileAdapter.sort();
        if (update_req) {
            mGlblParms.profileAdapter.updateShowList();
            createProfileGroupList();
            setProfileGroupSelectorListener();
            ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, pga);
            //         profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
            if (pga) {
                //            mGlblParms.util.reBuildTaskExecList();
                setSchedulerStatus();
            }
        }
    };

    final private void copyProfileGroupDlg(final String old_loc) {
        // ??
        final Dialog dialog = new Dialog(mContext);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //      dialog.getWindow().setSoftInputMode(
        //                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        dialog.setContentView(R.layout.single_item_input_dlg);
        final TextView dlg_title = (TextView) dialog.findViewById(R.id.single_item_input_title);
        final EditText dlg_et_name = (EditText) dialog.findViewById(R.id.single_item_input_dir);
        //      final TextView dlg_msg = (TextView) dialog.findViewById(R.id.single_item_input_msg);
        final Button btnCancel = (Button) dialog.findViewById(R.id.single_item_input_cancel_btn);
        final Button btnOK = (Button) dialog.findViewById(R.id.single_item_input_ok_btn);
        btnOK.setEnabled(false);

        dlg_title.setText(mContext.getString(R.string.msgs_profile_group_copy_profile_group));

        CommonDialog.setDlgBoxSizeCompact(dialog);

        dlg_et_name.setText(old_loc);
        dlg_et_name.addTextChangedListener(new TextWatcher() {
            @Override
            final public void afterTextChanged(Editable s) {
                if (s.length() != 0) {
                    //                dlg_et_name.selectAll();
                    String newgrp = dlg_et_name.getText().toString();
                    if (!newgrp.startsWith("*")) {
                        btnOK.setEnabled(true);
                        for (int i = 0; i < mGlblParms.profileGroupAdapter.getCount(); i++) {
                            if (mGlblParms.profileGroupAdapter.getItem(i).getProfileGroupName().equals(newgrp)) {
                                btnOK.setEnabled(false);
                                break;
                            }
                        }
                    } else
                        btnOK.setEnabled(false);
                } else
                    btnOK.setEnabled(false);
            }

            @Override
            final public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            final public void onTextChanged(CharSequence s, int start, int before, int count) {
            }
        });

        final NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                dlg_et_name.selectAll();
                String new_loc = dlg_et_name.getText().toString();
                copyProfileGroup(true, old_loc, new_loc);
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }

        });

        // CANCEL?
        btnCancel.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                dialog.dismiss();
            }
        });
        // OK?
        btnOK.setOnClickListener(new View.OnClickListener() {
            final public void onClick(View v) {
                ntfy.notifyToListener(POSITIVE, null);
                dialog.dismiss();
            }
        });
        // Cancel?
        dialog.setOnCancelListener(new Dialog.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface arg0) {
                btnCancel.performClick();
            }
        });
        //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
        //      dialog.setCancelable(false);
        dialog.show();
    };

    final private void copyProfileGroup(boolean update_req, final String from_loc, final String to_loc) {
        mGlblParms.util.addDebugMsg(2, "I",
                "copyProfileGroup entered, update=" + update_req + ", old=" + from_loc + ", new=" + to_loc);
        for (int i = mGlblParms.profileAdapter.getDataListCount() - 1; i >= 0; i--) {
            //         ProfileListItem pli=mGlblParms.profileAdapter.getDataListItem(i);
            ProfileListItem pli = mGlblParms.profileAdapter.getDataListItem(i).clone();
            if (pli.getProfileGroup().equals(from_loc)) {
                pli.setProfileGroup(to_loc);
                pli.setProfileGroupShowed(false);
                pli.setProfileGroupActivated(false);
                mGlblParms.profileAdapter.addDataListItem(pli);
            }
        }
        mGlblParms.profileAdapter.sort();
        if (update_req) {
            mGlblParms.profileAdapter.updateShowList();
            createProfileGroupList();
            setProfileGroupSelectorListener();
            ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, false);
            //         profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
        }
    };

    final private void deleteProfileGroupDlg(final String del_loc) {
        final NotifyEvent ntfy = new NotifyEvent(mContext);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                deleteProfileGroup(true, del_loc);
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }

        });
        mGlblParms.commonDlg.showCommonDialog(true, "W",
                getString(R.string.msgs_profile_group_delete_profile_group),
                String.format(getString(R.string.msgs_profile_group_delete_confirm), del_loc), ntfy);
    };

    final private void deleteProfileGroup(boolean update_req, String del_loc) {
        mGlblParms.util.addDebugMsg(2, "I",
                "deleteProfileGroup entered, update=" + update_req + ", del=" + del_loc);
        boolean pga = ProfileUtilities.isProfileGroupActive(mGlblParms.util, mGlblParms.profileAdapter, del_loc);
        ProfileUtilities.deleteProfileGroup(mGlblParms.util, mGlblParms.profileAdapter, del_loc);
        if (update_req) {
            mGlblParms.profileAdapter.updateShowList();
            createProfileGroupList();
            setProfileGroupSelectorListener();
            ProfileMaintenance.putProfileListToService(mGlblParms, mGlblParms.profileAdapter, pga);
            //         profMaint.saveProfileToFileProfileOnly(false, mGlblParms.profileAdapter, mGlblParms.profileListView, "", "");
            if (pga) {
                //            mGlblParms.util.reBuildTaskExecList();
                setSchedulerStatus();
            }
        }
    };

    final private void setProfileItemClickListner() {
        mGlblParms.profileListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            final public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ProfileListItem item = mGlblParms.profileAdapter.getProfItem(position);
                mGlblParms.util.addDebugMsg(1, "I", "Profilelist item Clicked :" + item.getProfileName());
                String curr_grp = item.getProfileGroup();
                if (item.getProfileGroup().equals(QUICK_TASK_GROUP_NAME)) {
                    if (item.getProfileType().equals(PROFILE_TYPE_TASK)) {
                        ProfileMaintenanceTaskProfile pmtp = ProfileMaintenanceTaskProfile.newInstance();
                        pmtp.showDialog(getSupportFragmentManager(), pmtp, "BROWSE", curr_grp, item);
                    } else if (item.getProfileType().equals(PROFILE_TYPE_TIME)) {
                        ProfileMaintenanceTimeProfile pmip = ProfileMaintenanceTimeProfile.newInstance();
                        pmip.showDialog(getSupportFragmentManager(), pmip, "BROWSE", curr_grp, item);
                    } else if (item.getProfileType().equals(PROFILE_TYPE_ACTION)) {
                        ProfileMaintenanceActionProfile pmap = ProfileMaintenanceActionProfile.newInstance();
                        pmap.showDialog(getSupportFragmentManager(), pmap, "BROWSE", curr_grp, item);
                    }
                } else {
                    boolean selected = false;
                    for (int i = 0; i < mGlblParms.profileAdapter.getProfItemCount(); i++) {
                        if (mGlblParms.profileAdapter.getProfItem(i).isProfileItemSelected()) {
                            selected = true;
                            break;
                        }
                    }
                    if (!selected) {
                        if (item.getProfileType().equals(PROFILE_TYPE_TASK)) {
                            ProfileMaintenanceTaskProfile pmtp = ProfileMaintenanceTaskProfile.newInstance();
                            pmtp.showDialog(getSupportFragmentManager(), pmtp, "EDIT", curr_grp, item);
                        } else if (item.getProfileType().equals(PROFILE_TYPE_TIME)) {
                            ProfileMaintenanceTimeProfile pmip = ProfileMaintenanceTimeProfile.newInstance();
                            pmip.showDialog(getSupportFragmentManager(), pmip, "EDIT", curr_grp, item);
                        } else if (item.getProfileType().equals(PROFILE_TYPE_ACTION)) {
                            ProfileMaintenanceActionProfile pmap = ProfileMaintenanceActionProfile.newInstance();
                            pmap.showDialog(getSupportFragmentManager(), pmap, "EDIT", curr_grp, item);
                        }
                    } else {
                        item = mGlblParms.profileAdapter.getProfItem(position);
                        if (item.isProfileItemSelected()) {
                            item.setProfileItemSelected(false);
                            mGlblParms.profileAdapter.notifyDataSetChanged();
                        } else {
                            item.setProfileItemSelected(true);
                            mGlblParms.profileAdapter.notifyDataSetChanged();
                        }
                    }
                }
            }
        });
    };

    final private void setProfilelistLongClickListener() {
        mGlblParms.profileListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            final public boolean onItemLongClick(AdapterView<?> arg0, View view, int idx, long arg3) {
                if (mGlblParms.profileAdapter.getProfItem(idx).getProfileGroup().equals(QUICK_TASK_GROUP_NAME)) {
                    createQuickTaskProfileContextMenu(view, idx);
                } else {
                    createProfileContextMenu(view, idx);
                }
                return true;
            }
        });
    };

    final private void createProfileContextMenu(View view, int idx) {
        ProfileListItem item;
        int scn = 0;
        boolean active_task_exists = false;
        for (int i = 0; i < mGlblParms.profileAdapter.getProfItemCount(); i++) {
            if (mGlblParms.profileAdapter.getProfItem(i).isProfileItemSelected()) {
                scn++;
            }
            if (mGlblParms.profileAdapter.getProfItem(i).isTaskActive())
                active_task_exists = true;
        }
        if (scn <= 1) {//single selection 
            for (int i = 0; i < mGlblParms.profileAdapter.getProfItemCount(); i++) {
                item = mGlblParms.profileAdapter.getProfItem(i);
                if (idx == i) {// set checked
                    item.setProfileItemSelected(true);
                    scn = i;//set new index no 
                } else {
                    if (item.isProfileItemSelected()) {//reset unchecked
                        item.setProfileItemSelected(false);
                    }
                }
            }
            mGlblParms.profileAdapter.notifyDataSetChanged();
            createProfileContextMenu_Single(view, idx, scn, active_task_exists);

        } else {
            createProfileContextMenu_Multiple(view, idx, active_task_exists);
        }
    };

    final private void createQuickTaskProfileContextMenu(View view, final int idx) {
        final String curr_grp = mGlblParms.profileAdapter.getProfItem(idx).getProfileGroup();
        mGlblParms.ccMenu
                .addMenuItem(getString(R.string.msgs_main_ccmenu_browse_profile) + " "
                        + mGlblParms.profileAdapter.getProfItem(idx).getProfileName())
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        if (mGlblParms.profileAdapter.getProfItem(idx).getProfileType().equals(PROFILE_TYPE_TASK)) {
                            ProfileMaintenanceTaskProfile pmtp = ProfileMaintenanceTaskProfile.newInstance();
                            pmtp.showDialog(getSupportFragmentManager(), pmtp, "BROWSE", curr_grp,
                                    mGlblParms.profileAdapter.getProfItem(idx));
                        } else if (mGlblParms.profileAdapter.getProfItem(idx).getProfileType()
                                .equals(PROFILE_TYPE_TIME)) {
                            ProfileMaintenanceTimeProfile pmip = ProfileMaintenanceTimeProfile.newInstance();
                            pmip.showDialog(getSupportFragmentManager(), pmip, "BROWSE", curr_grp,
                                    mGlblParms.profileAdapter.getProfItem(idx));
                        } else if (mGlblParms.profileAdapter.getProfItem(idx).getProfileType()
                                .equals(PROFILE_TYPE_ACTION)) {
                            ProfileMaintenanceActionProfile pmap = ProfileMaintenanceActionProfile.newInstance();
                            pmap.showDialog(getSupportFragmentManager(), pmap, "BROWSE", curr_grp,
                                    mGlblParms.profileAdapter.getProfItem(idx));
                        }
                    }
                });
        mGlblParms.ccMenu
                .addMenuItem(getString(R.string.msgs_main_ccmenu_copy_profile) + " "
                        + mGlblParms.profileAdapter.getProfItem(idx).getProfileName())
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.copyProfileDlg(mGlblParms, curr_grp, mGlblParms.profileAdapter,
                                mGlblParms.profileListView, mGlblParms.profileAdapter.getProfItem(idx), idx);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.createMenu();
    };

    final private void createProfileContextMenu_Single(View arg1, final int pos, int cin,
            boolean active_task_exists) {
        final ProfileListItem tpli = mGlblParms.profileAdapter.getProfItem(pos);
        final String curr_grp = mGlblParms.profileAdapter.getProfItem(pos).getProfileGroup();
        boolean dummy_prof = false;
        if (tpli.getProfileType().equals(""))
            dummy_prof = true;
        if (!dummy_prof) {
            if (!tpli.isProfileEnabled()) {
                mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_enable), R.drawable.menu_active)
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            final public void onClick(CharSequence menuTitle) {
                                ProfileMaintenance.setProfileToEnable(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                                ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                            }
                        });
            } else {
                mGlblParms.ccMenu
                        .addMenuItem(getString(R.string.msgs_main_ccmenu_disable), R.drawable.menu_inactive)
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            final public void onClick(CharSequence menuTitle) {
                                ProfileMaintenance.setProfileToDisable(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                                ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                            }
                        });
            }
        }
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_add_task), R.drawable.menu_add)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenanceTaskProfile pmtp = ProfileMaintenanceTaskProfile.newInstance();
                        pmtp.showDialog(getSupportFragmentManager(), pmtp, "ADD", curr_grp, null);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_add_timer), R.drawable.menu_add)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenanceTimeProfile pmip = ProfileMaintenanceTimeProfile.newInstance();
                        pmip.showDialog(getSupportFragmentManager(), pmip, "ADD", curr_grp, null);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_add_action), R.drawable.menu_add)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenanceActionProfile pmap = ProfileMaintenanceActionProfile.newInstance();
                        pmap.showDialog(getSupportFragmentManager(), pmap, "ADD", curr_grp, null);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        if (!dummy_prof) {
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_edit_profile), R.drawable.menu_edit)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            if (mGlblParms.profileAdapter.getProfItem(pos).getProfileType()
                                    .equals(PROFILE_TYPE_TASK)) {
                                ProfileMaintenanceTaskProfile pmtp = ProfileMaintenanceTaskProfile.newInstance();
                                pmtp.showDialog(getSupportFragmentManager(), pmtp, "EDIT", curr_grp,
                                        mGlblParms.profileAdapter.getProfItem(pos));
                                //                 ProfileMaintenance.editProfileTask(mGlblParms,curr_grp,mGlblParms.profileAdapter,mGlblParms.profileListView, mGlblParms.profileAdapter.getProfItem(pos),pos);
                            } else if (mGlblParms.profileAdapter.getProfItem(pos).getProfileType()
                                    .equals(PROFILE_TYPE_TIME)) {
                                ProfileMaintenanceTimeProfile pmip = ProfileMaintenanceTimeProfile.newInstance();
                                pmip.showDialog(getSupportFragmentManager(), pmip, "EDIT", curr_grp,
                                        mGlblParms.profileAdapter.getProfItem(pos));
                            } else if (mGlblParms.profileAdapter.getProfItem(pos).getProfileType()
                                    .equals(PROFILE_TYPE_ACTION)) {
                                ProfileMaintenanceActionProfile pmap = ProfileMaintenanceActionProfile
                                        .newInstance();
                                pmap.showDialog(getSupportFragmentManager(), pmap, "EDIT", curr_grp,
                                        mGlblParms.profileAdapter.getProfItem(pos));
                            }
                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_copy_profile))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            ProfileMaintenance.copyProfileDlg(mGlblParms, curr_grp, mGlblParms.profileAdapter,
                                    mGlblParms.profileListView, mGlblParms.profileAdapter.getProfItem(pos), pos);
                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_rename_profile))
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            ProfileMaintenance.renameProfileDlg(mGlblParms, curr_grp, mGlblParms.profileAdapter,
                                    mGlblParms.profileListView, mGlblParms.profileAdapter.getProfItem(pos), pos);

                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_delete), R.drawable.menu_trash)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            ProfileMaintenance.deleteProfileDlg(mGlblParms, curr_grp, mGlblParms.profileAdapter,
                                    mGlblParms.profileListView);
                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
            if (active_task_exists) {
                mGlblParms.ccMenu
                        .addMenuItem(getString(R.string.msgs_main_ccmenu_cancel_all_task), R.drawable.blank)
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            final public void onClick(CharSequence menuTitle) {
                                cancelAllActiveTask(mGlblParms.profileAdapter);
                                ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                            }
                        });
            }
            if (tpli.isTaskActive()) {
                mGlblParms.ccMenu
                        .addMenuItem(getString(R.string.msgs_main_ccmenu_cancel_active_task), R.drawable.blank)
                        .setOnClickListener(new CustomContextMenuOnClickListener() {
                            @Override
                            final public void onClick(CharSequence menuTitle) {
                                cancelSpecificTask(true, mGlblParms.profileAdapter, tpli.getProfileGroup(),
                                        tpli.getProfileName());
                                ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                        mGlblParms.profileAdapter, mGlblParms.profileListView);
                            }
                        });
            }
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_select_all), R.drawable.blank)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            ProfileMaintenance.setAllProfileItemChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_unselect_all), R.drawable.blank)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, curr_grp,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
        }
        mGlblParms.ccMenu.createMenu();
    };

    final private void createProfileContextMenu_Multiple(View arg1, final int pos, boolean active_task_exists) {
        final String cur_loc = mGlblParms.profileAdapter.getProfItem(pos).getProfileGroup();
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_enable), R.drawable.menu_active)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.setProfileToEnable(mGlblParms, cur_loc, mGlblParms.profileAdapter,
                                mGlblParms.profileListView);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, cur_loc,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_disable), R.drawable.menu_inactive)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.setProfileToDisable(mGlblParms, cur_loc, mGlblParms.profileAdapter,
                                mGlblParms.profileListView);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, cur_loc,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_delete), R.drawable.menu_trash)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.deleteProfileDlg(mGlblParms, cur_loc, mGlblParms.profileAdapter,
                                mGlblParms.profileListView);
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, cur_loc,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        if (active_task_exists) {
            mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_cancel_all_task), R.drawable.blank)
                    .setOnClickListener(new CustomContextMenuOnClickListener() {
                        @Override
                        final public void onClick(CharSequence menuTitle) {
                            cancelAllActiveTask(mGlblParms.profileAdapter);
                            ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, cur_loc,
                                    mGlblParms.profileAdapter, mGlblParms.profileListView);
                        }
                    });
        }
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_select_all), R.drawable.blank)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.setAllProfileItemChecked(mGlblParms, cur_loc, mGlblParms.profileAdapter,
                                mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.addMenuItem(getString(R.string.msgs_main_ccmenu_unselect_all), R.drawable.blank)
                .setOnClickListener(new CustomContextMenuOnClickListener() {
                    @Override
                    final public void onClick(CharSequence menuTitle) {
                        ProfileMaintenance.setAllProfileItemUnChecked(mGlblParms, cur_loc,
                                mGlblParms.profileAdapter, mGlblParms.profileListView);
                    }
                });
        mGlblParms.ccMenu.createMenu();
    };

    final private void cancelAllActiveTask(final AdapterProfileList tpfa) {
        String tl = "";
        for (int i = 0; i < tpfa.getDataListCount(); i++) {
            ProfileListItem tpli = tpfa.getDataListItem(i);
            if (tpli.isTaskActive()) {
                tl = tl + "\n" + tpli.getProfileGroup() + ", " + tpli.getProfileName();
            }
        }
        NotifyEvent ntfy = new NotifyEvent(this);
        ntfy.setListener(new NotifyEventListener() {
            @Override
            final public void positiveResponse(Context c, Object[] o) {
                try {
                    mSvcServer.aidlCancelAllActiveTask();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                //            for (int i=0;i<tpfa.getDataListCount();i++) {
                //               ProfileListItem tpli=tpfa.getDataListItem(i);
                //               if (tpli.isTaskActive()) {
                //                  try {
                //                     svcServer.aidlCancelSpecificTask(
                //                           tpli.getProfileGroup(),tpli.getProfileName());
                //                  } catch (RemoteException e) {
                //                     e.printStackTrace();
                //                  }
                //               }
                //            }
            }

            @Override
            final public void negativeResponse(Context c, Object[] o) {
            }
        });
        mGlblParms.commonDlg.showCommonDialog(true, "W", getString(R.string.msgs_main_cancel_confirm_title),
                getString(R.string.msgs_main_cancel_confirm_msg) + tl, ntfy);

    };

    final private void cancelSpecificTask(boolean dlg_req, final AdapterProfileList tpfa, final String grp,
            final String tn) {
        if (dlg_req) {
            NotifyEvent ntfy = new NotifyEvent(this);
            ntfy.setListener(new NotifyEventListener() {
                @Override
                final public void positiveResponse(Context c, Object[] o) {
                    try {
                        mSvcServer.aidlCancelSpecificTask(grp, tn);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                final public void negativeResponse(Context c, Object[] o) {
                }
            });
            mGlblParms.commonDlg.showCommonDialog(true, "W", getString(R.string.msgs_main_cancel_confirm_title),
                    getString(R.string.msgs_main_cancel_confirm_msg) + "\n" + tn, ntfy);

        } else {
            try {
                mSvcServer.aidlCancelSpecificTask(grp, tn);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    };

    final private void saveTaskData() {

        ActivityMainDataHolder data = new ActivityMainDataHolder();
        try {
            FileOutputStream fos = openFileOutput(ACTIVITY_TASK_DATA_FILE_NAME, MODE_PRIVATE);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            //          ArrayList<ProfileListItem> tl=new ArrayList<ProfileListItem>();
            //          if (mGlblParms.profileAdapter!=null)
            //             for (int i=0;i<mGlblParms.profileAdapter.getProfItemCount();i++)
            //                tl.add(mGlblParms.profileAdapter.getProfItem(i));
            //          data.tpfal=mGlblParms.profileAdapter.getAllDataList();
            data.aal = new ArrayList<String>();
            if (mAndroidApplicationList != null)
                data.aal.addAll(mAndroidApplicationList);
            oos.writeObject(data);
            oos.close();
            mGlblParms.util.addDebugMsg(1, "I", "Activity data was saved");
        } catch (Exception e) {
            e.printStackTrace();
            mGlblParms.util.addDebugMsg(1, "E", "saveActivityData error, " + e.getMessage());
        }
    };

    final private void restoreTaskData() {
        try {
            File lf = new File(getFilesDir() + "/" + ACTIVITY_TASK_DATA_FILE_NAME);
            //          FileInputStream fis = openFileInput(SMBSYNC_ACTIVITY_TASK_DATA_FILE_NAME);
            FileInputStream fis = new FileInputStream(lf);
            ObjectInputStream ois = new ObjectInputStream(fis);
            ActivityMainDataHolder data = (ActivityMainDataHolder) ois.readObject();
            //          profMaint.replacemGlblParms.profileAdapter(mGlblParms.profileAdapter,
            //             new AdapterProfileList(this, R.layout.task_profile_list_view_item, 
            //                   data.tpfal));
            mAndroidApplicationList = data.aal;
            //          androidApplicationList=new ArrayList<String>();
            //          androidApplicationList.addAll(data.aal);
            ois.close();

            mGlblParms.util.addDebugMsg(1, "I", "Activity data was restored");
        } catch (Exception e) {
            e.printStackTrace();
            mGlblParms.util.addDebugMsg(1, "E", "restoreActivityData error, " + e.getMessage());
        }
    };

    final private void deleteTaskData() {
        File lf = new File(getFilesDir() + "/" + ACTIVITY_TASK_DATA_FILE_NAME);
        if (lf.exists()) {
            lf.delete();
            mGlblParms.util.addDebugMsg(2, "I", "Activity data was deleted");
        }
    };

    final public class CustomTabContentView extends FrameLayout {
        LayoutInflater inflater = (LayoutInflater) getApplicationContext()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        public CustomTabContentView(Context context) {
            super(context);
        }

        public CustomTabContentView(Context context, String title) {
            this(context);
            View childview1 = inflater.inflate(R.layout.tab_widget1, null);
            TextView tv1 = (TextView) childview1.findViewById(R.id.tab_widget1_textview);
            tv1.setText(title);
            addView(childview1);
        }
    };
}

class ActivityMainDataHolder implements Serializable {
    private static final long serialVersionUID = 1L;
    //   public ArrayList<ProfileListItem> tpfal;
    public ArrayList<String> aal;
};