Example usage for android.app AlarmManager setInexactRepeating

List of usage examples for android.app AlarmManager setInexactRepeating

Introduction

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

Prototype

public void setInexactRepeating(@AlarmType int type, long triggerAtMillis, long intervalMillis,
        PendingIntent operation) 

Source Link

Document

Schedule a repeating alarm that has inexact trigger time requirements; for example, an alarm that repeats every hour, but not necessarily at the top of every hour.

Usage

From source file:com.licenta.android.licenseapp.alarm.AlarmReceiver.java

public static void setAlarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    /*/*from w  w w . j  ava  2  s  .c  o  m*/
     * If you don't have precise time requirements, use an inexact repeating alarm
     * the minimize the drain on the device battery.
     *
     * The call below specifies the alarm type, the trigger time, the interval at
     * which the alarm is fired, and the alarm's associated PendingIntent.
     * It uses the alarm type RTC_WAKEUP ("Real Time Clock" wake up), which wakes up
     * the device and triggers the alarm according to the time of the device's clock.
     *
     * Alternatively, you can use the alarm type ELAPSED_REALTIME_WAKEUP to trigger
     * an alarm based on how much time has elapsed since the device was booted. This
     * is the preferred choice if your alarm is based on elapsed time--for example, if
     * you simply want your alarm to fire every 60 minutes. You only need to use
     * RTC_WAKEUP if you want your alarm to fire at a particular date/time. Remember
     * that clock-based time may not translate well to other locales, and that your
     * app's behavior could be affected by the user changing the device's time setting.
     *
     */

    // Wake up the device to fire the alarm in 30 minutes, and every 30 minutes
    // after that.
    long intervalMillis;
    String intervalVal = prefs.getString("repeat_interval", "0");
    switch (intervalVal) {
    case "15":
        intervalMillis = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
        break;
    case "30":
        intervalMillis = AlarmManager.INTERVAL_HALF_HOUR;
        break;
    case "60":
        intervalMillis = AlarmManager.INTERVAL_HOUR;
        break;
    default:
        intervalMillis = 0;
        break;
    }

    // for testing
    intervalMillis = 6000;

    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + intervalMillis, intervalMillis, alarmIntent);

    prefs.edit().putBoolean(Constants.PREF_KEY_IS_ALARM_ON, true).apply();
    Log.d(context.getClass().getName(), "Alarm started");

}

