Example usage for android.app AlarmManager RTC

List of usage examples for android.app AlarmManager RTC

Introduction

In this page you can find the example usage for android.app AlarmManager RTC.

Prototype

int RTC

To view the source code for android.app AlarmManager RTC.

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC).

Usage

From source file:com.mediatek.systemupdate.HttpManager.java

int writeFile(HttpResponse response, long currSize) {
    Xlog.i(TAG, "writeFile");

    if (mDownloadInfo.getDLSessionStatus() != DownloadInfo.STATE_QUERYNEWVERSION) {
        //mNotification.clearNotification(NotifyManager.NOTIFY_DOWNLOADING);
        mNotification.showDownloadingNotificaton(mDownloadInfo.getVerNum(),
                (int) (((double) Util.getFileSize(Util.getPackageFileName(mContext))
                        / (double) mDownloadInfo.getUpdateImageSize()) * 100),
                true);/*from  ww  w. j a  v a 2 s .com*/
    }

    Util.cancelAlarm(mContext, Util.Action.ACTION_AUTO_DL_TIME_OUT);
    mDownloadInfo.setOtaAutoDlStatus(false);
    mDownloadInfo.setIfPauseWithinTime(false);

    try {
        // response.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
        // 10000);
        InputStream in = response.getEntity().getContent();
        File ifolder = new File(Util.getPackagePathName(mContext));
        if (!ifolder.exists()) {
            ifolder.mkdirs();
        }
        RandomAccessFile out = null;

        String pkgFile = Util.getPackageFileName(mContext);
        if (pkgFile == null) {
            Xlog.e(TAG, "pkgFile is null");
            mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT;
            return mErrorCode;
        }
        try {
            out = new RandomAccessFile(pkgFile, "rws");
            out.seek(currSize);
        } catch (IOException e) {
            e.printStackTrace();
            onShutdownConn();
            mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT;
            return mErrorCode;
        }
        byte[] buff = new byte[4096];
        int rc = 0;
        int i = 0;
        int j = 0;
        boolean rightnow = false;
        boolean finish = false;
        File fPkg = new File(pkgFile);

        if (fPkg == null) {
            out.close();
            mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT;
            return mErrorCode;
        }
        while ((rc = in.read(buff, 0, 4096)) > 0) {
            // to-do: handle Intent.ACTION_MEDIA_EJECT
            /*
             * synchronized (this) { if (mEjectFlag) { try { out.close(); }
             * catch (IOException e) { e.printStackTrace(); }
             * onShutdownConn(); return mErrorCode =
             * HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT; } }
             */

            try {
                if (fPkg.exists()) {
                    out.write(buff, 0, rc);
                } else {
                    Xlog.e(TAG, "file not exist during downloading ");
                    setPauseState();
                    out.close();
                    onShutdownConn();
                    mErrorCode = HTTP_FILE_NOT_EXIST;
                    sendErrorMessage();
                    return mErrorCode;
                }

            } catch (IOException e) {
                e.printStackTrace();
                out.close();
                onShutdownConn();
                mErrorCode = HTTP_DETECTED_SDCARD_CRASH_OR_UNMOUNT;
                return mErrorCode;
            }
            i++;
            int status = mDownloadInfo.getDLSessionStatus();
            if (status == DownloadInfo.STATE_PAUSEDOWNLOAD || status == DownloadInfo.STATE_QUERYNEWVERSION) {
                Xlog.i(TAG, "writeFile, DownloadInfo = " + status);
                mCookies = null;
                finish = false;
                out.close();
                onShutdownConn();
                return 0;

            }
            if (mHandler == null) {
                if (rightnow) {
                    i = 200;
                    rightnow = false;
                }
                if (i == 200) {
                    onDownloadProcessUpdate();
                    i = 0;
                }
            } else {
                if (!rightnow) {
                    i = 18;
                    rightnow = true;
                }
                if (i == 20) {
                    i = 0;
                    onDownloadProcessUpdate();
                }
            }
            j++;
            if (j == 20) {
                onTransferRatio();
                j = 0;
            }
            finish = true;
        }
        Xlog.i(TAG, "writeFile, finish, rc = " + rc + "bytes" + ". finish = " + finish);
        if (finish) {
            onTransferRatio();
            onDownloadProcessUpdate();
        }

        long curSize = Util.getFileSize(Util.getPackageFileName(mContext));
        Xlog.i(TAG, "curSize = " + curSize + " mNewVersionInfo.mSize = " + mDownloadInfo.getUpdateImageSize());

        out.close();

        if (curSize >= mDownloadInfo.getUpdateImageSize()) {

            onShutdownConn();
            return 0;
        }

    } catch (SocketTimeoutException e) {

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

        e.printStackTrace();
    }

    showNoNetworkToast();

    if (mDownloadInfo.getDLSessionStatus() == DownloadInfo.STATE_DOWNLOADING) {
        setPauseState();
        Xlog.e(TAG, "writeFile, exception to set pause state");
        mDownloadInfo.setOtaAutoDlStatus(true);
        mDownloadInfo.setIfPauseWithinTime(true);
        Util.setAlarm(mContext, AlarmManager.RTC, Calendar.getInstance().getTimeInMillis() + AUTO_DL_TIME,
                Util.Action.ACTION_AUTO_DL_TIME_OUT);

    }

    onShutdownConn();

    mErrorCode = HTTP_RESPONSE_NETWORK_ERROR;

    sendErrorMessage();
    return mErrorCode;
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

@Override
public void onResume() {
    //if exiting from the scan screen with an unregistered app
    if (GTConstants.exitingScanScreen && !Utility.deviceRegistered())
        onBackPressed();//  w  w w.  j  a v  a 2  s .c o  m

    //if this is a newly registered app then reboot
    if (newRegistration && Utility.deviceRegistered()) {
        try {
            Intent restartIntent = getPackageManager().getLaunchIntentForPackage(getPackageName());
            PendingIntent intent = PendingIntent.getActivity(HomeScreen.this, 0, restartIntent,
                    Intent.FLAG_ACTIVITY_CLEAR_TOP);
            AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            manager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, intent);
            System.exit(2);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "ON RESUME ERROR: " + e, Toast.LENGTH_LONG).show();
        }
    } else {
        if (!ScreenReceiver.wasScreenOn) {
            //Toast.makeText(getApplicationContext(), "ON RESUME", Toast.LENGTH_LONG).show();
            //if(ftpDownload.getStatus() != AsyncTask.Status.RUNNING)syncFTP();
            //syncFTP();
        }

        syncFTP();

        setuserBanner();

        //if returning from tag scan for time and attendance after an end shift then taa was set to 1
        //set taa to 2 and then launch dialog to display the time and attendance record and then signature page
        if (taa == 1) {
            taa = 0;
        }

        if (taa == 2) {
            //write to tar, transfer file to send directory
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                    "End shift;" + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n", true);

            //write additional info to tar file
            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                    "Total Time;" + Utility.gettimeDiff(Utility.getsessionStart(), Utility.getLocalDateTime())
                            + "\r\n" + "Time on Lunch;" + lunchTime + "\r\n" + "Time on Break;" + breakTime
                            + "\r\n",
                    true);

            //give time for file write
            Utility.initializeGeneralTimer(2000);
            do {
                Utility.Sleep(100);
            } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

            lunchTime = "00:00:00:00";
            breakTime = "00:00:00:00";

            taa = 5;
            show_taaSignature_dialog(); //returning from end shift location scan
        }

        if (taa == 3) {
            //write the event 25 information to the file
            String GM = "";
            if (GTConstants.isSignature) {
                GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID() + CRLF + "***SIGNATURE***" + CRLF
                        + Utility.getsharedPreference(HomeScreen.this, "signaturefileName");
                GTConstants.isSignature = false;
                signaturefileName = "";
            } else
                GM = Utility.getHeaderMessage("$GM") + ",25," + getCellID();

            Utility.write_to_file(HomeScreen.this, GTConstants.dardestinationFolder + GTConstants.tarfileName,
                    GM + "\r\n", true);

            //give time for file write
            Utility.initializeGeneralTimer(2000);
            do {
                Utility.Sleep(100);
            } while (!Utility.fileAccessComplete() && !Utility.getgeneraltimerFlag());

            //move the tar file to the send file folder 
            File from = new File(GTConstants.dardestinationFolder, GTConstants.tarfileName);

            //change the file name to match the $GM time and date
            String[] parse = GM.split(",");
            String newFile = GTConstants.LICENSE_ID.substring(7) + "_" + parse[10] + "_" + parse[2]
                    + "_tar.tar";

            File to = new File(GTConstants.sendfileFolder, newFile);
            from.renameTo(to);

            endshiftCode();

            taa = 0;
        }

        //check if the tag is in a tour
        if (GTConstants.exitingScanScreen) {
            if (GTConstants.isTour) {
                if (GTConstants.tourName.length() == 1) {
                    if (getlasttagScanned().length() == 16)
                        show_tours_dialog(true);
                } else {
                    updateTour(getlasttagScanned());
                }
            }

            //check if this is an account setup tag, designated by an "@&" as the first two characters
            if (getlasttagScanned().length() == 16) {
                String temp = Utility.get_from_GTParamsDataBase(HomeScreen.this, getlasttagScanned());
                if (temp.contains("@&")) {
                    temp = temp.substring(2);
                    setupAccounts("0", temp);
                    //Toast.makeText(getApplicationContext(), temp, Toast.LENGTH_LONG).show();
                }
            }

            GTConstants.exitingScanScreen = false;
        }

    }

    super.onResume();
}

