Example usage for android.content Intent EXTRA_TEXT

List of usage examples for android.content Intent EXTRA_TEXT

Introduction

In this page you can find the example usage for android.content Intent EXTRA_TEXT.

Prototype

String EXTRA_TEXT

To view the source code for android.content Intent EXTRA_TEXT.

Click Source Link

Document

A constant CharSequence that is associated with the Intent, used with #ACTION_SEND to supply the literal data to be sent.

Usage

From source file:com.kuacm.expo2013.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")");

    final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);

    if (receiver != null)
        receiver.send(STATUS_RUNNING, Bundle.EMPTY);

    final Context context = this;
    final SharedPreferences prefs = getSharedPreferences(Prefs.IOSCHED_SYNC, Context.MODE_PRIVATE);
    final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE);

    try {/* www. j a  va2 s  . c o  m*/
        // Bulk of sync work, performed by executing several fetches from
        // local and online sources.

        final long startLocal = System.currentTimeMillis();
        final boolean localParse = localVersion < VERSION_CURRENT;
        Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
        if (localParse) {
            // Load static local data
            mLocalExecutor.execute(R.xml.blocks, new LocalBlocksHandler());
            mLocalExecutor.execute(R.xml.rooms, new LocalRoomsHandler());
            mLocalExecutor.execute(R.xml.tracks, new LocalTracksHandler());
            mLocalExecutor.execute(R.xml.search_suggest, new LocalSearchSuggestHandler());
            mLocalExecutor.execute(R.xml.sessions, new LocalSessionsHandler());

            // Parse values from local cache first, since spreadsheet copy
            // or network might be down.
            mLocalExecutor.execute(context, "cache-sessions.xml", new RemoteSessionsHandler());
            mLocalExecutor.execute(context, "cache-speakers.xml", new RemoteSpeakersHandler());
            mLocalExecutor.execute(context, "cache-vendors.xml", new RemoteVendorsHandler());

            // Save local parsed version
            prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
        }
        Log.d(TAG, "local sync took " + (System.currentTimeMillis() - startLocal) + "ms");

        // Always hit remote spreadsheet for any updates
        final long startRemote = System.currentTimeMillis();

        mRemoteExecutor.executeGet(WORKSHEETS_URL, new RemoteWorksheetsHandler(mRemoteExecutor));

        Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");

    } catch (Exception e) {
        Log.e(TAG, "Problem while syncing", e);

        if (receiver != null) {
            // Pass back error to surface listener
            final Bundle bundle = new Bundle();
            bundle.putString(Intent.EXTRA_TEXT, e.toString());
            receiver.send(STATUS_ERROR, bundle);
        }
    }

    // Announce success to any surface listener
    Log.d(TAG, "sync finished");
    if (receiver != null)
        receiver.send(STATUS_FINISHED, Bundle.EMPTY);
}

