Example usage for android.os Debug waitForDebugger

List of usage examples for android.os Debug waitForDebugger

Introduction

In this page you can find the example usage for android.os Debug waitForDebugger.

Prototype

public static void waitForDebugger() 

Source Link

Document

Wait until a debugger attaches.

Usage

From source file:com.martineve.mendroid.task.MendeleyAPITask.java

public JSONArray[] doFetch(Object... params) {
    // TODO: remove this line when ready
    Debug.waitForDebugger();

    // first param is a string[]
    String[] urls = (String[]) params[0];

    // second param is a Context object
    c_context = (Context) params[1];

    int count = urls.length;
    JSONArray[] ret = new JSONArray[count];

    for (int i = 0; i < count; i++) {
        try {/*from   ww w .  j  a  v  a  2  s.  c o m*/
            Log.i("com.martineve.mendroid.task.MendeleyAPITask", "Executing API call: " + urls[i]);

            String strResponse = m_connect.getMendeleyResponse(urls[i]);

            if (!strResponse.replace("\n", "").startsWith("[")) {
                // wrap in JSONArray delimiters
                strResponse = "[" + strResponse + "]";
            }

            ret[i] = new JSONArray(strResponse);

            Log.i("com.martineve.mendroid.task.MendeleyAPITask", "Succesfully retrieved API call: " + urls[i]);

        } catch (Exception e) {
            // TODO: determine if this is due to needing re-auth
            Log.e("com.martineve.mendroid.task.MendeleyAPITask", "Failed to execute API call: " + urls[i], e);
            return null;
        }
        publishProgress((int) ((i / (float) count) * 100));
    }

    return ret;
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String processCommand(String theCmdLine, PrintWriter out, BufferedInputStream in, OutputStream cmdOut) {
    String strReturn = "";
    Command cCmd = null;/*w  ww  . j a  v a  2s.c o m*/
    Command cSubCmd = null;

    if (bTraceOn)
        ((ASMozStub) this.contextWrapper).SendToDataChannel(theCmdLine);

    String[] Argv = parseCmdLine2(theCmdLine);

    int Argc = Argv.length;

    cCmd = Command.getCmd(Argv[0]);

    switch (cCmd) {
    case TRACE:
        if (Argc == 2)
            bTraceOn = (Argv[1].equalsIgnoreCase("on") ? true : false);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for trace command!";
        break;

    case VER:
        strReturn = prgVersion;
        break;

    case CLOK:
        strReturn = GetClok();
        break;

    case TZGET:
        strReturn = GetTimeZone();
        break;

    case TZSET:
        if (Argc == 2)
            strReturn = SetTimeZone(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for settz command!";
        break;

    case UPDT:
        if (Argc >= 2)
            strReturn = StrtUpdtOMatic(Argv[1], Argv[2], (Argc > 3 ? Argv[3] : null),
                    (Argc > 4 ? Argv[4] : null));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for updt command!";
        break;

    case SETTIME:
        strReturn = SetSystemTime(Argv[1], (Argc > 2 ? Argv[2] : null), cmdOut);
        break;

    case CWD:
        try {
            strReturn = new java.io.File(currentDir).getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        break;

    case CD:
        if (Argc == 2)
            strReturn = changeDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cd command!";
        break;

    case LS:
        strReturn = PrintDir(((Argc > 1) ? Argv[1] : currentDir));
        break;

    case GETAPPROOT:
        if (Argc == 2)
            strReturn = GetAppRoot(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for getapproot command!";
        break;

    case ISDIR:
        if (Argc == 2)
            strReturn = isDirectory(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for isdir command!";
        break;

    case TESTROOT:
        strReturn = GetTestRoot();
        break;

    case DEAD:
        if (Argc == 2)
            strReturn = (IsProcessDead(Argv[1]) ? (Argv[1] + " is hung or unresponsive")
                    : (Argv[1] + " is ok"));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for dead command!";
        break;

    case PS:
        strReturn = GetProcessInfo();
        break;

    case PULL:
        if (Argc >= 2) {
            long lOff = 0;
            long lLen = -1;
            if (Argc > 2) {
                try {
                    lOff = Long.parseLong(Argv[2].trim());
                } catch (NumberFormatException nfe) {
                    lOff = 0;
                    System.out.println("NumberFormatException: " + nfe.getMessage());
                }
            }
            if (Argc == 4) {
                try {
                    lLen = Long.parseLong(Argv[3].trim());
                } catch (NumberFormatException nfe) {
                    lLen = -1;
                    System.out.println("NumberFormatException: " + nfe.getMessage());
                }
            }
            strReturn = Pull(Argv[1], lOff, lLen, cmdOut);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for pull command!";
        }
        break;

    case PUSH:
        if (Argc == 3) {
            long lArg = 0;
            try {
                lArg = Long.parseLong(Argv[2].trim());
            } catch (NumberFormatException nfe) {
                System.out.println("NumberFormatException: " + nfe.getMessage());
            }

            strReturn = Push(Argv[1], in, lArg);
        } else
            strReturn = sErrorPrefix + "Wrong number of arguments for push command!";
        break;

    case INST:
        if (Argc >= 2)
            strReturn = InstallApp(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for inst command!";
        break;

    case UNINST:
        if (Argc >= 2)
            strReturn = UnInstallApp(Argv[1], cmdOut, true);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for uninst command!";
        break;

    case UNINSTALL:
        if (Argc >= 2)
            strReturn = UnInstallApp(Argv[1], cmdOut, false);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for uninstall command!";
        break;

    case ALRT:
        if (Argc > 1) {
            if (Argv[1].contentEquals("on")) {
                String sTitle = "Agent Alert";
                String sMsg = "The Agent Alert System has been activated!";
                if (Argc == 3) {
                    sTitle = Argv[2];
                    sMsg = "";
                } else if (Argc == 4) {
                    sTitle = Argv[2];
                    sMsg = Argv[3];
                }
                StartAlert(sTitle, sMsg);
            } else {
                StopAlert();
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for alrt command!";
        }
        break;

    case REBT:
        if (Argc >= 1)
            strReturn = RunReboot(cmdOut, (Argc > 1 ? Argv[1] : null), (Argc > 2 ? Argv[2] : null));
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for rebt command!";
        //                RunReboot(cmdOut);
        break;

    case TMPD:
        strReturn = GetTmpDir();
        break;

    case DEVINFO:
        if (Argc == 1) {
            strReturn += SUTAgentAndroid.sUniqueID;
            strReturn += "\n";
            strReturn += GetOSInfo();
            strReturn += "\n";
            strReturn += GetSystemTime();
            strReturn += "\n";
            strReturn += GetUptime();
            strReturn += "\n";
            strReturn += GetUptimeMillis();
            strReturn += "\n";
            strReturn += GetSutUptimeMillis();
            strReturn += "\n";
            strReturn += GetScreenInfo();
            strReturn += "\n";
            strReturn += GetRotationInfo();
            strReturn += "\n";
            strReturn += GetMemoryInfo();
            strReturn += "\n";
            strReturn += GetPowerInfo();
            strReturn += "\n";
            strReturn += GetTemperatureInfo();
            strReturn += "\n";
            strReturn += GetProcessInfo();
            strReturn += "\n";
            strReturn += GetSutUserInfo();
            strReturn += "\n";
            strReturn += GetDiskInfo("/data");
            strReturn += "\n";
            strReturn += GetDiskInfo("/system");
            strReturn += "\n";
            strReturn += GetDiskInfo("/mnt/sdcard");
        } else {
            cSubCmd = Command.getCmd(Argv[1]);
            switch (cSubCmd) {
            case ID:
                strReturn = SUTAgentAndroid.sUniqueID;
                break;

            case SCREEN:
                strReturn = GetScreenInfo();
                break;

            case ROTATION:
                strReturn = GetRotationInfo();
                break;

            case PROCESS:
                strReturn = GetProcessInfo();
                break;

            case OS:
                strReturn = GetOSInfo();
                break;

            case SYSTIME:
                strReturn = GetSystemTime();
                break;

            case UPTIME:
                strReturn = GetUptime();
                break;

            case UPTIMEMILLIS:
                strReturn = GetUptimeMillis();
                break;

            case SUTUPTIMEMILLIS:
                strReturn = GetSutUptimeMillis();
                break;

            case MEMORY:
                strReturn = GetMemoryInfo();
                break;

            case POWER:
                strReturn += GetPowerInfo();
                break;

            case SUTUSERINFO:
                strReturn += GetSutUserInfo();
                break;

            case TEMPERATURE:
                strReturn += GetTemperatureInfo();
                break;

            case DISK:
                strReturn += "\n";
                strReturn += GetDiskInfo("/data");
                strReturn += "\n";
                strReturn += GetDiskInfo("/system");
                strReturn += "\n";
                strReturn += GetDiskInfo("/mnt/sdcard");
                break;

            default:
                break;
            }
        }
        break;

    case STAT:
        if (Argc == 2)
            strReturn = StatProcess(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ping command!";
        break;

    case PING:
        if (Argc == 2)
            strReturn = SendPing(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ping command!";
        break;

    case HASH:
        if (Argc == 2)
            strReturn = HashFile(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for hash command!";
        break;

    case PRUNE:
        if (Argc == 2)
            strReturn = PruneDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for prune command!";
        break;

    case FTPG:
        if (Argc == 4)
            strReturn = FTPGetFile(Argv[1], Argv[2], Argv[3], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for ftpg command!";
        break;

    case CAT:
        if (Argc == 2)
            strReturn = Cat(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cat command!";
        break;

    case DIRWRITABLE:
        if (Argc == 2)
            strReturn = IsDirWritable(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for dirwritable command!";
        break;

    case TIME:
        if (Argc == 2)
            strReturn = PrintFileTimestamp(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for time command!";
        break;

    case MKDR:
        if (Argc == 2)
            strReturn = MakeDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for mkdr command!";
        break;

    case RM:
        if (Argc == 2)
            strReturn = RemoveFile(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for rm command!";
        break;

    case MV:
        if (Argc == 3)
            strReturn = Move(Argv[1], Argv[2]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for mv command!";
        break;

    case CP:
        if (Argc == 3)
            strReturn = CopyFile(Argv[1], Argv[2]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for cp command!";
        break;

    case QUIT:
    case EXIT:
        strReturn = Argv[0];
        break;

    case DBG:
        Debug.waitForDebugger();
        strReturn = "waitForDebugger on";
        break;

    case ADB:
        if (Argc == 2) {
            if (Argv[1].contains("ip") || Argv[1].contains("usb")) {
                strReturn = SetADB(Argv[1]);
            } else {
                strReturn = sErrorPrefix + "Unrecognized argument for adb command!";
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for adb command!";
        }
        break;

    case TEST:
        long lFreeMemory = Runtime.getRuntime().freeMemory();
        long lTotMemory = Runtime.getRuntime().totalMemory();
        long lMaxMemory = Runtime.getRuntime().maxMemory();

        if (lFreeMemory > 0) {
            strReturn = "Max memory: " + lMaxMemory + "\nTotal Memory: " + lTotMemory + "\nFree memory: "
                    + lFreeMemory;
            break;
        }

        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = null;

        if (Argv[1].contains("fennec")) {
            ffxFiles = Uri.parse("content://" + fenProvider + "/dir");
        } else if (Argv[1].contains("firefox")) {
            ffxFiles = Uri.parse("content://" + ffxProvider + "/dir");
        }

        //                Uri ffxFiles = Uri.parse("content://org.mozilla.fencp/file");
        String[] columns = new String[] { "_id", "isdir", "filename", "length" };
        //                String[] columns = new String[] {
        //                        "_id",
        //                        "chunk"
        //                     };
        Cursor myCursor = cr.query(ffxFiles, columns, // Which columns to return
                (Argc > 1 ? Argv[1] : null), // Which rows to return (all rows)
                null, // Selection arguments (none)
                null); // Put the results in ascending order by name
        /*
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            String [] colNames = myCursor.getColumnNames();
            int    nID = 0;
            int nBytesRecvd = 0;
                
            for (int lcv = 0; lcv < nRows; lcv++) {
                if  (myCursor.moveToPosition(lcv)) {
                    nID = myCursor.getInt(0);
                    byte [] buf = myCursor.getBlob(1);
                    if (buf != null) {
                        nBytesRecvd += buf.length;
                        strReturn += new String(buf);
                        buf = null;
                    }
                }
            }
            strReturn += "[eof - " + nBytesRecvd + "]";
            myCursor.close();
        }
                
        */
        if (myCursor != null) {
            int nRows = myCursor.getCount();
            int nID = 0;
            String sFileName = "";
            long lFileSize = 0;
            boolean bIsDir = false;

            for (int lcv = 0; lcv < nRows; lcv++) {
                if (myCursor.moveToPosition(lcv)) {
                    nID = myCursor.getInt(0);
                    bIsDir = (myCursor.getInt(1) == 1 ? true : false);
                    sFileName = myCursor.getString(2);
                    lFileSize = myCursor.getLong(3);
                    strReturn += "" + nID + "\t" + (bIsDir ? "<dir> " : "      ") + sFileName + "\t" + lFileSize
                            + "\n";
                }
            }
            myCursor.close();
        }
        break;

    case EXEC:
    case ENVRUN:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, null, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECSU:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, null, true, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECCWD:
        if (Argc >= 3) {
            String[] theArgs = new String[Argc - 2];

            for (int lcv = 2; lcv < Argc; lcv++) {
                theArgs[lcv - 2] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, Argv[1], false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECCWDSU:
        if (Argc >= 3) {
            String[] theArgs = new String[Argc - 2];

            for (int lcv = 2; lcv < Argc; lcv++) {
                theArgs[lcv - 2] = Argv[lcv];
            }

            strReturn = StartPrg2(theArgs, cmdOut, Argv[1], true, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case RUN:
        if (Argc >= 2) {
            String[] theArgs = new String[Argc - 1];

            for (int lcv = 1; lcv < Argc; lcv++) {
                theArgs[lcv - 1] = Argv[lcv];
            }

            if (Argv[1].contains("/") || Argv[1].contains("\\") || !Argv[1].contains("."))
                strReturn = StartPrg(theArgs, cmdOut, false, DEFAULT_STARTPRG_TIMEOUT_SECONDS);
            else
                strReturn = StartJavaPrg(theArgs, null);
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case EXECEXT:
        // An "extended" exec command with format:
        //    execext [su] [cwd=<path>] [t=<timeout in seconds>] arg1 ...
        if (Argc >= 2) {
            boolean su = false;
            String cwd = null;
            int timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS;
            int extra;
            for (extra = 1; extra < Argc; extra++) {
                if (Argv[extra].equals("su")) {
                    su = true;
                } else if (Argv[extra].startsWith("cwd=")) {
                    cwd = Argv[extra].substring(4);
                } else if (Argv[extra].startsWith("t=")) {
                    timeout = Integer.parseInt(Argv[extra].substring(2));
                    if (timeout < 1 || timeout > 4 * 60 * 60) {
                        Log.e("SUTAgentAndroid", "invalid execext timeout " + Argv[extra].substring(2)
                                + "; using default instead");
                        timeout = DEFAULT_STARTPRG_TIMEOUT_SECONDS;
                    }
                } else {
                    break;
                }
            }

            if (extra < Argc) {
                String[] theArgs = new String[Argc - extra];
                for (int lcv = extra; lcv < Argc; lcv++) {
                    theArgs[lcv - extra] = Argv[lcv];
                }

                strReturn = StartPrg2(theArgs, cmdOut, cwd, su, timeout);
            } else {
                strReturn = sErrorPrefix + "No regular arguments for " + Argv[0] + " command!";
            }
        } else {
            strReturn = sErrorPrefix + "Wrong number of arguments for " + Argv[0] + " command!";
        }
        break;

    case KILL:
        if (Argc == 2)
            strReturn = KillProcess(Argv[1], cmdOut);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for kill command!";
        break;

    case DISK:
        strReturn = GetDiskInfo((Argc == 2 ? Argv[1] : "/"));
        break;

    case UNZP:
        strReturn = Unzip(Argv[1], (Argc == 3 ? Argv[2] : ""));
        break;

    case ZIP:
        strReturn = Zip(Argv[1], (Argc == 3 ? Argv[2] : ""));
        break;

    case CHMOD:
        if (Argc == 2)
            strReturn = ChmodDir(Argv[1]);
        else
            strReturn = sErrorPrefix + "Wrong number of arguments for chmod command!";
        break;

    case TOPACTIVITY:
        strReturn = TopActivity();
        break;

    case HELP:
        strReturn = PrintUsage();
        break;

    default:
        strReturn = sErrorPrefix + "[" + Argv[0] + "] command";
        if (Argc > 1) {
            strReturn += " with arg(s) =";
            for (int lcv = 1; lcv < Argc; lcv++) {
                strReturn += " [" + Argv[lcv] + "]";
            }
        }
        strReturn += " is currently not implemented.";
        break;
    }

    return (strReturn);
}

From source file:com.android.exchange.SyncManager.java

public void run() {
    sStop = false;//w  w w. ja va 2 s.  c om
    alwaysLog("!!! SyncManager thread running");
    // If we're really debugging, turn on all logging
    if (Eas.DEBUG) {
        Eas.USER_LOG = true;
        Eas.PARSER_LOG = true;
        Eas.FILE_LOG = true;
    }

    // If we need to wait for the debugger, do so
    if (Eas.WAIT_DEBUG) {
        Debug.waitForDebugger();
    }

    // Synchronize here to prevent a shutdown from happening while we initialize our observers
    // and receivers
    synchronized (sSyncLock) {
        if (INSTANCE != null) {
            mResolver = getContentResolver();

            // Set up our observers; we need them to know when to start/stop various syncs based
            // on the insert/delete/update of mailboxes and accounts
            // We also observe synced messages to trigger upsyncs at the appropriate time
            mAccountObserver = new AccountObserver(mHandler);
            mResolver.registerContentObserver(Account.CONTENT_URI, true, mAccountObserver);
            mMailboxObserver = new MailboxObserver(mHandler);
            mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
            mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
            mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);
            mMessageObserver = new MessageObserver(mHandler);
            mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver);
            mSyncStatusObserver = new EasSyncStatusObserver();
            mStatusChangeListener = ContentResolver
                    .addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver);

            // Set up our observer for AccountManager
            mAccountsUpdatedListener = new EasAccountsUpdatedListener();
            AccountManager.get(getApplication()).addOnAccountsUpdatedListener(mAccountsUpdatedListener,
                    mHandler, true);

            // Set up receivers for connectivity and background data setting
            mConnectivityReceiver = new ConnectivityReceiver();
            registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

            mBackgroundDataSettingReceiver = new ConnectivityReceiver();
            registerReceiver(mBackgroundDataSettingReceiver,
                    new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
            // Save away the current background data setting; we'll keep track of it with the
            // receiver we just registered
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mBackgroundData = cm.getBackgroundDataSetting();

            // See if any settings have changed while we weren't running...
            checkPIMSyncSettings();
        }
    }

    try {
        // Loop indefinitely until we're shut down
        while (!sStop) {
            runAwake(SYNC_MANAGER_ID);
            waitForConnectivity();
            mNextWaitReason = "Heartbeat";
            long nextWait = checkMailboxes();
            try {
                synchronized (this) {
                    if (!mKicked) {
                        if (nextWait < 0) {
                            log("Negative wait? Setting to 1s");
                            nextWait = 1 * SECONDS;
                        }
                        if (nextWait > 10 * SECONDS) {
                            log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason);
                            runAsleep(SYNC_MANAGER_ID, nextWait + (3 * SECONDS));
                        }
                        wait(nextWait);
                    }
                }
            } catch (InterruptedException e) {
                // Needs to be caught, but causes no problem
                log("SyncManager interrupted");
            } finally {
                synchronized (this) {
                    if (mKicked) {
                        //log("Wait deferred due to kick");
                        mKicked = false;
                    }
                }
            }
        }
        log("Shutdown requested");
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in SyncManager", e);
        throw e;
    } finally {
        shutdown();
    }
}

From source file:com.mwebster.exchange.SyncManager.java

public void run() {
    mStop = false;//from www . j a  va  2 s . c om

    // If we're really debugging, turn on all logging
    if (Eas.DEBUG) {
        Eas.USER_LOG = true;
        Eas.PARSER_LOG = true;
        Eas.FILE_LOG = true;
    }

    // If we need to wait for the debugger, do so
    if (Eas.WAIT_DEBUG) {
        Debug.waitForDebugger();
    }

    // Set up our observers; we need them to know when to start/stop various syncs based
    // on the insert/delete/update of mailboxes and accounts
    // We also observe synced messages to trigger upsyncs at the appropriate time
    mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
    mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);
    mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver);
    ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS, mSyncStatusObserver);
    mAccountsUpdatedListener = new EasAccountsUpdatedListener();
    // TODO Find and fix root cause of duplication
    try {
        AccountManager.get(getApplication()).addOnAccountsUpdatedListener(mAccountsUpdatedListener, mHandler,
                true);
    } catch (IllegalStateException e1) {
        // This exception is more of a warning; we shouldn't be in the state in which we
        // already have a listener.
    }

    // Set up receivers for ConnectivityManager
    mConnectivityReceiver = new ConnectivityReceiver();
    registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    mBackgroundDataSettingReceiver = new ConnectivityReceiver();
    registerReceiver(mBackgroundDataSettingReceiver,
            new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
    // Save away background data setting; we'll keep track of it with the receiver
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    mBackgroundData = cm.getBackgroundDataSetting();

    // See if any settings have changed while we weren't running...
    checkPIMSyncSettings();

    try {
        while (!mStop) {
            runAwake(SYNC_MANAGER_ID);
            waitForConnectivity();
            mNextWaitReason = "Heartbeat";
            long nextWait = checkMailboxes();
            try {
                synchronized (this) {
                    if (!mKicked) {
                        if (nextWait < 0) {
                            log("Negative wait? Setting to 1s");
                            nextWait = 1 * SECONDS;
                        }
                        if (nextWait > 10 * SECONDS) {
                            log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason);
                            runAsleep(SYNC_MANAGER_ID, nextWait + (3 * SECONDS));
                        }
                        wait(nextWait);
                    }
                }
            } catch (InterruptedException e) {
                // Needs to be caught, but causes no problem
            } finally {
                synchronized (this) {
                    if (mKicked) {
                        //log("Wait deferred due to kick");
                        mKicked = false;
                    }
                }
            }
        }
        log("Shutdown requested");
    } catch (RuntimeException e) {
        Log.e(TAG, "RuntimeException in SyncManager", e);
        throw e;
    } finally {
        log("Finishing SyncManager");
        // Lots of cleanup here
        // Stop our running syncs
        stopServiceThreads();

        // Stop receivers and content observers
        if (mConnectivityReceiver != null) {
            unregisterReceiver(mConnectivityReceiver);
        }
        if (mBackgroundDataSettingReceiver != null) {
            unregisterReceiver(mBackgroundDataSettingReceiver);
        }

        if (INSTANCE != null) {
            ContentResolver resolver = getContentResolver();
            resolver.unregisterContentObserver(mAccountObserver);
            resolver.unregisterContentObserver(mMailboxObserver);
            resolver.unregisterContentObserver(mSyncedMessageObserver);
            resolver.unregisterContentObserver(mMessageObserver);
            unregisterCalendarObservers();
        }
        // Don't leak the Intent associated with this listener
        if (mAccountsUpdatedListener != null) {
            AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener);
            mAccountsUpdatedListener = null;
        }

        // Clear pending alarms and associated Intents
        clearAlarms();

        // Release our wake lock, if we have one
        synchronized (mWakeLocks) {
            if (mWakeLock != null) {
                mWakeLock.release();
                mWakeLock = null;
            }
        }

        log("Goodbye");
    }

    if (!mStop) {
        // If this wasn't intentional, try to restart the service
        throw new RuntimeException("EAS SyncManager crash; please restart me...");
    }
}

From source file:com.android.exchange.ExchangeService.java

public void run() {
    sStop = false;//from   ww w .ja  v a 2 s.co  m
    alwaysLog("ExchangeService thread running");
    // If we're really debugging, turn on all logging
    if (Eas.DEBUG) {
        Eas.USER_LOG = true;
        Eas.PARSER_LOG = true;
        Eas.FILE_LOG = true;
    }

    TempDirectory.setTempDirectory(this);

    // If we need to wait for the debugger, do so
    if (Eas.WAIT_DEBUG) {
        Debug.waitForDebugger();
    }

    // Synchronize here to prevent a shutdown from happening while we initialize our observers
    // and receivers
    synchronized (sSyncLock) {
        if (INSTANCE != null) {
            mResolver = getContentResolver();

            // Set up our observers; we need them to know when to start/stop various syncs based
            // on the insert/delete/update of mailboxes and accounts
            // We also observe synced messages to trigger upsyncs at the appropriate time
            mAccountObserver = new AccountObserver(mHandler);
            mResolver.registerContentObserver(Account.NOTIFIER_URI, true, mAccountObserver);
            mMailboxObserver = new MailboxObserver(mHandler);
            mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
            mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
            mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);

            // Set up receivers for connectivity and background data setting
            mConnectivityReceiver = new ConnectivityReceiver();
            registerReceiver(mConnectivityReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));

            mBackgroundDataSettingReceiver = new ConnectivityReceiver();
            registerReceiver(mBackgroundDataSettingReceiver,
                    new IntentFilter(ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
            // Save away the current background data setting; we'll keep track of it with the
            // receiver we just registered
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            mBackgroundData = cm.getBackgroundDataSetting();

            // Do any required work to clean up our Mailboxes (this serves to upgrade
            // mailboxes that existed prior to EmailProvider database version 17)
            MailboxUtilities.fixupUninitializedParentKeys(this, getEasAccountSelector());
        }
    }

    try {
        // Loop indefinitely until we're shut down
        while (!sStop) {
            runAwake(EXTRA_MAILBOX_ID);
            waitForConnectivity();
            mNextWaitReason = null;
            long nextWait = checkMailboxes();
            try {
                synchronized (this) {
                    if (!mKicked) {
                        if (nextWait < 0) {
                            log("Negative wait? Setting to 1s");
                            nextWait = 1 * SECONDS;
                        }
                        if (nextWait > 10 * SECONDS) {
                            if (mNextWaitReason != null) {
                                log("Next awake " + nextWait / 1000 + "s: " + mNextWaitReason);
                            }
                            runAsleep(EXTRA_MAILBOX_ID, nextWait + (3 * SECONDS));
                        }
                        wait(nextWait);
                    }
                }
            } catch (InterruptedException e) {
                // Needs to be caught, but causes no problem
                log("ExchangeService interrupted");
            } finally {
                synchronized (this) {
                    if (mKicked) {
                        //log("Wait deferred due to kick");
                        mKicked = false;
                    }
                }
            }
        }
        log("Shutdown requested");
    } catch (ProviderUnavailableException pue) {
        // Shutdown cleanly in this case
        // NOTE: Sync adapters will also crash with this error, but that is already handled
        // in the adapters themselves, i.e. they return cleanly via done().  When the Email
        // process starts running again, the Exchange process will be started again in due
        // course, assuming there is at least one existing EAS account.
        Log.e(TAG, "EmailProvider unavailable; shutting down");
        // Ask for our service to be restarted; this should kick-start the Email process as well
        startService(new Intent(this, ExchangeService.class));
    } catch (RuntimeException e) {
        // Crash; this is a completely unexpected runtime error
        Log.e(TAG, "RuntimeException in ExchangeService", e);
        throw e;
    } finally {
        shutdown();
    }
}