From source file:com.nuvolect.deepdive.probe.DecompileApk.java

public JSONObject stopThread(String threadId) {

    THREAD_ID thread = THREAD_ID.valueOf(threadId);
    Thread myThread = null;/*from w  w w .ja  va2 s  .  co m*/

    switch (thread) {

    case unpack_apk:
        myThread = m_unpackApkThread;
        break;
    case dex2jar:
        myThread = m_dex2jarThread;
        break;
    case optimize_dex:
        myThread = m_optimizeDexThread;
        break;
    case cfr:
        myThread = m_cfrThread;
        break;
    case jadx:
        myThread = m_jadxThread;
        break;
    case fern_flower:
        myThread = m_fernThread;
        break;
    default:// do nothing
    }

    //        if( myThread != null){
    //                myThread.currentThread().stop();// deprecated as of API 16 jellybean
    //            myThread.currentThread().interrupt(); // not working, does not stop thread
    //        }

    /**
     * Not the best solution but attempts to selectively stop individual threads do not
     * seem to work. We need need a more robust solution for long running process management.
     */
    Intent mStartActivity = new Intent(m_ctx, com.nuvolect.deepdive.main.MainActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(m_ctx, mPendingIntentId, mStartActivity,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) m_ctx.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);

    Runtime.getRuntime().exit(0);

    return getStatus();
}