From source file:com.acl.sunshine.app.ForecastFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    // The SimpleCursorAdapter will take data from the database through the
    // Loader and use it to populate the ListView it's attached to.
    mForecastAdapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item_forecast, null,
            // the column names to use to fill the textviews
            new String[] { WeatherEntry.COLUMN_DATETEXT, WeatherEntry.COLUMN_SHORT_DESC,
                    WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP },
            // the textviews to fill with the data pulled from the columns above
            new int[] { R.id.list_item_date_textview, R.id.list_item_forecast_textview,
                    R.id.list_item_high_textview, R.id.list_item_low_textview },
            0);/*w ww  .  j  ava 2 s  . co  m*/

    mForecastAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            boolean isMetric = Utility.isMetric(getActivity());
            switch (columnIndex) {
            case COL_WEATHER_MAX_TEMP:
            case COL_WEATHER_MIN_TEMP: {
                // we have to do some formatting and possibly a conversion
                ((TextView) view).setText(Utility.formatTemperature(cursor.getDouble(columnIndex), isMetric));
                return true;
            }
            case COL_WEATHER_DATE: {
                String dateString = cursor.getString(columnIndex);
                TextView dateView = (TextView) view;
                dateView.setText(Utility.formatDate(dateString));
                return true;
            }
            }
            return false;
        }
    });

    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    // Get a reference to the ListView, and attach this adapter to it.
    ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
    listView.setAdapter(mForecastAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Cursor cursor = mForecastAdapter.getCursor();
            if (cursor != null && cursor.moveToPosition(position)) {
                String dateString = Utility.formatDate(cursor.getString(COL_WEATHER_DATE));
                String weatherDescription = cursor.getString(COL_WEATHER_DESC);

                boolean isMetric = Utility.isMetric(getActivity());
                String high = Utility.formatTemperature(cursor.getDouble(COL_WEATHER_MAX_TEMP), isMetric);
                String low = Utility.formatTemperature(cursor.getDouble(COL_WEATHER_MIN_TEMP), isMetric);

                String detailString = String.format("%s - %s - %s/%s", dateString, weatherDescription, high,
                        low);

                Intent intent = new Intent(getActivity(), DetailActivity.class).putExtra(Intent.EXTRA_TEXT,
                        detailString);
                startActivity(intent);
            }
        }
    });

    return rootView;
}

From source file:edu.stanford.mobisocial.dungbeetle.ui.fragments.FeedActionsFragment.java

private void sendToExternalFriend() {
    Intent share = new Intent(Intent.ACTION_SEND);
    share.putExtra(Intent.EXTRA_TEXT,
            "Join me in a Musubi thread: " + ThreadRequest.getInvitationUri(getActivity(), mExternalFeedUri));
    share.putExtra(Intent.EXTRA_SUBJECT, "Join me on Musubi!");
    share.setType("text/plain");
    startActivity(share);/* w  w  w .  j  ava2 s .  com*/
}

From source file:foam.jellyfish.StarwispBuilder.java

public static void email(Context context, String emailTo, String emailCC, String subject, String emailText,
        List<String> filePaths) {
    //need to "send multiple" to get more than one attachment
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);
    emailIntent.setType("text/plain");
    emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { emailTo });
    emailIntent.putExtra(android.content.Intent.EXTRA_CC, new String[] { emailCC });
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);

    ArrayList<String> extra_text = new ArrayList<String>();
    extra_text.add(emailText);/*  w ww  .java2s . c om*/
    emailIntent.putStringArrayListExtra(Intent.EXTRA_TEXT, extra_text);
    //emailIntent.putExtra(Intent.EXTRA_TEXT, emailText);

    //has to be an ArrayList
    ArrayList<Uri> uris = new ArrayList<Uri>();
    //convert from paths to Android friendly Parcelable Uri's
    for (String file : filePaths) {
        File fileIn = new File(file);
        Uri u = Uri.fromFile(fileIn);
        uris.add(u);
    }
    emailIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
    context.startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}

From source file:com.gmail.altakey.lucene.AsyncImageLoader.java

private InputStream read(ProgressReportingInputStream.ProgressListener listener) throws FileNotFoundException {
    final Context context = this.view.getContext();

    if (Intent.ACTION_SEND.equals(this.intent.getAction())) {
        final Bundle extras = this.intent.getExtras();
        if (extras.containsKey(Intent.EXTRA_STREAM))
            return new ProgressReportingInputStream(context.getContentResolver()
                    .openInputStream((Uri) extras.getParcelable(Intent.EXTRA_STREAM)), listener);
        if (extras.containsKey(Intent.EXTRA_TEXT)) {
            try {
                final HttpGet req = new HttpGet(extras.getCharSequence(Intent.EXTRA_TEXT).toString());
                return new ProgressReportingInputStream(this.httpClient.execute(req).getEntity().getContent(),
                        listener);/*from   ww w.  ja  v  a2  s . co  m*/
            } catch (IllegalArgumentException e) {
                return null;
            } catch (IOException e) {
                return null;
            }
        }
    }

    if (Intent.ACTION_VIEW.equals(this.intent.getAction()))
        return new ProgressReportingInputStream(
                context.getContentResolver().openInputStream(this.intent.getData()), listener);

    return null;
}