From source file:org.telegram.ui.CacheControlActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("CacheSettings", R.string.CacheSettings));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override//from w ww. j  av a  2s .c o m
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            }
        }
    });

    listAdapter = new ListAdapter(context);

    fragmentView = new FrameLayout(context);
    FrameLayout frameLayout = (FrameLayout) fragmentView;
    frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.settings_background));

    ListView listView = new ListView(context);
    listView.setDivider(null);
    listView.setDividerHeight(0);
    listView.setVerticalScrollBarEnabled(false);
    listView.setDrawSelectorOnTop(true);
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    listView.setAdapter(listAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(final AdapterView<?> adapterView, View view, final int i, long l) {
            if (getParentActivity() == null) {
                return;
            }
            if (i == keepMediaRow) {
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setItems(
                        new CharSequence[] { LocaleController.formatPluralString("Weeks", 1),
                                LocaleController.formatPluralString("Months", 1),
                                LocaleController.getString("KeepMediaForever", R.string.KeepMediaForever) },
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, final int which) {
                                SharedPreferences.Editor editor = ApplicationLoader.applicationContext
                                        .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE).edit();
                                editor.putInt("keep_media", which).commit();
                                if (listAdapter != null) {
                                    listAdapter.notifyDataSetChanged();
                                }
                                PendingIntent pintent = PendingIntent.getService(
                                        ApplicationLoader.applicationContext, 0,
                                        new Intent(ApplicationLoader.applicationContext,
                                                ClearCacheService.class),
                                        0);
                                AlarmManager alarmManager = (AlarmManager) ApplicationLoader.applicationContext
                                        .getSystemService(Context.ALARM_SERVICE);
                                if (which == 2) {
                                    alarmManager.cancel(pintent);
                                } else {
                                    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                                            AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pintent);
                                }
                            }
                        });
                showDialog(builder.create());
            } else if (i == databaseRow) {
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
                builder.setMessage(
                        LocaleController.getString("LocalDatabaseClear", R.string.LocalDatabaseClear));
                builder.setPositiveButton(LocaleController.getString("CacheClear", R.string.CacheClear),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                final ProgressDialog progressDialog = new ProgressDialog(getParentActivity());
                                progressDialog
                                        .setMessage(LocaleController.getString("Loading", R.string.Loading));
                                progressDialog.setCanceledOnTouchOutside(false);
                                progressDialog.setCancelable(false);
                                progressDialog.show();
                                MessagesStorage.getInstance().getStorageQueue().postRunnable(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            SQLiteDatabase database = MessagesStorage.getInstance()
                                                    .getDatabase();
                                            ArrayList<Long> dialogsToCleanup = new ArrayList<>();
                                            SQLiteCursor cursor = database
                                                    .queryFinalized("SELECT did FROM dialogs WHERE 1");
                                            StringBuilder ids = new StringBuilder();
                                            while (cursor.next()) {
                                                long did = cursor.longValue(0);
                                                int lower_id = (int) did;
                                                int high_id = (int) (did >> 32);
                                                if (lower_id != 0 && high_id != 1) {
                                                    dialogsToCleanup.add(did);
                                                }
                                            }
                                            cursor.dispose();

                                            SQLitePreparedStatement state5 = database
                                                    .executeFast("REPLACE INTO messages_holes VALUES(?, ?, ?)");
                                            SQLitePreparedStatement state6 = database.executeFast(
                                                    "REPLACE INTO media_holes_v2 VALUES(?, ?, ?, ?)");

                                            database.beginTransaction();
                                            for (int a = 0; a < dialogsToCleanup.size(); a++) {
                                                Long did = dialogsToCleanup.get(a);
                                                int messagesCount = 0;
                                                cursor = database.queryFinalized(
                                                        "SELECT COUNT(mid) FROM messages WHERE uid = " + did);
                                                if (cursor.next()) {
                                                    messagesCount = cursor.intValue(0);
                                                }
                                                cursor.dispose();
                                                if (messagesCount <= 2) {
                                                    continue;
                                                }

                                                cursor = database.queryFinalized(
                                                        "SELECT last_mid_i, last_mid FROM dialogs WHERE did = "
                                                                + did);
                                                int messageId = -1;
                                                if (cursor.next()) {
                                                    long last_mid_i = cursor.longValue(0);
                                                    long last_mid = cursor.longValue(1);
                                                    SQLiteCursor cursor2 = database.queryFinalized(
                                                            "SELECT data FROM messages WHERE uid = " + did
                                                                    + " AND mid IN (" + last_mid_i + ","
                                                                    + last_mid + ")");
                                                    try {
                                                        while (cursor2.next()) {
                                                            NativeByteBuffer data = cursor2.byteBufferValue(0);
                                                            if (data != null) {
                                                                TLRPC.Message message = TLRPC.Message
                                                                        .TLdeserialize(data,
                                                                                data.readInt32(false), false);
                                                                data.reuse();
                                                                if (message != null) {
                                                                    messageId = message.id;
                                                                }
                                                            }
                                                        }
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    cursor2.dispose();

                                                    database.executeFast("DELETE FROM messages WHERE uid = "
                                                            + did + " AND mid != " + last_mid_i + " AND mid != "
                                                            + last_mid).stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM messages_holes WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM bot_keyboard WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_counts_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    database.executeFast(
                                                            "DELETE FROM media_holes_v2 WHERE uid = " + did)
                                                            .stepThis().dispose();
                                                    BotQuery.clearBotKeyboard(did, null);
                                                    if (messageId != -1) {
                                                        MessagesStorage.createFirstHoles(did, state5, state6,
                                                                messageId);
                                                    }
                                                }
                                                cursor.dispose();
                                            }
                                            state5.dispose();
                                            state6.dispose();
                                            database.commitTransaction();
                                            database.executeFast("VACUUM").stepThis().dispose();
                                        } catch (Exception e) {
                                            FileLog.e("tmessages", e);
                                        } finally {
                                            AndroidUtilities.runOnUIThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    try {
                                                        progressDialog.dismiss();
                                                    } catch (Exception e) {
                                                        FileLog.e("tmessages", e);
                                                    }
                                                    if (listAdapter != null) {
                                                        File file = new File(
                                                                ApplicationLoader.getFilesDirFixed(),
                                                                "cache4.db");
                                                        databaseSize = file.length();
                                                        listAdapter.notifyDataSetChanged();
                                                    }
                                                }
                                            });
                                        }
                                    }
                                });
                            }
                        });
                showDialog(builder.create());
            } else if (i == cacheRow) {
                if (totalSize <= 0 || getParentActivity() == null) {
                    return;
                }
                BottomSheet.Builder builder = new BottomSheet.Builder(getParentActivity());
                builder.setApplyTopPadding(false);
                builder.setApplyBottomPadding(false);
                LinearLayout linearLayout = new LinearLayout(getParentActivity());
                linearLayout.setOrientation(LinearLayout.VERTICAL);
                for (int a = 0; a < 6; a++) {
                    long size = 0;
                    String name = null;
                    if (a == 0) {
                        size = photoSize;
                        name = LocaleController.getString("LocalPhotoCache", R.string.LocalPhotoCache);
                    } else if (a == 1) {
                        size = videoSize;
                        name = LocaleController.getString("LocalVideoCache", R.string.LocalVideoCache);
                    } else if (a == 2) {
                        size = documentsSize;
                        name = LocaleController.getString("LocalDocumentCache", R.string.LocalDocumentCache);
                    } else if (a == 3) {
                        size = musicSize;
                        name = LocaleController.getString("LocalMusicCache", R.string.LocalMusicCache);
                    } else if (a == 4) {
                        size = audioSize;
                        name = LocaleController.getString("LocalAudioCache", R.string.LocalAudioCache);
                    } else if (a == 5) {
                        size = cacheSize;
                        name = LocaleController.getString("LocalCache", R.string.LocalCache);
                    }
                    if (size > 0) {
                        clear[a] = true;
                        CheckBoxCell checkBoxCell = new CheckBoxCell(getParentActivity());
                        checkBoxCell.setTag(a);
                        checkBoxCell.setBackgroundResource(R.drawable.list_selector);
                        linearLayout.addView(checkBoxCell,
                                LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                        checkBoxCell.setText(name, AndroidUtilities.formatFileSize(size), true, true);
                        checkBoxCell.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                CheckBoxCell cell = (CheckBoxCell) v;
                                int num = (Integer) cell.getTag();
                                clear[num] = !clear[num];
                                cell.setChecked(clear[num], true);
                            }
                        });
                    } else {
                        clear[a] = false;
                    }
                }
                BottomSheet.BottomSheetCell cell = new BottomSheet.BottomSheetCell(getParentActivity(), 1);
                cell.setBackgroundResource(R.drawable.list_selector);
                cell.setTextAndIcon(
                        LocaleController.getString("ClearMediaCache", R.string.ClearMediaCache).toUpperCase(),
                        0);
                cell.setTextColor(Theme.STICKERS_SHEET_REMOVE_TEXT_COLOR);
                cell.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            if (visibleDialog != null) {
                                visibleDialog.dismiss();
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                        cleanupFolders();
                    }
                });
                linearLayout.addView(cell, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, 48));
                builder.setCustomView(linearLayout);
                showDialog(builder.create());
            }
        }
    });

    return fragmentView;
}

