Example usage for android.app PendingIntent getBroadcast

List of usage examples for android.app PendingIntent getBroadcast

Introduction

In this page you can find the example usage for android.app PendingIntent getBroadcast.

Prototype

public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will perform a broadcast, like calling Context#sendBroadcast(Intent) Context.sendBroadcast() .

Usage

From source file:com.crearo.gpslogger.GpsLoggingService.java

private void cancelAlarm() {
    if (alarmIntent != null) {
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, alarmIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        am.cancel(sender);/*w ww  .  j av  a2 s .  c o  m*/
    }
}

From source file:be.ugent.zeus.hydra.util.audiostream.MusicService.java

/**
 * Starts playing the next song. If manualUrl is null, the next song will be randomly selected
 * from our Media Retriever (that is, it will be a random song in the user's device). If
 * manualUrl is non-null, then it specifies the URL or path to the song that will be played
 * next.//from  w  ww . ja  va  2 s . c o m
 */
void playmp3(String mp3url) {
    mState = State.Stopped;
    relaxResources(false); // release everything except MediaPlayer

    try {
        // set the source of the media player to a manual URL or path
        createMediaPlayerIfNeeded();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setDataSource(mp3url);
        mIsStreaming = true;

        mSongTitle = "Urgent.fm";

        mState = State.Preparing;
        setUpAsForeground(mSongTitle + " (loading)");

        // Use the media button APIs (if available) to register ourselves for media button
        // events

        MediaButtonHelper.registerMediaButtonEventReceiverCompat(mAudioManager, mMediaButtonReceiverComponent);

        // Use the remote control APIs (if available) to set the playback state

        if (mRemoteControlClientCompat == null) {
            Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON);
            intent.setComponent(mMediaButtonReceiverComponent);
            mRemoteControlClientCompat = new RemoteControlClientCompat(PendingIntent.getBroadcast(
                    this /*context*/, 0 /*requestCode, ignored*/, intent /*intent*/, 0 /*flags*/));
            RemoteControlHelper.registerRemoteControlClient(mAudioManager, mRemoteControlClientCompat);
        }

        mRemoteControlClientCompat.setPlaybackState(RemoteControlClient.PLAYSTATE_PLAYING);

        mRemoteControlClientCompat.setTransportControlFlags(RemoteControlClient.FLAG_KEY_MEDIA_PLAY
                | RemoteControlClient.FLAG_KEY_MEDIA_PAUSE | RemoteControlClient.FLAG_KEY_MEDIA_STOP);

        // Update the remote controls
        mRemoteControlClientCompat.editMetadata(true)
                .putString(MediaMetadataRetriever.METADATA_KEY_TITLE, "Urgent.fm")
                .putBitmap(RemoteControlClientCompat.MetadataEditorCompat.METADATA_KEY_ARTWORK, mDummyAlbumArt)
                .apply();

        // starts preparing the media player in the background. When it's done, it will call
        // our OnPreparedListener (that is, the onPrepared() method on this class, since we set
        // the listener to 'this').
        //
        // Until the media player is prepared, we *cannot* call start() on it!
        mPlayer.prepareAsync();

        // If we are streaming from the internet, we want to hold a Wifi lock, which prevents
        // the Wifi radio from going to sleep while the song is playing. If, on the other hand,
        // we are *not* streaming, we want to release the lock if we were holding it before.
        if (mIsStreaming) {
            mWifiLock.acquire();
        } else if (mWifiLock.isHeld()) {
            mWifiLock.release();
        }
    } catch (IOException ex) {
        Log.e("MusicService", "IOException playing next song: " + ex.getMessage());
        ex.printStackTrace();
    }
}

From source file:com.google.android.libraries.cast.companionlibrary.notification.VideoCastNotificationService.java

/**
 * Returns the {@link NotificationCompat.Action} for forwarding the current media by
 * {@code millis} milliseconds./*from   w ww.  j a v  a 2s. c o  m*/
 */
protected NotificationCompat.Action getForwardAction(long millis) {
    Intent intent = new Intent(ACTION_FORWARD);
    intent.setPackage(getPackageName());
    intent.putExtra(EXTRA_FORWARD_STEP_MS, (int) millis);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    int iconResourceId = R.drawable.ic_notification_forward_48dp;
    if (millis == TEN_SECONDS_MILLIS) {
        iconResourceId = R.drawable.ic_notification_forward10_48dp;
    } else if (millis == THIRTY_SECONDS_MILLIS) {
        iconResourceId = R.drawable.ic_notification_forward30_48dp;
    }

    return new NotificationCompat.Action.Builder(iconResourceId, getString(R.string.ccl_forward), pendingIntent)
            .build();
}

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