From source file:im.delight.android.baselib.Social.java

/**
 * Constructs an SMS Intent for the given message details and opens the application chooser for this Intent
 *
 * @param recipient the recipient's phone number or `null`
 * @param body the body of the message//  w  ww .  ja v a  2 s. c o m
 * @param captionRes the string resource ID for the application chooser's window title
 * @param context the Context instance to start the Intent from
 * @throws Exception if there was an error trying to launch the SMS Intent
 */
public static void sendSMS(final String recipient, final String body, final int captionRes,
        final Context context) throws Exception {
    final Intent intent = new Intent(Intent.ACTION_SENDTO);
    intent.setType(HTTP.PLAIN_TEXT_TYPE);
    if (recipient != null && recipient.length() > 0) {
        intent.setData(Uri.parse("smsto:" + recipient));
    } else {
        intent.setData(Uri.parse("sms:"));
    }
    intent.putExtra("sms_body", body);
    intent.putExtra(Intent.EXTRA_TEXT, body);
    if (context != null) {
        // offer a selection of all applications that can handle the SMS Intent
        context.startActivity(Intent.createChooser(intent, context.getString(captionRes)));
    }
}

From source file:com.willhauck.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override//from   ww  w. j a va2s  . c  o  m
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    prefDonateBitcoin.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            try {
                // Open installed Bitcoin wallet if possible
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(
                        "bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
                startActivity(intent);
            } catch (Exception e) {
                // Otherwise, show dialog with Bitcoin address
                EditText input = new EditText(SettingsActivity.this);
                input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                input.setEnabled(false);

                new AlertDialog.Builder(SettingsActivity.this).setTitle("Bitcoin Address")
                        .setMessage(
                                "Please donate to the following Bitcoin address. Thank you for the support.")
                        .setView(input)
                        .setPositiveButton("Copy Address", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(
                                        Context.CLIPBOARD_SERVICE);
                                clipboard.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
                            }
                        }).setNegativeButton("Okay", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                            }
                        }).show();
            }
            return true;
        }
    });

    Preference prefGooglePlus = findPreference("pref_google_plus");
    prefGooglePlus.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Google Plus page
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("https://plus.google.com/114633032648182423928/posts"));
            startActivity(intent);
            return true;
        }
    });

    Preference prefDonatePlay = findPreference("pref_donate_play");
    prefDonatePlay.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open Donation Key app on Play Store
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setData(Uri.parse("market://details?id=com.willhauck.donation"));
            startActivity(intent);
            return true;
        }
    });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}