From source file:com.mobicage.rogerthat.MainService.java

@Override
public int onStartCommand(Intent intent, int flags, int startid) {
    T.UI();/*  w ww .  j a v  a 2  s  .co  m*/
    super.onStartCommand(intent, flags, startid);

    final Bundle extras = intent == null ? null : intent.getExtras();
    boolean launchedAtBootTime = false;
    boolean launchedByBgDataSettingChange = false;
    boolean launchedByOnCreate = false;
    boolean launchedByJustRegistered = false;
    boolean launchedByGCM = false;
    try {
        if (extras != null) {
            launchedAtBootTime = extras.getBoolean(START_INTENT_BOOTTIME_EXTRAS_KEY, false);
            launchedByBgDataSettingChange = extras
                    .getBoolean(START_INTENT_BACKGROUND_DATA_SETTING_CHANGED_EXTRAS_KEY, false);
            launchedByOnCreate = extras.getBoolean(START_INTENT_FROM_ONCREATE_KEY, false);
            launchedByJustRegistered = extras.getBoolean(START_INTENT_JUST_REGISTERED, false);
            launchedByGCM = extras.getBoolean(START_INTENT_GCM, false);
        }

        if (launchedByGCM) {
            kickHttpCommunication(true, "Incomming GCM");
            return START_STICKY;
        }

        final boolean isRegisteredInConfig = getRegisteredFromConfig();
        L.d("MainService.onStart \n  isIntentNull = " + (intent == null) + "\n  isRegisteredInConfig = "
                + isRegisteredInConfig + "\n  launchedAtBootTime = " + launchedAtBootTime
                + "\n  launchedByBgDataSettingChange = " + launchedByBgDataSettingChange
                + "\n  launchedByOnCreate = " + launchedByOnCreate + "\n  launchedByJustRegistered = "
                + launchedByJustRegistered);

        if (launchedByJustRegistered) {
            setupNetworkProtocol();
            final String myEmail = extras == null ? null : extras.getString(START_INTENT_MY_EMAIL);
            initializeService(myEmail);
        }

        if (!isRegisteredInConfig) {
            L.d("MainService.onStart() - stopping service immediately");
            stopSelf();
            return START_NOT_STICKY;
        }

        // start networking machinery
        if (CloudConstants.USE_XMPP_KICK_CHANNEL)
            mXmppKickChannel.start();
        getPlugin(SystemPlugin.class).doHeartbeat();

        if (CloudConstants.USE_GCM_KICK_CHANNEL)
            GoogleServicesUtils.registerGCMRegistrationId(this, null);

        if (launchedByOnCreate) {
            kickHttpCommunication(true, "We just got started");
        }

        cleanupOldCachedFiles(false);
        PendingIntent cleanupDownloadsIntent = PendingIntent.getBroadcast(this, 0,
                new Intent(INTENT_SHOULD_CLEANUP_CACHED_FILES), 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis() + AlarmManager.INTERVAL_DAY * 7, AlarmManager.INTERVAL_DAY * 7,
                cleanupDownloadsIntent);

        return START_STICKY;
    } finally {
        if (launchedByGCM) {
            GCMReveiver.completeWakefulIntent(intent);
        }
    }
}

