Search in sources :

Example 81 with AlarmManager

use of android.app.AlarmManager in project android_frameworks_base by crdroidandroid.

the class NetworkStatsServiceTest method setUp.

@Override
public void setUp() throws Exception {
    super.setUp();
    mServiceContext = new BroadcastInterceptingContext(getContext());
    mStatsDir = getContext().getFilesDir();
    if (mStatsDir.exists()) {
        IoUtils.deleteContents(mStatsDir);
    }
    mNetManager = createMock(INetworkManagementService.class);
    // TODO: Mock AlarmManager when migrating this test to Mockito.
    AlarmManager alarmManager = (AlarmManager) mServiceContext.getSystemService(Context.ALARM_SERVICE);
    mTime = createMock(TrustedTime.class);
    mSettings = createMock(NetworkStatsSettings.class);
    mConnManager = createMock(IConnectivityManager.class);
    PowerManager powerManager = (PowerManager) mServiceContext.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
    mService = new NetworkStatsService(mServiceContext, mNetManager, alarmManager, wakeLock, mTime, TelephonyManager.getDefault(), mSettings, new NetworkStatsObservers(), mStatsDir, getBaseDir(mStatsDir));
    mHandlerThread = new IdleableHandlerThread("HandlerThread");
    mHandlerThread.start();
    Handler.Callback callback = new NetworkStatsService.HandlerCallback(mService);
    mHandler = new Handler(mHandlerThread.getLooper(), callback);
    mService.setHandler(mHandler, callback);
    mService.bindConnectivityManager(mConnManager);
    mElapsedRealtime = 0L;
    expectCurrentTime();
    expectDefaultSettings();
    expectNetworkStatsUidDetail(buildEmptyStats());
    expectSystemReady();
    // catch INetworkManagementEventObserver during systemReady()
    final Capture<INetworkManagementEventObserver> networkObserver = new Capture<INetworkManagementEventObserver>();
    mNetManager.registerObserver(capture(networkObserver));
    expectLastCall().atLeastOnce();
    replay();
    mService.systemReady();
    mSession = mService.openSession();
    verifyAndReset();
    mNetworkObserver = networkObserver.getValue();
}
Also used : TrustedTime(android.util.TrustedTime) INetworkManagementService(android.os.INetworkManagementService) BroadcastInterceptingContext(com.android.server.BroadcastInterceptingContext) Handler(android.os.Handler) IdleHandler(android.os.MessageQueue.IdleHandler) Capture(org.easymock.Capture) NetworkStatsSettings(com.android.server.net.NetworkStatsService.NetworkStatsSettings) PowerManager(android.os.PowerManager) NetworkStatsService(com.android.server.net.NetworkStatsService) IAlarmManager(android.app.IAlarmManager) AlarmManager(android.app.AlarmManager) INetworkManagementEventObserver(android.net.INetworkManagementEventObserver) IConnectivityManager(android.net.IConnectivityManager)

Example 82 with AlarmManager

use of android.app.AlarmManager in project android_frameworks_base by DirtyUnicorns.

the class ScheduleConditionProvider method updateAlarm.

private void updateAlarm(long now, long time) {
    final AlarmManager alarms = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    final PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, REQUEST_CODE_EVALUATE, new Intent(ACTION_EVALUATE).addFlags(Intent.FLAG_RECEIVER_FOREGROUND).putExtra(EXTRA_TIME, time), PendingIntent.FLAG_UPDATE_CURRENT);
    alarms.cancel(pendingIntent);
    if (time > now) {
        if (DEBUG)
            Slog.d(TAG, String.format("Scheduling evaluate for %s, in %s, now=%s", ts(time), formatDuration(time - now), ts(now)));
        alarms.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    } else {
        if (DEBUG)
            Slog.d(TAG, "Not scheduling evaluate");
    }
}
Also used : AlarmManager(android.app.AlarmManager) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent)

Example 83 with AlarmManager

use of android.app.AlarmManager in project Talon-for-Twitter by klinker24.

the class HomeFragment method doRefresh.