From source file:org.ietf.ietfsched.service.SyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER);
    if (debbug)/*from w  w w .j  av  a 2 s .  c  o m*/
        Log.d(TAG, "Receiver is = " + receiver);
    if (receiver != null)
        receiver.send(STATUS_RUNNING, Bundle.EMPTY);
    final Context context = this;
    final SharedPreferences prefs = getSharedPreferences(Prefs.IETFSCHED_SYNC, Context.MODE_PRIVATE);
    final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE);
    //      final int lastLength = prefs.getInt(Prefs.LAST_LENGTH, VERSION_NONE);
    final String lastEtag = prefs.getString(Prefs.LAST_ETAG, "");
    //      final long startLocal = System.currentTimeMillis();

    //boolean localParse = localVersion < VERSION_CURRENT;
    boolean localParse = false;
    Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT);
    boolean remoteParse = true;
    //      int remoteLength = -1;
    String remoteEtag = "";

    try {
        String htmlURL = BASE_URL + "agenda.csv";
        if (debbug)
            Log.d(TAG, "HEAD " + htmlURL);
        remoteEtag = mRemoteExecutor.executeHead(htmlURL);
        if (debbug)
            Log.d(TAG, "HEAD " + htmlURL + " " + remoteEtag);
        if (remoteEtag == null) {
            Log.d(TAG, "Error connection, cannot retrieve any information from" + htmlURL);
            remoteParse = false;
        } else {
            remoteParse = !remoteEtag.equals(lastEtag);
        }
    } catch (Exception e) {
        remoteParse = false;
        e.printStackTrace();
    }

    // HACK FOR TESTS PURPOSES. TO REMOVE 
    //      Log.w(TAG, "For tests purposes, only the local parsing is activated");
    //      remoteParse = false;
    //      localParse = true;
    // HACK FIN.   

    if (!remoteParse && !localParse) {
        Log.d(TAG, "Already synchronized");
        if (receiver != null)
            receiver.send(STATUS_FINISHED, Bundle.EMPTY);
        return;
    }

    if (remoteParse) {
        String csvURL = BASE_URL + "agenda.csv";
        try {
            if (debbug)
                Log.d(TAG, csvURL);
            InputStream agenda = mRemoteExecutor.executeGet(csvURL);
            mLocalExecutor.execute(agenda);
            prefs.edit().putString(Prefs.LAST_ETAG, remoteEtag).commit();
            prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
            localParse = false;
            Log.d(TAG, "remote sync finished");
            if (receiver != null)
                receiver.send(STATUS_FINISHED, Bundle.EMPTY);
        } catch (Exception e) {
            Log.e(TAG, "Error HTTP request " + csvURL, e);
            if (!localParse) {
                final Bundle bundle = new Bundle();
                bundle.putString(Intent.EXTRA_TEXT, "Connection error. No updates.");
                if (receiver != null) {
                    receiver.send(STATUS_ERROR, bundle);
                }
            }
        }
    }

    if (localParse) {
        try {
            mLocalExecutor.execute(context, "agenda-83.csv");
            Log.d(TAG, "local sync finished");
            prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit();
            if (receiver != null)
                receiver.send(STATUS_FINISHED, Bundle.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            final Bundle bundle = new Bundle();
            bundle.putString(Intent.EXTRA_TEXT, e.toString());
            if (receiver != null) {
                receiver.send(STATUS_ERROR, bundle);
            }
        }
    }
}

From source file:com.harshad.linconnectclient.SettingsActivity.java