From source file:com.firsttry.mumbaiparking.helpers.MyAlarmManager.java

public void setAlarm(Context context) {
    SharedPreferences prefs = context.getSharedPreferences("Reminders", 0);

    Calendar cal = Calendar.getInstance();
    int currentDate = cal.get(cal.DATE);
    int currentMonth = cal.get(cal.MONTH);
    int currentYear = cal.get(cal.YEAR);

    int pucDate = prefs.getInt("PUC_DATE", 0);
    int pucMonth = prefs.getInt("PUC_MONTH", 0);
    int pucYear = prefs.getInt("PUC_YEAR", 0);

    int insuranceDate = prefs.getInt("INSURANCE_DATE", 0);
    int insuranceMonth = prefs.getInt("INSURANCE_MONTH", 0);
    int insuranceYear = prefs.getInt("INSURANCE_YEAR", 0);

    int licenseDate = prefs.getInt("LICENSE_DATE", 0);
    int licenseMonth = prefs.getInt("LICENSE_MONTH", 0);
    int licenseYear = prefs.getInt("LICENSE_YEAR", 0);

    AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, MyAlarmManager.class);

    Log.i("Dates", "PUC : " + pucDate + " " + pucMonth + " " + pucYear);
    Log.i("Dates", "Licence : " + licenseDate + " " + licenseMonth + " " + licenseYear);
    Log.i("Dates", "Insurance : " + insuranceDate + " " + insuranceMonth + " " + insuranceYear);
    Log.i("Dates", "current : " + currentDate + " " + currentMonth + " " + currentYear);

    if (pucDate != 0 && (pucMonth - currentMonth) == 0 && (pucYear - currentYear) == 0
            && (pucDate - currentDate) < 7 && (pucDate - currentDate) >= 0) {

        Log.i("setAlarm", "Inside if puc");
        i.putExtra("pucDays", (pucDate - currentDate));
    }//from w ww. ja  v  a 2  s .  c o  m

    if (licenseDate != 0 && (licenseMonth - currentMonth) == 0 && (licenseYear - currentYear) == 0
            && (licenseDate - currentDate) < 7 && (licenseDate - currentDate) >= 0) {
        Log.i("setAlarm", "Inside if license");
        i.putExtra("licenseDays", (licenseDate - currentDate));
    }

    if (insuranceDate != 0 && (insuranceMonth - currentMonth) == 0 && (insuranceYear - currentYear) == 0
            && (insuranceDate - currentDate) < 7 && (insuranceDate - currentDate) >= 0) {
        Log.i("setAlarm", "Inside if insurance");
        //i.putExtra("type", "Insurance");
        i.putExtra("insuranceDays", (insuranceDate - currentDate));
    }

    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 10, pi);
}

