Example usage for android.app PendingIntent getActivity

List of usage examples for android.app PendingIntent getActivity

Introduction

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

Prototype

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

Source Link

Document

Retrieve a PendingIntent that will start a new activity, like calling Context#startActivity(Intent) Context.startActivity(Intent) .

Usage

From source file:com.ubuntuone.android.files.service.UpDownService.java

public void onQuotaExceeded() {
    // Cancel all transfers.
    TransferUtils.setUploadsState(getContentResolver(), TransferState.FAILED);

    // Cancel retry alarm.
    Alarms.unregisterRetryFailedAlarm();

    String title = "Insufficient storage space";
    String text = "Select to buy more storage";

    // Notify the user, suggest storage upgrade.
    Notification notification = new NotificationCompat.Builder(this).setOngoing(false).setTicker(title)
            .setSmallIcon(R.drawable.stat_u1_logo).setOnlyAlertOnce(true).setAutoCancel(true).getNotification();

    final Intent intent = new Intent(UpDownService.this, PreferencesActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(PreferencesActivity.PURCHASE_STORAGE_SCREEN, 1);
    final PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), REQUEST_PURCHASE_SCREEN, intent,
            0);//from  ww  w  .  j  a  v a 2  s.  c  o  m
    notification.setLatestEventInfo(UpDownService.this, title, text, pi);

    notificationManager.notify(R.id.stat_quota_exceeded_id, notification);
    hasQuotaExceeded = true;
}

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

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);

    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));

    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
    Log.i(TAG, "vpn4=" + vpn4 + " vpn6=" + vpn6);
    builder.addAddress(vpn4, 32);/*from   w ww.  j a v  a 2  s .co  m*/
    builder.addAddress(vpn6, 128);

    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            Log.i(TAG, "dns=" + dns);
            builder.addDnsServer(dns);
        }

    if (tethering) {
        // USB Tethering 192.168.42.x
        // Wi-Fi Tethering 192.168.43.x
        // https://en.wikipedia.org/wiki/IPv4#Special-use_addresses
        builder.addRoute("0.0.0.0", 2); // 0-63
        builder.addRoute("64.0.0.0", 3); // 64-95
        builder.addRoute("96.0.0.0", 4); // 96-111
        builder.addRoute("112.0.0.0", 5); // 112-119
        builder.addRoute("120.0.0.0", 6); // 120-123
        builder.addRoute("124.0.0.0", 7); // 124-125
        builder.addRoute("126.0.0.0", 8); // 126
        // skip 127.0.0.0/8 - localhost
        builder.addRoute("128.0.0.0", 2); // 128-191
        builder.addRoute("192.0.0.0", 9); // 192.0-192.127
        builder.addRoute("192.128.0.0", 11); // 192.128-192.159
        builder.addRoute("192.160.0.0", 13); // 192.160-192.167
        builder.addRoute("192.168.0.0", 19); // 192.168.0-192.168.31
        builder.addRoute("192.168.32.0", 21); // 192.168.32-192.168.39
        builder.addRoute("192.168.40.0", 23); // 192.168.40-192.168.41
        // skip 192.168.42 - 192.168.43 - tethering
        builder.addRoute("192.168.44.0", 22); // 192.168.44-192.168.47
        builder.addRoute("192.168.48.0", 20); // 192.168.48-192.168.63
        builder.addRoute("192.168.64.0", 18); // 192.168.64-192.168.127
        builder.addRoute("192.168.128.0", 17); // 192.168.128-192.168.255
        builder.addRoute("192.169.0.0", 16); // 192.169
        builder.addRoute("192.170.0.0", 15); // 192.170-192.171
        builder.addRoute("192.172.0.0", 14); // 192.172-192.175
        builder.addRoute("192.176.0.0", 12); // 192.176-191.191
        builder.addRoute("192.192.0.0", 10); // 192.192-192.255
        builder.addRoute("193.0.0.0", 8); // 193
        builder.addRoute("194.0.0.0", 7); // 194-195
        builder.addRoute("196.0.0.0", 6); // 196-199
        builder.addRoute("200.0.0.0", 5); // 200-207
        builder.addRoute("208.0.0.0", 4); // 208-223

        try {
            builder.addRoute("224.0.0.0", 4); // 224-239
            builder.addRoute("240.0.0.0", 4); // 240-255
        } catch (Throwable ex) {
            // Some Android versions do not accept broadcast addresses
            Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);

    builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);

    // Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        else if (filter)
            for (Rule rule : listRule)
                if (!rule.apply || (!system && rule.system))
                    try {
                        Log.i(TAG, "Not routing " + rule.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}

From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java

public static void linkButtons(Context context, RemoteViews views, boolean playerActive) {

    Intent intent = new Intent(context, playerActive ? DownloadActivity.class : MainActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.appwidget_coverart, pendingIntent);
    views.setOnClickPendingIntent(R.id.appwidget_top, pendingIntent);

    // Emulate media button clicks.
    intent = new Intent("1");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_play, pendingIntent);

    intent = new Intent("2");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_next, pendingIntent);

    intent = new Intent("3");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT,
            new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_previous, pendingIntent);

    intent = new Intent("4");
    intent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    intent.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP));
    pendingIntent = PendingIntent.getService(context, 0, intent, 0);
    views.setOnClickPendingIntent(R.id.control_stop, pendingIntent);
}