public int doRefresh() {
    int numberNew = 0;
    if (TimelineRefreshService.isRunning || WidgetRefreshService.isRunning || CatchupPull.isRunning) {
        // quit if it is running in the background
        return 0;
    }
    try {
        Cursor cursor = cursorAdapter.getCursor();
        if (cursor.moveToLast()) {
            long id = cursor.getLong(cursor.getColumnIndex(HomeSQLiteHelper.COLUMN_TWEET_ID));
            sharedPrefs.edit().putLong("current_position_" + currentAccount, id).commit();
            HomeDataSource.getInstance(context).markPosition(currentAccount, id);
        // HomeContentProvider.updateCurrent(currentAccount, context, id);
        }
    } catch (Exception e) {
    }
    boolean needClose = false;
    context.sendBroadcast(new Intent("com.klinker.android.twitter.CLEAR_PULL_UNREAD"));
    twitter = Utils.getTwitter(context, settings);
    final List<twitter4j.Status> statuses = new ArrayList<twitter4j.Status>();
    boolean foundStatus = false;
    Paging paging = new Paging(1, 200);
    long[] lastId = null;
    long id;
    try {
        lastId = HomeDataSource.getInstance(context).getLastIds(currentAccount);
        id = lastId[1];
    } catch (Exception e) {
        id = sharedPrefs.getLong("account_" + currentAccount + "_lastid", 1l);
    }
    Log.v("talon_inserting", "since_id=" + id);
    try {
        paging.setSinceId(id);
    } catch (Exception e) {
    // 0 for some reason, so dont set one and let the database sort which should show and which shouldn't
    }
    long beforeDownload = Calendar.getInstance().getTimeInMillis();
    for (int i = 0; i < settings.maxTweetsRefresh; i++) {
        try {
            if (!foundStatus) {
                paging.setPage(i + 1);
                List<Status> list = twitter.getHomeTimeline(paging);
                statuses.addAll(list);
                if (statuses.size() <= 1 || statuses.get(statuses.size() - 1).getId() == lastId[0]) {
                    Log.v("talon_inserting", "found status");
                    foundStatus = true;
                } else {
                    Log.v("talon_inserting", "haven't found status");
                    foundStatus = false;
                }
            }
        } catch (TwitterException e) {
            Log.v("talon_error", "code: " + e.getErrorCode());
            if (e.getErrorCode() == 88) {
                // rate limit reached
                rateLimited = true;
                foundStatus = true;
                return 0;
            }
        } catch (Exception e) {
            // the page doesn't exist
            e.printStackTrace();
            Log.v("talon_error", "error with refresh");
            foundStatus = true;
        } catch (OutOfMemoryError o) {
        // don't know why...
        }
    }
    long afterDownload = Calendar.getInstance().getTimeInMillis();
    Log.v("talon_inserting", "downloaded " + statuses.size() + " tweets in " + (afterDownload - beforeDownload));
    if (statuses.size() > 0) {
        statuses.remove(statuses.size() - 1);
    }
    HashSet hs = new HashSet();
    hs.addAll(statuses);
    statuses.clear();
    statuses.addAll(hs);
    Log.v("talon_inserting", "tweets after hashset: " + statuses.size());
    manualRefresh = false;
    if (needClose) {
        HomeDataSource.dataSource = null;
        Log.v("talon_home_frag", "sending the reset home broadcase in needclose section");
        dontGetCursor = true;
        context.sendBroadcast(new Intent("com.klinker.android.twitter.RESET_HOME"));
    }
    if (lastId == null) {
        try {
            lastId = HomeDataSource.getInstance(context).getLastIds(currentAccount);
        } catch (Exception e) {
            // let the
            lastId = new long[] { 0, 0, 0, 0, 0 };
        }
    }
    try {
        numberNew = insertTweets(statuses, lastId);
    } catch (NullPointerException e) {
        return 0;
    }
    if (numberNew > statuses.size()) {
        numberNew = statuses.size();
    }
    if (numberNew > 0 && statuses.size() > 0) {
        sharedPrefs.edit().putLong("account_" + currentAccount + "_lastid", statuses.get(0).getId()).commit();
    }
    Log.v("talon_inserting", "inserted " + numberNew + " tweets in " + (Calendar.getInstance().getTimeInMillis() - afterDownload));
    // numberNew = statuses.size();
    unread = numberNew;
    statuses.clear();
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    long now = new Date().getTime();
    long alarm = now + settings.timelineRefresh;
    PendingIntent pendingIntent = PendingIntent.getService(context, HOME_REFRESH_ID, new Intent(context, TimelineRefreshService.class), 0);
    if (settings.timelineRefresh != 0)
        am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.timelineRefresh, pendingIntent);
    else
        am.cancel(pendingIntent);
    int unreadCount;
    try {
        unreadCount = HomeDataSource.getInstance(context).getUnreadCount(currentAccount);
    } catch (Exception e) {
        unreadCount = numberNew;
    }
    return unreadCount;
}
Also used : Status(twitter4j.Status) TimelineRefreshService(com.klinker.android.twitter.services.TimelineRefreshService) Paging(twitter4j.Paging) ArrayList(java.util.ArrayList) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) Cursor(android.database.Cursor) TwitterException(twitter4j.TwitterException) StaleDataException(android.database.StaleDataException) Date(java.util.Date) AlarmManager(android.app.AlarmManager) PendingIntent(android.app.PendingIntent) TwitterException(twitter4j.TwitterException) HashSet(java.util.HashSet)