From source file:com.jins_meme.bridge.MainActivity.java

void restart() {
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(),
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 500, pendingIntent);

    finishAndRemoveTask();//from w w  w . jav a  2  s.  c  o  m
}

From source file:com.android.launcher3.Utilities.java

public static void restart(Context context, int delay) {
    if (delay == 0) {
        delay = 1;/*from  w  w w  .j  av a2s . c om*/
    }
    Intent restartIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
    restartIntent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    PendingIntent intent = PendingIntent.getActivity(context, 0, restartIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.RTC, java.lang.System.currentTimeMillis() + delay, intent);
    java.lang.System.exit(2);
}

From source file:eu.faircode.adblocker.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();/*from  w  ww. j a va2s  .  c  o m*/
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command");
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log");
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats");
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for interactive state changes
    last_interactive = Util.isInteractive(this);
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    ifInteractive.addAction(ACTION_SCREEN_OFF_DELAYED);
    registerReceiver(interactiveStateReceiver, ifInteractive);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:com.master.metehan.filtereagle.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();/*from  w w  w.  jav  a  2 s  .  c  o m*/
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command");
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log");
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats");
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for interactive state changes
    last_interactive = Util.isInteractive(this);
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    ifInteractive.addAction(ACTION_SCREEN_OFF_DELAYED);
    registerReceiver(interactiveStateReceiver, ifInteractive);
    registeredInteractiveState = true;

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
        registeredPowerSave = true;
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
    registeredConnectivityChanged = true;

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);
    registeredPackageAdded = true;

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);

    // Setup broadcast to send url map to server. Set inexact repeating for battery saving.
    Intent urlIntent = new Intent(this, URLBroadcastReceiver.class);
    PendingIntent urlPendingIntent = PendingIntent.getBroadcast(this, 0, urlIntent, 0);
    long frequency = 120 * 1000; // two minute frequency for testing
    //long frequency = AlarmManager.INTERVAL_DAY;
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000, frequency,
            urlPendingIntent);
}

