Example usage for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

List of usage examples for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

Introduction

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

Prototype

int ELAPSED_REALTIME_WAKEUP

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

Click Source Link

Document

Alarm time in android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime() (time since boot, including sleep), which will wake up the device when it goes off.

Usage

From source file:alaindc.crowdroid.SendIntentService.java

private void handleActionReceivedData(String response) {

    // Data got from server response
    int timeout; // sec
    double radius; // meters
    int sensor;/*from  w  w w  .jav  a 2  s  . c o  m*/
    double latitude, longitude;

    // Update view sending a broadcast intent
    Intent intent = new Intent(Constants.INTENT_RECEIVED_DATA);
    intent.putExtra(Constants.INTENT_RECEIVED_DATA_EXTRA_DATA, response);
    LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

    try {
        JSONArray jsonArray = new JSONArray(response);
        JSONObject jsonObject = jsonArray.getJSONObject(0);

        sensor = jsonObject.getInt("sensor");
        // For time homogeneity
        timeout = jsonObject.getInt("timeout");
        // For space homogeneity
        radius = jsonObject.getDouble("radius");
        latitude = jsonObject.getDouble("lat");
        longitude = jsonObject.getDouble("long");

    } catch (JSONException e) {
        return;
    }

    if (sensor == Constants.TYPE_TEL) {
        SharedPreferences sharedPref = getApplicationContext().getSharedPreferences(Constants.PREF_FILE,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean(Constants.THROUGHPUT_TAKEN, false);
        editor.commit();
    }

    Intent geofenceIntent = new Intent(getApplicationContext(), GeofenceIntentService.class);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_SENSORTYPE, sensor);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_LATITUDE, latitude);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_LONGITUDE, longitude);
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_RADIUS, String.valueOf(radius));
    geofenceIntent.putExtra(Constants.EXTRA_GEOFENCE_EXPIRE_MILLISEC, String.valueOf(timeout * 1000));
    getApplicationContext().startService(geofenceIntent);

    // Set timeout based on server response
    alarmMgr = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Intent intentAlarm = new Intent(getApplicationContext(), SendIntentService.class);
    intentAlarm.setAction(Constants.ACTION_SENDDATA + sensor);
    intentAlarm.putExtra(Constants.EXTRA_TYPE_OF_SENSOR_TO_SEND, sensor);
    alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intentAlarm, 0);

    int seconds = timeout;
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + seconds * 1000,
            alarmIntent);
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

@Override
public void onCreate() {
    Log.d(TAG, "created");
    super.onCreate();

    partialWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
            .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "RMBTLoopWakeLock");
    partialWakeLock.acquire();/*  w w w  .  j  a v  a 2s.c o  m*/

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    readConfig();

    geoLocation = new LocalGeoLocation(this);
    geoLocation.start();

    notificationBuilder = createNotificationBuilder();

    startForeground(NotificationIDs.LOOP_ACTIVE, notificationBuilder.build());
    final IntentFilter actionFilter = new IntentFilter(RMBTService.BROADCAST_TEST_FINISHED);
    actionFilter.addAction(RMBTService.BROADCAST_TEST_ABORTED);
    registerReceiver(receiver, actionFilter);

    final IntentFilter rmbtTaskActionFilter = new IntentFilter(RMBTTask.BROADCAST_TEST_START);
    registerReceiver(rmbtTaskReceiver, rmbtTaskActionFilter);

    final Intent alarmIntent = new Intent(ACTION_ALARM, null, this, getClass());
    alarm = PendingIntent.getService(this, 0, alarmIntent, 0);

    if (ConfigHelper.isLoopModeWakeLock(this)) {
        Log.d(TAG, "using dimWakeLock");
        dimWakeLock = ((PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE))
                .newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
                        | PowerManager.ON_AFTER_RELEASE, "RMBTLoopDimWakeLock");
        dimWakeLock.acquire();

        final Intent wakeupAlarmIntent = new Intent(ACTION_WAKEUP_ALARM, null, this, getClass());
        wakeupAlarm = PendingIntent.getService(this, 0, wakeupAlarmIntent, 0);

        final long now = SystemClock.elapsedRealtime();
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + 10000, 10000, wakeupAlarm);
    }

    bindService(new Intent(getApplicationContext(), RMBTService.class), this, BIND_AUTO_CREATE);
}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

private void setAlarm(long millis) {
    Log.d(TAG, "setAlarm: " + millis);

    final long now = SystemClock.elapsedRealtime();
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, now + millis, alarm);
}