From source file:com.ubuntuone.android.files.service.UpDownService.java

private synchronized void showFailedTransfersNotification(int failed) {
    String title = "Ubuntu One";
    Resources r = getResources();
    String text = r.getQuantityString(R.plurals.failed_to_upload_n_files, failed, failed);

    final Intent intent = new Intent(UpDownService.this, PreferencesActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(PreferencesActivity.SHOW_RETRY_FAILED, 1);
    final PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), REQUEST_RETRY_SCREEN, intent,
            0);//from  w  ww. j  ava2  s. co  m

    Notification notification = new NotificationCompat.Builder(this).setOngoing(false).setTicker(title)
            .setSmallIcon(R.drawable.stat_u1_logo).setOnlyAlertOnce(true).setAutoCancel(true).getNotification();
    notification.setLatestEventInfo(this, title, text, pi);

    notificationManager.notify(R.id.stat_failed_upload_id, notification);
}

From source file:com.irccloud.android.Notifications.java

public NotificationCompat.Builder alert(int bid, String title, String body) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext()).setContentTitle(title)
                    .setContentText(body).setTicker(body).setAutoCancel(true).setColor(IRCCloudApplication
                            .getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
                    .setSmallIcon(R.drawable.ic_stat_notify);

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    builder.setContentIntent(/*from w  w w  . jav  a2s  . com*/
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));

    NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(bid,
            builder.build());

    return builder;
}

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