private void showCollapsedNotificationWithNext(final Context context, String title, String text,
        Long nextBroadcastTime) {
    LogUtils.d(TAG, "showCollapsedNotificationWithNext nextBroadcastTime: %d", nextBroadcastTime);
    Intent activityIntent = new Intent(context, DeskClock.class);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activityIntent.putExtra(DeskClock.SELECT_TAB_INTENT_EXTRA, DeskClock.TIMER_TAB_INDEX);
    PendingIntent pendingActivityIntent = PendingIntent.getActivity(context, 0, activityIntent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);
    showCollapsedNotification(context, title, text, NotificationCompat.PRIORITY_HIGH, pendingActivityIntent,
            IN_USE_NOTIFICATION_ID, false);

    if (nextBroadcastTime == null) {
        return;/*from w  w w.  ja  v a2 s . c om*/
    }
    Intent nextBroadcast = new Intent();
    nextBroadcast.setAction(Timers.NOTIF_IN_USE_SHOW);
    PendingIntent pendingNextBroadcast = PendingIntent.getBroadcast(context, 0, nextBroadcast, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    if (Utils.isKitKatOrLater()) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, nextBroadcastTime, pendingNextBroadcast);
    }
}

From source file:com.irccloud.android.activity.PastebinViewerActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        finish();/*from  w  w w .  j a  v a  2s .c om*/
        if (getWindowManager().getDefaultDisplay().getWidth() < TypedValue
                .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 800, getResources().getDisplayMetrics())
                || isMultiWindow())
            overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right);
        return true;
    } else if (item.getItemId() == R.id.delete) {
        if (Uri.parse(url).getQueryParameter("own_paste").equals("1")) {
            AlertDialog.Builder builder = new AlertDialog.Builder(PastebinViewerActivity.this);
            builder.setTitle("Delete Snippet");
            builder.setMessage("Are you sure you want to delete this snippet?");
            builder.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    NetworkConnection.getInstance().delete_paste(Uri.parse(url).getQueryParameter("id"));
                    finish();
                    Toast.makeText(PastebinViewerActivity.this, "Snippet deleted", Toast.LENGTH_SHORT).show();
                }
            });
            builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            });
            AlertDialog d = builder.create();
            d.setOwnerActivity(PastebinViewerActivity.this);
            d.show();
        }
    } else if (item.getItemId() == R.id.action_linenumbers) {
        item.setChecked(!item.isChecked());
        mWebView.loadUrl("javascript:window.PASTEVIEW.doToggleLines()");
    } else if (item.getItemId() == R.id.action_browser) {
        if (!PreferenceManager
                .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext())
                .getBoolean("browser", false)
                && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
            CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
            builder.setToolbarColor(ColorScheme.getInstance().navBarColor);
            builder.addDefaultShareMenuItem();
            builder.addMenuItem("Copy URL",
                    PendingIntent.getBroadcast(this, 0, new Intent(this, ChromeCopyLinkBroadcastReceiver.class),
                            PendingIntent.FLAG_UPDATE_CURRENT));

            CustomTabsIntent intent = builder.build();
            intent.intent.setData(Uri.parse(url.contains("?") ? url.substring(0, url.indexOf("?")) : url));
            if (Build.VERSION.SDK_INT >= 22)
                intent.intent.putExtra(Intent.EXTRA_REFERRER,
                        Uri.parse(Intent.URI_ANDROID_APP_SCHEME + "//" + getPackageName()));
            if (Build.VERSION.SDK_INT >= 16 && intent.startAnimationBundle != null) {
                startActivity(intent.intent, intent.startAnimationBundle);
            } else {
                startActivity(intent.intent);
            }
        } else {
            Intent intent = new Intent(Intent.ACTION_VIEW,
                    Uri.parse(url.contains("?") ? url.substring(0, url.indexOf("?")) : url));
            startActivity(intent);
        }
        finish();
        return true;
    } else if (item.getItemId() == R.id.action_copy) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                    CLIPBOARD_SERVICE);
            if (url.contains("?"))
                clipboard.setText(url.substring(0, url.indexOf("?")));
            else
                clipboard.setText(url);
        } else {
            @SuppressLint("ServiceCast")
            android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(
                    CLIPBOARD_SERVICE);
            android.content.ClipData clip;
            if (url.contains("?"))
                clip = android.content.ClipData.newRawUri("IRCCloud Snippet URL",
                        Uri.parse(url.substring(0, url.indexOf("?"))));
            else
                clip = android.content.ClipData.newRawUri("IRCCloud Snippet URL", Uri.parse(url));
            clipboard.setPrimaryClip(clip);
        }
        Toast.makeText(PastebinViewerActivity.this, "Link copied to clipboard", Toast.LENGTH_SHORT).show();
    } else if (item.getItemId() == R.id.action_share) {
        if (getIntent() != null && getIntent().getDataString() != null) {
            Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(url));
            intent.setType("text/plain");
            if (url.contains("?"))
                intent.putExtra(Intent.EXTRA_TEXT, url.substring(0, url.indexOf("?")));
            else
                intent.putExtra(Intent.EXTRA_TEXT, url);
            intent.putExtra(ShareCompat.EXTRA_CALLING_PACKAGE, getPackageName());
            intent.putExtra(ShareCompat.EXTRA_CALLING_ACTIVITY,
                    getPackageManager().getLaunchIntentForPackage(getPackageName()).getComponent());
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET | Intent.FLAG_ACTIVITY_NEW_TASK);

            startActivity(Intent.createChooser(intent, "Share Snippet"));
            Answers.getInstance().logShare(new ShareEvent().putContentType("Pastebin"));
        }
    } else if (item.getItemId() == R.id.action_edit) {
        mSpinner.setVisibility(View.VISIBLE);
        Intent i = new Intent(this, PastebinEditorActivity.class);
        i.putExtra("paste_id", Uri.parse(url).getQueryParameter("id"));
        startActivityForResult(i, 1);
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.parse.ParsePushBroadcastReceiver.java

/**
 * Creates a {@link Notification} with reasonable defaults. If "alert" and "title" are
 * both missing from data, then returns {@code null}. If the text in the notification is longer
 * than 38 characters long, the style of the notification will be set to
 * {@link android.app.Notification.BigTextStyle}.
 * <p/>/*from  www. j a  v a2  s . com*/
 * As a security precaution, developers overriding this method should be sure to set the package
 * on notification {@code Intent}s to avoid leaking information to other apps.
 *
 * @param context
 *      The {@code Context} in which the receiver is running.
 * @param intent
 *      An {@code Intent} containing the channel and data of the current push notification.
 * @return
 *      The notification to be displayed.
 *
 * @see ParsePushBroadcastReceiver#onPushReceive(Context, Intent)
 */
protected Notification getNotification(Context context, Intent intent) {
    JSONObject pushData = getPushData(intent);
    if (pushData == null || (!pushData.has("alert") && !pushData.has("title"))) {
        return null;
    }

    String title = pushData.optString("title", ManifestInfo.getDisplayName(context));
    String alert = pushData.optString("alert", "Notification received.");
    String tickerText = String.format(Locale.getDefault(), "%s: %s", title, alert);

    Bundle extras = intent.getExtras();

    Random random = new Random();
    int contentIntentRequestCode = random.nextInt();
    int deleteIntentRequestCode = random.nextInt();

    // Security consideration: To protect the app from tampering, we require that intent filters
    // not be exported. To protect the app from information leaks, we restrict the packages which
    // may intercept the push intents.
    String packageName = context.getPackageName();

    Intent contentIntent = new Intent(ParsePushBroadcastReceiver.ACTION_PUSH_OPEN);
    contentIntent.putExtras(extras);
    contentIntent.setPackage(packageName);

    Intent deleteIntent = new Intent(ParsePushBroadcastReceiver.ACTION_PUSH_DELETE);
    deleteIntent.putExtras(extras);
    deleteIntent.setPackage(packageName);

    PendingIntent pContentIntent = PendingIntent.getBroadcast(context, contentIntentRequestCode, contentIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    PendingIntent pDeleteIntent = PendingIntent.getBroadcast(context, deleteIntentRequestCode, deleteIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The purpose of setDefaults(Notification.DEFAULT_ALL) is to inherit notification properties
    // from system defaults
    NotificationCompat.Builder parseBuilder = new NotificationCompat.Builder(context);
    parseBuilder.setContentTitle(title).setContentText(alert).setTicker(tickerText)
            .setSmallIcon(this.getSmallIconId(context, intent)).setLargeIcon(this.getLargeIcon(context, intent))
            .setContentIntent(pContentIntent).setDeleteIntent(pDeleteIntent).setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL);
    if (alert != null && alert.length() > ParsePushBroadcastReceiver.SMALL_NOTIFICATION_MAX_CHARACTER_LIMIT) {
        parseBuilder.setStyle(new NotificationCompat.Builder.BigTextStyle().bigText(alert));
    }
    return parseBuilder.build();
}

From source file:edu.missouri.bas.service.SensorService.java

@SuppressWarnings("deprecation")
@Override//  ww  w  . j av a 2  s  . c  om
public void onCreate() {

    super.onCreate();
    Log.d(TAG, "Starting sensor service");
    mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundsMap = new HashMap<Integer, Integer>();
    soundsMap.put(SOUND1, mSoundPool.load(this, R.raw.bodysensor_alarm, 1));
    soundsMap.put(SOUND2, mSoundPool.load(this, R.raw.voice_notification, 1));

    serviceContext = this;

    mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    bluetoothMacAddress = mBluetoothAdapter.getAddress();
    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Get location manager
    mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    activityRecognition = new ActivityRecognitionScan(getApplicationContext());
    activityRecognition.startActivityRecognitionScan();

    mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    serviceWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "SensorServiceLock");
    serviceWakeLock.acquire();

    //Initialize start time
    stime = System.currentTimeMillis();

    //Setup calendar object
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(stime);

    /*
     * Setup notification manager
     */

    notification = new Notification(R.drawable.icon2, "Recorded", System.currentTimeMillis());
    notification.defaults = 0;
    notification.flags |= Notification.FLAG_ONGOING_EVENT;
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
    notifyIntent.setClass(this, MainActivity.class);

    /*
     * Display notification that service has started
     */
    notification.tickerText = "Sensor Service Running";
    PendingIntent contentIntent = PendingIntent.getActivity(SensorService.this, 0, notifyIntent,
            Notification.FLAG_ONGOING_EVENT);
    notification.setLatestEventInfo(SensorService.this, getString(R.string.app_name),
            "Recording service started at: " + cal.getTime().toString(), contentIntent);

    notificationManager.notify(SensorService.SERVICE_NOTIFICATION_ID, notification);

    // locationControl = new LocationControl(this, mLocationManager, 1000 * 60, 200, 5000);   

    IntentFilter activityResultFilter = new IntentFilter(XMLSurveyActivity.INTENT_ACTION_SURVEY_RESULTS);
    SensorService.this.registerReceiver(alarmReceiver, activityResultFilter);

    IntentFilter sensorDataFilter = new IntentFilter(SensorService.ACTION_SENSOR_DATA);
    SensorService.this.registerReceiver(alarmReceiver, sensorDataFilter);
    Log.d(TAG, "Sensor service created.");

    try {
        prepareIO();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    prepareAlarms();

    Intent startSensors = new Intent(SensorService.ACTION_START_SENSORS);
    this.sendBroadcast(startSensors);

    Intent scheduleCheckConnection = new Intent(SensorService.ACTION_SCHEDULE_CHECK);
    scheduleCheck = PendingIntent.getBroadcast(serviceContext, 0, scheduleCheckConnection, 0);
    mAlarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000 * 60 * 5, 1000 * 60 * 5, scheduleCheck);
    mLocationClient = new LocationClient(this, this, this);
}

From source file:com.mobiperf.MeasurementScheduler.java

private void handleMeasurement() {
    if (!userConsented()) {
        Logger.i("Skipping measurement - User has not consented");
        return;//  w w  w . j  a  v  a  2s.  co  m
    }

    try {
        MeasurementTask task = taskQueue.peek();
        // Process the head of the queue.
        if (task != null && task.timeFromExecution() <= 0) {
            taskQueue.poll();
            Future<MeasurementResult> future;
            Logger.i("Processing task " + task.toString());
            // Run the head task using the executor
            if (task.getDescription().priority == MeasurementTask.USER_PRIORITY) {
                sendStringMsg("Scheduling user task:\n" + task);
                // User task can override the power policy. So a different task wrapper is used.
                future = measurementExecutor.submit(new UserMeasurementTask(task));
            } else {
                sendStringMsg("Scheduling task:\n" + task);
                future = measurementExecutor.submit(new PowerAwareTask(task, resourceCapManager, this));
            }
            synchronized (pendingTasks) {
                pendingTasks.put(task, future);
            }

            MeasurementDesc desc = task.getDescription();

            long newStartTime = desc.startTime.getTime() + (long) desc.intervalSec * 1000;

            // Add a clone of the task if it's still valid.
            if (newStartTime < desc.endTime.getTime()
                    && (desc.count == MeasurementTask.INFINITE_COUNT || desc.count > 1)) {
                MeasurementTask newTask = task.clone();
                if (desc.count != MeasurementTask.INFINITE_COUNT) {
                    newTask.getDescription().count--;
                }
                newTask.getDescription().startTime.setTime(newStartTime);
                submitTask(newTask);
            }
        }
        // Schedule the next measurement in the taskQueue
        task = taskQueue.peek();
        if (task != null) {
            long timeFromExecution = Math.max(task.timeFromExecution(),
                    Config.MIN_TIME_BETWEEN_MEASUREMENT_ALARM_MSEC);
            measurementIntentSender = PendingIntent.getBroadcast(this, 0,
                    new UpdateIntent("", UpdateIntent.MEASUREMENT_ACTION), PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + timeFromExecution,
                    measurementIntentSender);
        }
    } catch (IllegalArgumentException e) {
        // Task creation in clone can create this exception
        Logger.e("Exception when cloning task");
        sendStringMsg("Exception when cloning task: " + e);
    } catch (Exception e) {
        // We don't want any unexpected exception to crash the process
        Logger.e("Exception when handling measurements", e);
        sendStringMsg("Exception running task: " + e);
    }
    persistState();
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

/**
 * Create the pending intent that is broadcast on the quarter hour.
 *
 * @param context The Context in which this PendingIntent should perform the broadcast.
 * @return a pending intent with an intent unique to DigitalAppWidgetProvider
 *//*  www . ja v a 2  s  .c  o  m*/
private PendingIntent getOnQuarterHourPendingIntent(Context context) {
    if (mPendingIntent == null) {
        mPendingIntent = PendingIntent.getBroadcast(context, 0, new Intent(ACTION_ON_QUARTER_HOUR),
                PendingIntent.FLAG_CANCEL_CURRENT);
    }
    return mPendingIntent;
}

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

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

    // Get preferences
    getSettings();//from  www.j  a v  a 2 s .  co  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<DrawerItem> serverItems = new ArrayList<DrawerItem>();
    ArrayList<DrawerItem> actionItems = new ArrayList<DrawerItem>();
    //        ArrayList<ObjectDrawerItem> labelItems = new ArrayList<ObjectDrawerItem>();
    ArrayList<DrawerItem> settingsItems = new ArrayList<DrawerItem>();

    // Add server category
    serverItems.add(new DrawerItem(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++) {
        serverItems.add(new DrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                DRAWER_ITEM_SERVERS, ((i + 1) == currentServerValue), "changeCurrentServer"));

    }

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

    // Add labels

    // Add settings actions
    settingsItems.add(new DrawerItem(R.drawable.ic_action_options, navigationDrawerItemTitles[7],
            DRAWER_ITEM_ACTIONS, false, "openOptions"));
    settingsItems.add(new DrawerItem(R.drawable.ic_drawer_settings, navigationDrawerItemTitles[8],
            DRAWER_ITEM_ACTIONS, false, "openSettings"));

    if (packageName.equals("com.lgallardo.qbittorrentclient")) {
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_pro, navigationDrawerItemTitles[9],
                DRAWER_ITEM_ACTIONS, false, "getPro"));
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[10],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    } else {
        settingsItems.add(new DrawerItem(R.drawable.ic_drawer_help, navigationDrawerItemTitles[9],
                DRAWER_ITEM_ACTIONS, false, "openHelp"));
    }

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

    //        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);

    // 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);

    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 was awoken from an intent-filter,
    // get intent from the intent filter and Add URL torrent
    addTorrentByIntent(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.qbittorrentclient.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.qbittorrentclient.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.qbittorrentclient.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();

}