@SuppressLint("SimpleDateFormat")
private void setupSimplePreferencesScreen() {
    // Load preferences
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(SettingsActivity.this);

    // Add preferences from XML
    addPreferencesFromResource(R.xml.pref_general);
    bindPreferenceSummaryToValue(findPreference("pref_ip"));

    // Preference Categories
    serverCategory = ((PreferenceCategory) findPreference("cat_servers"));

    // Preferences
    refreshPreference = ((Preference) findPreference("pref_refresh"));
    serverCategory.removePreference(refreshPreference);

    loadingPreference = ((Preference) findPreference("pref_loading"));
    serverCategory.removePreference(loadingPreference);

    Preference prefEnable = findPreference("pref_enable");
    prefEnable.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override//w w  w .j a  v a  2  s.c  om
        public boolean onPreferenceClick(Preference arg0) {
            // If Android 4.3+, open Notification Listener settings,
            // otherwise open accessibility settings
            if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                startActivityForResult(new Intent(android.provider.Settings.ACTION_ACCESSIBILITY_SETTINGS), 0);
            } else {
                Intent intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                startActivity(intent);
            }
            return true;
        }
    });

    ((Preference) findPreference("pref_ip")).setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference arg0, Object arg1) {
            // Update Custom IP address summary
            arg0.setSummary((String) arg1);

            refreshServerList();

            // Create and send test notification
            SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");
            Object[] notif = new Object[3];
            notif[0] = "Hello from Android!";
            notif[1] = "Test succesful @ " + sf.format(new Date());
            notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);
            new TestTask().execute(notif);

            return true;
        }
    });

    Preference prefDownload = findPreference("pref_download");
    prefDownload.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Create share dialog with server download URL
            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT,
                    "Download LinConnect server @ https://github.com/hauckwill/linconnect-server");
            sendIntent.setType("text/plain");
            startActivity(sendIntent);
            return true;
        }
    });

    Preference prefApplication = findPreference("pref_application");
    prefApplication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference arg0) {
            // Open application settings screen
            Intent intent = new Intent(getApplicationContext(), ApplicationSettingsActivity.class);

            startActivity(intent);
            return true;
        }
    });

    //   Preference prefDonateBitcoin = findPreference("pref_donate_btc");
    //   prefDonateBitcoin
    //         .setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //            @Override
    //            public boolean onPreferenceClick(Preference arg0) {
    //               try {
    // Open installed Bitcoin wallet if possible
    //                  Intent intent = new Intent(Intent.ACTION_VIEW);
    //                  intent.setData(Uri
    //                        .parse("bitcoin:1125MguyS1feaop99bCDPQG6ukUcMuvVBo?label=Will%20Hauck&message=Donation%20for%20LinConnect"));
    //                  startActivity(intent);
    //               } catch (Exception e) {
    // Otherwise, show dialog with Bitcoin address
    //                  EditText input = new EditText(SettingsActivity.this);
    //                  input.setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
    //                  input.setEnabled(false);

    //                  new AlertDialog.Builder(SettingsActivity.this)
    //                        .setTitle("Bitcoin Address")
    //                        .setMessage(
    //                              "Please donate to the following Bitcoin address. Thank you for the support.")
    //                        .setView(input)
    //                        .setPositiveButton(
    //                              "Copy Address",
    //                              new DialogInterface.OnClickListener() {
    //                                 public void onClick(
    //                                       DialogInterface dialog,
    //                                       int whichButton) {
    //                                    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    //                                    clipboard
    //                                          .setText("1125MguyS1feaop99bCDPQG6ukUcMuvVBo");
    //                                 }
    //                              })
    //                        .setNegativeButton(
    //                              "Okay",
    //                              new DialogInterface.OnClickListener() {
    //                                 public void onClick(
    //                                       DialogInterface dialog,
    //                                       int whichButton) {
    //                                 }
    //                              }).show();
    //               }
    //               return true;
    //            }
    //         });

    //   Preference prefGooglePlus = findPreference("pref_google_plus");
    //   prefGooglePlus
    //         .setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //            @Override
    //            public boolean onPreferenceClick(Preference arg0) {
    //               // Open Google Plus page
    //               Intent intent = new Intent(Intent.ACTION_VIEW);
    //               intent.setData(Uri
    //                     .parse("https://plus.google.com/114633032648182423928/posts"));
    //               startActivity(intent);
    //               return true;
    //            }
    //         });

    //   Preference prefDonatePlay = findPreference("pref_donate_play");
    //   prefDonatePlay
    //         .setOnPreferenceClickListener(new OnPreferenceClickListener() {
    //            @Override
    //            public boolean onPreferenceClick(Preference arg0) {
    // Open Donation Key app on Play Store
    //               Intent intent = new Intent(Intent.ACTION_VIEW);
    //               intent.setData(Uri
    //                     .parse("market://details?id=com.willhauck.donation"));
    //               startActivity(intent);
    //               return true;
    //            }
    //         });

    // Create handler to process a detected server
    serverFoundHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.obj != null) {

                javax.jmdns.ServiceInfo serviceInfo = mJmDNS.getServiceInfo(jmDnsServiceType, (String) msg.obj);

                // Get info about server
                String name = serviceInfo.getName();
                String port = String.valueOf(serviceInfo.getPort());
                String ip = serviceInfo.getHostAddresses()[0];

                // Create a preference representing the server
                Preference p = new Preference(SettingsActivity.this);
                p.setTitle(name);
                p.setSummary(ip + ":" + port);

                p.setOnPreferenceClickListener(new OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference arg0) {
                        refreshServerList();

                        // Save IP address in preferences
                        Editor e = sharedPreferences.edit();
                        e.putString("pref_ip", arg0.getSummary().toString());
                        e.apply();

                        // Create and send test notification
                        SimpleDateFormat sf = new SimpleDateFormat("HH:mm:ss");

                        Object[] notif = new Object[3];
                        notif[0] = "Hello from Android!";
                        notif[1] = "Test succesful @ " + sf.format(new Date());
                        notif[2] = SettingsActivity.this.getResources().getDrawable(R.drawable.ic_launcher);

                        new TestTask().execute(notif);

                        return true;
                    }

                });

                // Add preference to server list if it doesn't already exist
                boolean found = false;
                for (int i = 0; i < serverCategory.getPreferenceCount(); i++) {
                    if (serverCategory.getPreference(i) != null
                            && serverCategory.getPreference(i).getTitle() != null
                            && serverCategory.getPreference(i).getTitle().equals(p.getTitle())) {
                        found = true;
                    }
                }
                if (!found) {
                    serverCategory.addPreference(p);
                }

                refreshServerList();

                // Remove loading indicator, add refresh indicator if it
                // isn't already there
                if (findPreference("pref_loading") != null)
                    serverCategory.removePreference(findPreference("pref_loading"));
                if (findPreference("pref_refresh") == null)
                    serverCategory.addPreference(refreshPreference);

            }
            return true;
        }
    });

    // Create task to scan for servers
    class ServerScanTask extends AsyncTask<String, ServiceEvent, Boolean> {

        @Override
        protected void onPreExecute() {
            // Remove refresh preference, add loading preference
            if (findPreference("pref_refresh") != null)
                serverCategory.removePreference(refreshPreference);
            serverCategory.addPreference(loadingPreference);

            try {
                mJmDNS.removeServiceListener(jmDnsServiceType, ServerListener);
            } catch (Exception e) {
            }

            refreshServerList();

        }

        @Override
        protected Boolean doInBackground(String... notif) {
            WifiInfo wifiinfo = mWifiManager.getConnectionInfo();
            int intaddr = wifiinfo.getIpAddress();

            // Ensure there is an active Wifi connection
            if (intaddr != 0) {
                byte[] byteaddr = new byte[] { (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff),
                        (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) };
                InetAddress addr = null;
                try {
                    addr = InetAddress.getByAddress(byteaddr);
                } catch (UnknownHostException e1) {
                }

                // Create Multicast lock (required for JmDNS)
                mMulticastLock = mWifiManager.createMulticastLock("LinConnect");
                mMulticastLock.setReferenceCounted(true);
                mMulticastLock.acquire();

                try {
                    mJmDNS = JmDNS.create(addr, "LinConnect");
                } catch (IOException e) {
                }

                // Create listener for detected servers
                ServerListener = new ServiceListener() {

                    @Override
                    public void serviceAdded(ServiceEvent arg0) {
                        final String name = arg0.getName();
                        // Send the server data to the handler, delayed by
                        // 500ms to ensure all information is read
                        serverFoundHandler.sendMessageDelayed(Message.obtain(serverFoundHandler, -1, name),
                                500);
                    }

                    @Override
                    public void serviceRemoved(ServiceEvent arg0) {
                    }

                    @Override
                    public void serviceResolved(ServiceEvent arg0) {
                        mJmDNS.requestServiceInfo(arg0.getType(), arg0.getName(), 1);
                    }
                };
                mJmDNS.addServiceListener(jmDnsServiceType, ServerListener);

                return true;
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (!result) {
                // Notify user if there is no connection
                if (findPreference("pref_loading") != null) {
                    serverCategory.removePreference(findPreference("pref_loading"));
                    serverCategory.addPreference(refreshPreference);

                }
                Toast.makeText(getApplicationContext(), "Error: no connection.", Toast.LENGTH_LONG).show();
            }
        }
    }

    refreshPreference.setOnPreferenceClickListener(new OnPreferenceClickListener() {

        @Override
        public boolean onPreferenceClick(Preference arg0) {
            new ServerScanTask().execute();
            return true;
        }

    });

    // Start scanning for servers
    new ServerScanTask().execute();
}