From source file:com.achow101.bitcointalkforum.MainActivity.java

public void onResume() {
    super.onResume();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    int seconds = Integer.parseInt(prefs.getString("notifications_sync_freq", "60"));
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra("SESSION ID", sessId);
    i.putExtra("Username", mUsername);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    am.cancel(pi);/* w  w  w .j  av  a2 s. c o  m*/

    if (prefs.getBoolean("notifications_new_message", true)) {
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + seconds * 1000, seconds * 1000, pi);
    }
}

From source file:com.android.deskclock.timer.TimerReceiver.java

private void updateNextTimesup(Context context) {
    TimerObj t = getNextRunningTimer(mTimers, false, Utils.getTimeNow());
    long nextTimesup = (t == null) ? -1 : t.getTimesupTime();
    int timerId = (t == null) ? -1 : t.mTimerId;

    Intent intent = new Intent();
    intent.setAction(Timers.TIMES_UP);//from www.  java2s  .c  o m
    intent.setClass(context, TimerReceiver.class);
    // Time-critical, should be foreground
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    if (!mTimers.isEmpty()) {
        intent.putExtra(Timers.TIMER_INTENT_EXTRA, timerId);
    }
    AlarmManager mngr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent p = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    if (t != null) {
        if (Utils.isKitKatOrLater()) {
            mngr.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        } else {
            mngr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, nextTimesup, p);
        }
        if (Timers.LOGGING) {
            Log.d(TAG, "Setting times up to " + nextTimesup);
        }
    } else {
        // if no timer is found Pending Intents should be canceled
        // to keep the internal state consistent with the UI
        mngr.cancel(p);
        p.cancel();
        if (Timers.LOGGING) {
            Log.v(TAG, "no next times up");
        }
    }
}

From source file:com.psiphon3.psiphonlibrary.UpgradeChecker.java

/**
 * Creates the periodic alarm used to check for updates. Can be called unconditionally; it
 * handles cases when the alarm is already created.
 * @param appContext The application context.
 *///w w w . j  a v a  2s  .c  o  m
private static void createAlarm(Context appContext) {
    if (!allowedToSelfUpgrade(appContext)) {
        // Don't waste resources with an alarm if we can't possibly self-upgrade.
        log(appContext, R.string.upgrade_checker_no_alarm_no_selfupgrading, MyLog.Sensitivity.NOT_SENSITIVE,
                Log.WARN);
        return;
    }

    Intent intent = new Intent(appContext, UpgradeChecker.class);
    intent.setAction(ALARM_INTENT_ACTION);

    boolean alarmExists = (PendingIntent.getBroadcast(appContext, ALARM_INTENT_REQUEST_CODE, intent,
            PendingIntent.FLAG_NO_CREATE) != null);

    if (alarmExists) {
        log(appContext, R.string.upgrade_checker_alarm_exists, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);
        return;
    }

    log(appContext, R.string.upgrade_checker_creating_alarm, MyLog.Sensitivity.NOT_SENSITIVE, Log.WARN);

    PendingIntent alarmIntent = PendingIntent.getBroadcast(appContext, ALARM_INTENT_REQUEST_CODE, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmMgr = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_FIFTEEN_MINUTES,
            AlarmManager.INTERVAL_HALF_DAY, alarmIntent);
}

From source file:org.simlar.SimlarService.java

private void startKeepAwake() {
    final Intent startIntent = new Intent("org.simlar.keepAwake");
    mkeepAwakePendingIntent = PendingIntent.getBroadcast(this, 0, startIntent, 0);

    ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 600000, 600000, mkeepAwakePendingIntent);

    IntentFilter filter = new IntentFilter();
    filter.addAction("org.simlar.keepAwake");
    registerReceiver(mKeepAwakeReceiver, filter);
}

From source file:com.swetha.easypark.GetIndividualParkingSpotDetails.java