public JSONObject stopThread(String threadId) {

    THREAD_ID thread = THREAD_ID.valueOf(threadId);
    Thread myThread = null;//from  www .  ja v a  2s.com

    switch (thread) {

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

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

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

    Runtime.getRuntime().exit(0);

    return getStatus();
}

From source file:com.zertinteractive.wallpaper.MainActivity.java

@SuppressLint("NewApi")
public void setNotification() {
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager notificationManager = (NotificationManager) getSystemService(ns);

    @SuppressWarnings("deprecation")
    Notification notification = new Notification(R.drawable.ic_launcher, "Ticker Text",
            System.currentTimeMillis());

    RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.romantic_wallpaper);

    //the intent that is started when the notification is clicked (works)
    Intent notificationIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    notification.contentView = notificationView;
    notification.contentIntent = pendingNotificationIntent;
    //        notification.flags |= Notification.FLAG_NO_CLEAR;
    notification.flags = Notification.FLAG_LOCAL_ONLY;

    //this is the intent that is supposed to be called when the button is clicked
    Intent switchIntent = new Intent(this, MainActivity.class);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
    ////from   w  w w . java2 s . c o m
    notificationView.setOnClickPendingIntent(R.id.download_notification, pendingSwitchIntent);
    notificationManager.notify(1, notification);
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Creates a system notification./*from w w  w .  j a  v  a 2 s . c om*/
 *    
 * @param context            Context.
 * @param notSound            Enable or disable the sound
 * @param notSoundRawId         Custom raw sound id. If enabled and not set 
 *                         default notification sound will be used. Set to -1 to 
 *                         default system notification.
 * @param multipleNot         Setting to True allows showing multiple notifications.
 * @param groupMultipleNotKey   If is set, multiple notifications can be grupped by this key.
 * @param notAction            Action for this notification
 * @param notTitle            Title
 * @param notMessage         Message
 * @param notClazz            Class to be executed
 * @param extras            Extra information
 * 
 */
public static void notification_generate(Context context, boolean notSound, int notSoundRawId,
        boolean multipleNot, String groupMultipleNotKey, String notAction, String notTitle, String notMessage,
        Class<?> notClazz, Bundle extras, boolean wakeUp) {

    try {
        int iconResId = notification_getApplicationIcon(context);
        long when = System.currentTimeMillis();

        Notification notification = new Notification(iconResId, notMessage, when);

        // Hide the notification after its selected
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        if (notSound) {
            if (notSoundRawId > 0) {
                try {
                    notification.sound = Uri.parse("android.resource://"
                            + context.getApplicationContext().getPackageName() + "/" + notSoundRawId);
                } catch (Exception e) {
                    if (LOG_ENABLE) {
                        Log.w(TAG, "Custom sound " + notSoundRawId + "could not be found. Using default.");
                    }
                    notification.defaults |= Notification.DEFAULT_SOUND;
                    notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                }
            } else {
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            }
        }

        Intent notificationIntent = new Intent(context, notClazz);
        notificationIntent.setAction(notClazz.getName() + "." + notAction);
        if (extras != null) {
            notificationIntent.putExtras(extras);
        }

        //Set intent so it does not start a new activity
        //
        //Notes:
        //   - The flag FLAG_ACTIVITY_SINGLE_TOP makes that only one instance of the activity exists(each time the
        //      activity is summoned no onCreate() method is called instead, onNewIntent() is called.
        //  - If we use FLAG_ACTIVITY_CLEAR_TOP it will make that the last "snapshot"/TOP of the activity it will 
        //     be this called this intent. We do not want this because the HOME button will call this "snapshot". 
        //     To avoid this behaviour we use FLAG_ACTIVITY_BROUGHT_TO_FRONT that simply takes to foreground the 
        //     activity.
        //
        //See http://developer.android.com/reference/android/content/Intent.html           
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        int REQUEST_UNIQUE_ID = 0;
        if (multipleNot) {
            if (groupMultipleNotKey != null && groupMultipleNotKey.length() > 0) {
                REQUEST_UNIQUE_ID = groupMultipleNotKey.hashCode();
            } else {
                if (random == null) {
                    random = new Random();
                }
                REQUEST_UNIQUE_ID = random.nextInt();
            }
            PendingIntent.getActivity(context, REQUEST_UNIQUE_ID, notificationIntent,
                    PendingIntent.FLAG_ONE_SHOT);
        }

        notification.setLatestEventInfo(context, notTitle, notMessage, intent);

        //This makes the device to wake-up is is idle with the screen off.
        if (wakeUp) {
            powersaving_wakeUp(context);
        }

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);

        //We check if the sound is disabled to enable just for a moment
        AudioManager amanager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        int previousAudioMode = amanager.getRingerMode();
        ;
        if (notSound && previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            amanager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }

        notificationManager.notify(REQUEST_UNIQUE_ID, notification);

        //We restore the sound setting
        if (previousAudioMode != AudioManager.RINGER_MODE_NORMAL) {
            //We wait a little so sound is played
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
            }
        }
        amanager.setRingerMode(previousAudioMode);

        Log.d(TAG, "Android Notification created.");

    } catch (Exception e) {
        if (LOG_ENABLE)
            Log.e(TAG, "The notification could not be created (" + e.getMessage() + ")", e);
    }
}

From source file:com.klinker.android.twitter.utils.NotificationUtils.java