From source file:com.zhengde163.netguard.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();//  w  ww . j ava 2  s. co  m
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    //        Util.setTheme(this);
    setTheme(R.style.AppThemeBlue);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command");
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log");
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats");
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for interactive state changes
    last_interactive = Util.isInteractive(this);
    IntentFilter ifInteractive = new IntentFilter();
    ifInteractive.addAction(Intent.ACTION_SCREEN_ON);
    ifInteractive.addAction(Intent.ACTION_SCREEN_OFF);
    ifInteractive.addAction(ACTION_SCREEN_OFF_DELAYED);
    registerReceiver(interactiveStateReceiver, ifInteractive);
    registeredInteractiveState = true;

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
        registeredPowerSave = true;
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
    registeredConnectivityChanged = true;

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);
    registeredPackageAdded = true;

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:android_network.hetnet.vpn_service.ServiceSinkhole.java

@Override
public void onCreate() {
    Log.i(TAG, "Create version=" + Util.getSelfVersionName(this) + "/" + Util.getSelfVersionCode(this));

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Native init
    jni_init();//from w  w w .j  av a 2  s.c  om
    boolean pcap = prefs.getBoolean("pcap", false);
    setPcap(pcap, this);

    prefs.registerOnSharedPreferenceChangeListener(this);

    Util.setTheme(this);
    super.onCreate();

    HandlerThread commandThread = new HandlerThread(getString(R.string.app_name) + " command",
            Process.THREAD_PRIORITY_FOREGROUND);
    HandlerThread logThread = new HandlerThread(getString(R.string.app_name) + " log",
            Process.THREAD_PRIORITY_BACKGROUND);
    HandlerThread statsThread = new HandlerThread(getString(R.string.app_name) + " stats",
            Process.THREAD_PRIORITY_BACKGROUND);
    commandThread.start();
    logThread.start();
    statsThread.start();

    commandLooper = commandThread.getLooper();
    logLooper = logThread.getLooper();
    statsLooper = statsThread.getLooper();

    commandHandler = new CommandHandler(commandLooper);
    logHandler = new LogHandler(logLooper);
    statsHandler = new StatsHandler(statsLooper);

    // Listen for power save mode
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && !Util.isPlayStoreInstall(this)) {
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        powersaving = pm.isPowerSaveMode();
        IntentFilter ifPower = new IntentFilter();
        ifPower.addAction(PowerManager.ACTION_POWER_SAVE_MODE_CHANGED);
        registerReceiver(powerSaveReceiver, ifPower);
        registeredPowerSave = true;
    }

    // Listen for user switches
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        IntentFilter ifUser = new IntentFilter();
        ifUser.addAction(Intent.ACTION_USER_BACKGROUND);
        ifUser.addAction(Intent.ACTION_USER_FOREGROUND);
        registerReceiver(userReceiver, ifUser);
        registeredUser = true;
    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        // Listen for idle mode state changes
        IntentFilter ifIdle = new IntentFilter();
        ifIdle.addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
        registerReceiver(idleStateReceiver, ifIdle);
        registeredIdleState = true;
    }

    // Listen for connectivity updates
    IntentFilter ifConnectivity = new IntentFilter();
    ifConnectivity.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    registerReceiver(connectivityChangedReceiver, ifConnectivity);
    registeredConnectivityChanged = true;

    // Listen for added applications
    IntentFilter ifPackage = new IntentFilter();
    ifPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
    ifPackage.addDataScheme("package");
    registerReceiver(packageAddedReceiver, ifPackage);
    registeredPackageAdded = true;

    // Setup house holding
    Intent alarmIntent = new Intent(this, ServiceSinkhole.class);
    alarmIntent.setAction(ACTION_HOUSE_HOLDING);
    PendingIntent pi = PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, SystemClock.elapsedRealtime() + 60 * 1000,
            AlarmManager.INTERVAL_HALF_DAY, pi);
}

From source file:com.av.remusic.service.MediaService.java

public void timing(int time) {
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(PAUSE_ACTION),
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.set(AlarmManager.RTC, System.currentTimeMillis() + time, pendingIntent);

}