private void scheduleNotification(Notification notification) {

    Intent notificationIntent = new Intent(this, NotificationPublisher.class);
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, Integer.parseInt(theParkingSpotId));
    notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    long currentTimeInLong = DateTimeHelpers
            .convertToLongFromTime(DateTimeHelpers.dtf.format(new Date()).toString());
    long delay = toTime - (currentTimeInLong + Constants.tenMinutesInMilliseconds);
    long futureInMills = SystemClock.elapsedRealtime() + delay;

    Log.i("GetIndividualParkingSpotDetails", " Spot has been blocked till long " + toTime);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(toTime));

    Log.i("GetIndividualParkingSpotDetails", " CurrentTime in  long " + currentTimeInLong);
    Log.i("GetIndividualParkingSpotDetails",
            " Spot has been blocked till  DateTime" + DateTimeHelpers.convertToTimeFromLong(currentTimeInLong));

    Log.i("GetIndividualParkingSpotDetails", "value of delay" + delay);
    Log.i("GetIndividualParkingSpotDetails",
            "value of mills in time" + DateTimeHelpers.convertToTimeFromLong(futureInMills));

    Log.i("GetIndividualParkingSpotDetails", "Notification is kept at this mills" + futureInMills);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMills, pendingIntent);

}

From source file:com.lgallardo.youtorrentcontroller.RefreshListener.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get preferences
    getSettings();//w  ww .j  av  a 2  s. c o  m

    // Set alarm for checking completed torrents, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), NotifierService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), NotifierService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                notification_period, alarmIntent);
    }

    // Set alarm for RSS checking, if not set
    if (PendingIntent.getBroadcast(getApplication(), 0, new Intent(getApplication(), RSSService.class),
            PendingIntent.FLAG_NO_CREATE) == null) {

        // Set Alarm for checking completed torrents
        alarmMgr = (AlarmManager) getApplication().getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(getApplication(), RSSService.class);
        alarmIntent = PendingIntent.getBroadcast(getApplication(), 0, intent, 0);

        alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5000,
                AlarmManager.INTERVAL_DAY, alarmIntent);
    }

    // Set Theme (It must be fore inflating or setContentView)
    if (dark_ui) {
        this.setTheme(R.style.Theme_Dark);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
            getWindow().setStatusBarColor(getResources().getColor(R.color.Theme_Dark_toolbarBackground));
        }
    } else {
        this.setTheme(R.style.Theme_Light);

        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().setNavigationBarColor(getResources().getColor(R.color.primary));
        }

    }

    setContentView(R.layout.activity_main);

    toolbar = (Toolbar) findViewById(R.id.app_bar);

    if (dark_ui) {
        toolbar.setBackgroundColor(getResources().getColor(R.color.Theme_Dark_primary));
    }

    setSupportActionBar(toolbar);

    // Set App title
    setTitle(R.string.app_shortname);

    // Drawer menu
    navigationDrawerServerItems = getResources().getStringArray(R.array.qBittorrentServers);
    navigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    //        drawerList = (ListView) findViewById(R.id.left_drawer);

    mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View
    mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are

    ArrayList<ObjectDrawerItem> serverItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> actionItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<ObjectDrawerItem> settingsItems = new ArrayList<ObjectDrawerItem>();

    // Add server category
    serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_servers,
            getResources().getString(R.string.drawer_servers_category), DRAWER_CATEGORY, false, null));

    // Server items
    int currentServerValue = 1;

    try {
        currentServerValue = Integer.parseInt(MainActivity.currentServer);
    } catch (NumberFormatException e) {

    }

    for (int i = 0; i < navigationDrawerServerItems.length; i++) {
        //            Log.d("Debug", "MainActivity - currentServerValue - currentServerValue: " + currentServerValue);
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1): " + (i + 1));
        //            Log.d("Debug", "MainActivity - currentServerValue - (i + 1) == currentServerValue: " + ((i + 1) == currentServerValue));

        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                DRAWER_ITEM_SERVERS, ((i + 1) == currentServerValue), "changeCurrentServer"));

    }

    //
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 1", DRAWER_ITEM_SERVERS, true, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 2", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));
    //        serverItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_subitem, "Server 3", DRAWER_ITEM_SERVERS, false, "changeCurrentServer"));

    // Add actions
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_all, navigationDrawerItemTitles[0],
            DRAWER_ITEM_ACTIONS, lastState.equals("all"), "refreshAll"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_downloading, navigationDrawerItemTitles[1],
            DRAWER_ITEM_ACTIONS, lastState.equals("downloading"), "refreshDownloading"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_completed, navigationDrawerItemTitles[2],
            DRAWER_ITEM_ACTIONS, lastState.equals("completed"), "refreshCompleted"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_paused, navigationDrawerItemTitles[3],
            DRAWER_ITEM_ACTIONS, lastState.equals("pause"), "refreshPaused"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_active, navigationDrawerItemTitles[4],
            DRAWER_ITEM_ACTIONS, lastState.equals("active"), "refreshActive"));
    actionItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_inactive, navigationDrawerItemTitles[5],
            DRAWER_ITEM_ACTIONS, lastState.equals("inactive"), "refreshInactive"));

    // Add settings actions
    //        drawerItems.add(new ObjectDrawerItem(R.drawable.ic_action_options, navigationDrawerItemTitles[6], DRAWER_ITEM_ACTIONS, false, "openOptions"));
    settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_settings, navigationDrawerItemTitles[6],
            DRAWER_ITEM_ACTIONS, false, "openSettings"));
    if (packageName.equals("com.lgallardo.youtorrentcontroller")) {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_pro, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "getPro"));
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[8],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    } else {
        settingsItems.add(new ObjectDrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[7],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    }

    // Set adapter

    rAdapter = new DrawerItemRecyclerViewAdapter(getApplicationContext(), this, serverItems, actionItems,
            settingsItems, null);
    rAdapter.notifyDataSetChanged();

    //        Log.d("Debug", "MainActivity - oldActionPosition: "+ (Arrays.asList(actionStates).indexOf(lastState)));

    //        drawerList.setAdapter(adapter);
    mRecyclerView.setAdapter(rAdapter);

    mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
    mRecyclerView.setLayoutManager(mLayoutManager); // Setting the layout Manager

    // Set selection according to last state
    setSelectionAndTitle(lastState);

    // Set the item click listener
    //        drawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Get drawer title
    title = drawerTitle = getTitle();

    // Add the application icon control code inside MainActivity onCreate

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // New ActionBarDrawerToggle for Google Material Desing (v7)
    drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open,
            R.string.drawer_close) {

        /**
         * Called when a drawer has settled in a completely closed state.
         */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            // getSupportActionBar().setTitle(title);
        }

        /**
         * Called when a drawer has settled in a completely open state.
         */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // getSupportActionBar().setTitle(drawerTitle);
            // setTitle(R.string.app_shortname);
        }
    };

    drawerLayout.setDrawerListener(drawerToggle);
    //        drawerToggle.syncState();               // Finally we set the drawer toggle sync State

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
    getSupportActionBar().setHomeButtonEnabled(false);

    // Get options and save them as shared preferences
    //        qBittorrentOptions qso = new qBittorrentOptions();
    //        qso.execute(new String[]{qbQueryString + "/preferences", "getSettings"});

    // If it were awaked from an intent-filter,
    // Get token and cookie and then
    // get intent from the intent filter and Add URL torrent
    //        Log.d("Debug", "MainActivity - 1");
    new torrentTokenByIntent().execute(getIntent());

    // Fragments

    // Check whether the activity is using the layout version with
    // the fragment_container FrameLayout. If so, we must add the first
    // fragment
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        // if (savedInstanceState != null) {
        // return;
        // }

        // This fragment will hold the list of torrents
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.youtorrentcontroller.ItemstFragment();
        }

        // This fragment will hold the list of torrents
        helpTabletFragment = new HelpFragment();

        // Set the second fragments container
        firstFragment.setSecondFragmentContainer(R.id.content_frame);

        // This i the second fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.list_frame, helpTabletFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.list_frame, helpTabletFragment, "firstFragment");
        }

        if (fragmentManager.findFragmentByTag("secondFragment") == null) {
            fragmentTransaction.add(R.id.content_frame, secondFragment, "secondFragment");
        } else {
            fragmentTransaction.replace(R.id.content_frame, secondFragment, "secondFragment");
        }

        fragmentTransaction.commit();

        // Second fragment will be added in ItemsFRagment's onListItemClick
        // method

    } else {

        // Phones handle just one fragment

        // Create an instance of ItemsFragments
        if (firstFragment == null) {
            firstFragment = new com.lgallardo.youtorrentcontroller.ItemstFragment();
        }
        firstFragment.setSecondFragmentContainer(R.id.one_frame);

        // This is the about fragment, holding a default message at the
        // beginning
        secondFragment = new AboutFragment();

        // If we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        //            if (savedInstanceState != null) {
        //
        //                // Handle Item list empty due to Fragment stack
        //                try {
        //                    FragmentManager fm = getFragmentManager();
        //
        //                    if (fm.getBackStackEntryCount() == 1 && fm.findFragmentById(R.id.one_frame) instanceof com.lgallardo.youtorrentcontroller.TorrentDetailsFragment) {
        //
        //                        refreshCurrent();
        //
        //                    }
        //                }
        //                catch (Exception e) {
        //                }
        //
        //                return;
        //            }

        // Add the fragment to the 'list_frame' FrameLayout
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        if (fragmentManager.findFragmentByTag("firstFragment") == null) {
            fragmentTransaction.add(R.id.one_frame, secondFragment, "firstFragment");
        } else {
            fragmentTransaction.replace(R.id.one_frame, secondFragment, "firstFragment");
        }

        // if torrent details was loaded reset back button stack
        for (int i = 0; i < fragmentManager.getBackStackEntryCount(); ++i) {
            fragmentManager.popBackStack();
        }

        fragmentTransaction.commit();
    }

    // Activity is visible
    activityIsVisible = true;

    // First refresh
    refreshCurrent();

    handler = new Handler();
    handler.postDelayed(m_Runnable, refresh_period);

    // Load banner
    loadBanner();

}