public static void newInteractions(User interactor, Context context, SharedPreferences sharedPrefs,
        String type) {//from   www  .ja  v  a 2 s  .  com
    String title = "";
    String text = "";
    String smallText = "";
    Bitmap icon = null;

    AppSettings settings = AppSettings.getInstance(context);

    Intent resultIntent = new Intent(context, RedirectToDrawer.class);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 0);

    int newFollowers = sharedPrefs.getInt("new_followers", 0);
    int newRetweets = sharedPrefs.getInt("new_retweets", 0);
    int newFavorites = sharedPrefs.getInt("new_favorites", 0);
    int newQuotes = sharedPrefs.getInt("new_quotes", 0);

    // set title
    if (newFavorites + newRetweets + newFollowers > 1) {
        title = context.getResources().getString(R.string.new_interactions);
    } else {
        title = context.getResources().getString(R.string.new_interaction_upper);
    }

    // set text
    String currText = sharedPrefs.getString("old_interaction_text", "");
    if (!currText.equals("")) {
        currText += "<br>";
    }
    if (settings.displayScreenName) {
        text = currText + "<b>" + interactor.getScreenName() + "</b> " + type;
    } else {
        text = currText + "<b>" + interactor.getName() + "</b> " + type;
    }
    sharedPrefs.edit().putString("old_interaction_text", text).commit();

    // set icon
    int types = 0;
    if (newFavorites > 0) {
        types++;
    }
    if (newFollowers > 0) {
        types++;
    }
    if (newRetweets > 0) {
        types++;
    }
    if (newQuotes > 0) {
        types++;
    }

    if (types > 1) {
        icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_icon);
    } else {
        if (newFavorites > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_heart_dark);
        } else if (newRetweets > 0) {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_repeat_dark);
        } else {
            icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.drawer_user_dark);
        }
    }

    // set shorter text
    int total = newFavorites + newFollowers + newRetweets + newQuotes;
    if (total > 1) {
        smallText = total + " " + context.getResources().getString(R.string.new_interactions_lower);
    } else {
        smallText = text;
    }

    Intent markRead = new Intent(context, ReadInteractionsService.class);
    PendingIntent readPending = PendingIntent.getService(context, 0, markRead, 0);

    Intent deleteIntent = new Intent(context, NotificationDeleteReceiverOne.class);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(Html.fromHtml(
                    settings.addonTheme ? smallText.replaceAll("FF8800", settings.accentColor) : smallText))
            .setSmallIcon(R.drawable.ic_stat_icon).setLargeIcon(icon).setContentIntent(resultPendingIntent)
            .setTicker(title).setDeleteIntent(PendingIntent.getBroadcast(context, 0, deleteIntent, 0))
            .setPriority(NotificationCompat.PRIORITY_HIGH).setAutoCancel(true);

    if (context.getResources().getBoolean(R.bool.expNotifications)) {
        mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(
                Html.fromHtml(settings.addonTheme ? text.replaceAll("FF8800", settings.accentColor) : text)));
    }

    if (settings.vibrate) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    if (settings.sound) {
        try {
            mBuilder.setSound(Uri.parse(settings.ringtone));
        } catch (Exception e) {
            mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
        }
    }

    if (settings.led)
        mBuilder.setLights(0xFFFFFF, 1000, 1000);

    if (settings.notifications) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

        notificationManager.notify(4, mBuilder.build());

        // if we want to wake the screen on a new message
        if (settings.wakeScreen) {
            PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
            final PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
            wakeLock.acquire(5000);
        }

        // Pebble notification
        if (sharedPrefs.getBoolean("pebble_notification", false)) {
            sendAlertToPebble(context, title, text);
        }

        // Light Flow notification
        sendToLightFlow(context, title, text);
    }
}

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