Example 84 with AlarmManager

use of android.app.AlarmManager in project instructure-android by instructure.

the class AlarmReceiver method setAlarm.

public void setAlarm(Context context, Calendar calendar, long assignmentId, String title, String subTitle) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent i = new Intent(context, AlarmReceiver.class);
    i.putExtra(Const.TITLE_TEXT, title);
    i.putExtra(Const.SUBTITLE_TEXT, subTitle);
    // set alarms here
    // get the row id and set it as the request code so it will be unique
    int alarmId = -1;
    DatabaseHandler mDatabaseHandler = new DatabaseHandler(context);
    try {
        mDatabaseHandler.open();
        alarmId = mDatabaseHandler.getRowIdByAssignmentId(assignmentId);
        mDatabaseHandler.close();
    } catch (SQLException e) {
    // can't find the alarmId
    }
    // verify that we have a valid alarm id
    if (alarmId != -1) {
        PendingIntent pi = PendingIntent.getBroadcast(context, alarmId, i, PendingIntent.FLAG_UPDATE_CURRENT);
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
    }
}
Also used : SQLException(java.sql.SQLException) DatabaseHandler(com.instructure.parentapp.database.DatabaseHandler) AlarmManager(android.app.AlarmManager) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) PendingIntent(android.app.PendingIntent)

Example 85 with AlarmManager

use of android.app.AlarmManager in project android_packages_apps_Settings by LineageOS.

the class TimePreferenceController method setTime.

void setTime(int hourOfDay, int minute) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    long when = Math.max(c.getTimeInMillis(), TimePreferenceHost.MIN_DATE);
    if (when / 1000 < Integer.MAX_VALUE) {
        ((AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE)).setTime(when);
    }
}
Also used : Calendar(java.util.Calendar) AlarmManager(android.app.AlarmManager)

Aggregations

AlarmManager (android.app.AlarmManager)471 PendingIntent (android.app.PendingIntent)349 Intent (android.content.Intent)323 Calendar (java.util.Calendar)75 SuppressLint (android.annotation.SuppressLint)24 Date (java.util.Date)24 Context (android.content.Context)22 SharedPreferences (android.content.SharedPreferences)20 SimpleDateFormat (java.text.SimpleDateFormat)18 Test (org.junit.Test)17 VisibleForTesting (com.android.internal.annotations.VisibleForTesting)13 Config (org.robolectric.annotation.Config)13 Handler (android.os.Handler)11 HashMap (java.util.HashMap)11 PowerManager (android.os.PowerManager)10 File (java.io.File)10 Map (java.util.Map)10 Activity (android.app.Activity)9 ShadowAlarmManager (org.robolectric.shadows.ShadowAlarmManager)9 TargetApi (android.annotation.TargetApi)8