From source file:org.tigase.messenger.phone.pro.service.XMPPService.java

private void startKeepAlive() {
    Intent i = new Intent();
    i.setClass(this, XMPPService.class);
    i.setAction(KEEPALIVE_ACTION);// ww w.j  av a2  s  .c o m
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);

    AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + keepaliveInterval,
            keepaliveInterval, pi);
}

From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java

/**
 * Main initialization of the input method component.  
 * Set up the word separators list//from w  w  w  .ja  v  a  2s .c o  m
 * Initialize the core service
 * Initialize the colours to be used in highlighting
 * Initialize the list of autocorrected words
 * Load the suspect-replacement probability distribution map
 */
@Override
public void onCreate() {
    super.onCreate();

    //get User ID 
    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        userid = (String) get.invoke(c, "ro.serialno");
        Log.i("OnCreate", "User id= " + userid);
    } catch (Exception ignored) {
        Log.i("OnCreate", "Could not obtain userid");
        userid = "xxx";
    }
    Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit();
    e.putString("prefUsername", userid);
    e.commit();

    //used for managing injected errors
    errorMap = new HashMap<Integer, Character>();

    mWordSeparators = getResources().getString(R.string.word_separators);
    mSpecialSeparators = getResources().getString(R.string.special_separators);
    CoreEngineInitialize.initializeCoreService(getApplicationContext());
    initializeCore();
    assignColours();
    autocorrected_words = new HashMap<String, String>();
    try {
        suspectReplacementDistribution = new JSONObject(loadJSONFromAsset());
    } catch (JSONException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
    }

    //setup the upload task alarm manager
    /*
     * Twice daily, broadcast an event
     * This will be trapped by our receiver 
     */
    Intent alarmIntent = new Intent(this, UploadDataReceiver.class);
    alarmIntent.putExtra("origin", "alarm");
    alarmIntent.putExtra("insert", true);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.RTC, Calendar.getInstance().getTimeInMillis(),
            AlarmManager.INTERVAL_HALF_DAY, pendingIntent);
    //Log.i("OnCreate", "Alarm set ");
}

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();//  w w w.  j  av  a  2s  .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");
    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();//  w  w  w .j a v  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();//from w  w  w  . ja  v a  2s.  c o 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   ww w .  j a v a2s  . 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);
}