private Builder getBuilder(List<Rule> listAllowed, List<Rule> listRule) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean subnet = prefs.getBoolean("subnet", false);
    boolean tethering = prefs.getBoolean("tethering", false);
    boolean lan = prefs.getBoolean("lan", false);
    boolean ip6 = prefs.getBoolean("ip6", true);
    boolean filter = prefs.getBoolean("filter", false);
    boolean system = prefs.getBoolean("manage_system", false);

    // Build VPN service
    Builder builder = new Builder();
    builder.setSession(getString(R.string.app_name));

    // VPN address
    String vpn4 = prefs.getString("vpn4", "10.1.10.1");
    Log.i(TAG, "vpn4=" + vpn4);
    builder.addAddress(vpn4, 32);/*  ww  w  .  j ava  2 s . c o  m*/
    if (ip6) {
        String vpn6 = prefs.getString("vpn6", "fd00:1:fd00:1:fd00:1:fd00:1");
        Log.i(TAG, "vpn6=" + vpn6);
        builder.addAddress(vpn6, 128);
    }

    // DNS address
    if (filter)
        for (InetAddress dns : getDns(ServiceSinkhole.this)) {
            if (ip6 || dns instanceof Inet4Address) {
                Log.i(TAG, "dns=" + dns);
                builder.addDnsServer(dns);
            }
        }

    // Subnet routing
    if (subnet) {
        // Exclude IP ranges
        List<IPUtil.CIDR> listExclude = new ArrayList<>();
        listExclude.add(new IPUtil.CIDR("127.0.0.0", 8)); // localhost

        if (tethering) {
            // USB Tethering 192.168.42.x
            // Wi-Fi Tethering 192.168.43.x
            listExclude.add(new IPUtil.CIDR("192.168.42.0", 23));
        }

        if (lan) {
            try {
                Enumeration<NetworkInterface> nis = NetworkInterface.getNetworkInterfaces();
                while (nis.hasMoreElements()) {
                    NetworkInterface ni = nis.nextElement();
                    if (ni != null && ni.isUp() && !ni.isLoopback() && ni.getName() != null
                            && !ni.getName().startsWith("tun"))
                        for (InterfaceAddress ia : ni.getInterfaceAddresses())
                            if (ia.getAddress() instanceof Inet4Address) {
                                IPUtil.CIDR local = new IPUtil.CIDR(ia.getAddress(),
                                        ia.getNetworkPrefixLength());
                                Log.i(TAG, "Excluding " + ni.getName() + " " + local);
                                listExclude.add(local);
                            }
                }
            } catch (SocketException ex) {
                Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
            }
        }

        Configuration config = getResources().getConfiguration();
        if (config.mcc == 310 && config.mnc == 260) {
            // T-Mobile Wi-Fi calling
            listExclude.add(new IPUtil.CIDR("66.94.2.0", 24));
            listExclude.add(new IPUtil.CIDR("66.94.6.0", 23));
            listExclude.add(new IPUtil.CIDR("66.94.8.0", 22));
            listExclude.add(new IPUtil.CIDR("208.54.0.0", 16));
        }
        listExclude.add(new IPUtil.CIDR("224.0.0.0", 3)); // broadcast

        Collections.sort(listExclude);

        try {
            InetAddress start = InetAddress.getByName("0.0.0.0");
            for (IPUtil.CIDR exclude : listExclude) {
                Log.i(TAG, "Exclude " + exclude.getStart().getHostAddress() + "..."
                        + exclude.getEnd().getHostAddress());
                for (IPUtil.CIDR include : IPUtil.toCIDR(start, IPUtil.minus1(exclude.getStart())))
                    try {
                        builder.addRoute(include.address, include.prefix);
                    } catch (Throwable ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }
                start = IPUtil.plus1(exclude.getEnd());
            }
            for (IPUtil.CIDR include : IPUtil.toCIDR("224.0.0.0", "255.255.255.255"))
                try {
                    builder.addRoute(include.address, include.prefix);
                } catch (Throwable ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        } catch (UnknownHostException ex) {
            Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        }
    } else
        builder.addRoute("0.0.0.0", 0);

    Log.i(TAG, "IPv6=" + ip6);
    if (ip6)
        builder.addRoute("0:0:0:0:0:0:0:0", 0);

    // MTU
    int mtu = jni_get_mtu();
    Log.i(TAG, "MTU=" + mtu);
    builder.setMtu(mtu);

    //         Add list of allowed applications
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
        if (last_connected && !filter)
            for (Rule rule : listAllowed)
                try {
                    builder.addDisallowedApplication(rule.info.packageName);
                } catch (PackageManager.NameNotFoundException ex) {
                    Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                }
        else if (filter)
            for (Rule rule : listRule)
                if (!rule.apply || (!system && rule.system))
                    try {
                        Log.i(TAG, "Not routing " + rule.info.packageName);
                        builder.addDisallowedApplication(rule.info.packageName);
                    } catch (PackageManager.NameNotFoundException ex) {
                        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                    }

    // Build configure intent
    Intent configure = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, configure, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setConfigureIntent(pi);

    return builder;
}