From source file:net.kidlogger.kidlogger.KLService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //List file synchronizer
    listFileSync = new ListFileSync(this);

    // Check a previous file and send the file if exist
    checkPrevFiles();//  www. j  a v a 2 s.c o  m

    // Handle outgoing call delay 
    mHandler = new Handler() {
        public void handleMessage(Message msg) {
            String message = (String) msg.obj;
            if (message == null)
                return;
            //Log.i("KLS", "message: " + message);
            if (message.equals("start")) {
                delayNewCallEvent = new CountDownTimer(15000L, 1000L) {
                    public void onTick(long millisUntilFinish) {
                    }

                    public void onFinish() {
                        new Thread(new Runnable() {
                            public void run() {
                                //Log.i("KLS", "doAfterDelay");
                                doAfterDelay();
                            }
                        }).start();
                    }
                }.start();
            } else if (message.equals("stop")) {
                //Log.i("KLS", "Stop delay");
                if (delayNewCallEvent != null) {
                    delayNewCallEvent.cancel();
                    delayNewCallEvent = null;
                }
            }
        }
    };

    // Define a BroadcastReceiver to detect if date is changed
    /*dateChanged = new BroadcastReceiver(){
       public void onReceive(Context context, Intent intent){
    String action = intent.getAction();
                  
    if(action != null && action.equals(Intent.ACTION_DATE_CHANGED)){
       new Thread(new Runnable(){
          public void run(){
             checkPrevFiles();
             app.logError(CN, "Date is changed");
          }
       }).start();
    }            
       }
    };
    IntentFilter filter = new IntentFilter(Intent.ACTION_DATE_CHANGED);      
    registerReceiver(dateChanged, filter);*/

    // Stub of remote service
    remoteServiceStub = new IRemoteService.Stub() {
        public void sendString(String string) throws RemoteException {
            runKeyEvent(string);
        }
    };

    // Setup things to log
    setupLogging();

    // Uploading files      
    if (Settings.uploadLogs(this)) {
        mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        if (mAlarmManager == null) {
            app.logError(CN + "onStartCommand", "Couldn't get AlarmManager");
            uploadOn = false;
        } else {
            //Intent i = new Intent(this, AlarmReceiver.class);
            Intent i = new Intent(KLService.ALARM_ACTION);
            mPI = PendingIntent.getBroadcast(this, 0, i, 0);
            mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
                    postSendingFreq, mPI);
        }

        //---------------------------------------------------------------------------------
        /*mUploadData = new Runnable(){
           public void run(){
              new Thread(new Runnable(){
          public void run(){
             //doSendingFile();
             doSendHtml();
             checkDate();
             if(!mIsRoaming)
                doSendMedia();
          }
              }).start();
              handlering.postDelayed(mUploadData, postSendingFreq);
           }            
        };
        handlering.postDelayed(mUploadData, postSendingFreq);*/
        //---------------------------------------------------------------------------------
        uploadOn = true;
    }

    // Log power
    boolean powerOn = getBoolPref("powerOff");
    if (powerOn) {
        new Thread(new Runnable() {
            public void run() {
                sync.writeLog(".htm", Templates.getPowerLog(false));
            }
        }).start();
        //WriteThread wpl = new WriteThread(sync, ".htm", Templates.getPowerLog(false));

        saveToPref("powerOff", false);
    }

    // Log start service
    logServiceState(true);

    app.mService = this;
    app.mServiceOnCreate = false;

    //Log.i(CN + "onStartCommand", "onStartCommand");

    return START_STICKY;
}