Example usage for android.os AsyncTask THREAD_POOL_EXECUTOR

List of usage examples for android.os AsyncTask THREAD_POOL_EXECUTOR

Introduction

In this page you can find the example usage for android.os AsyncTask THREAD_POOL_EXECUTOR.

Prototype

Executor THREAD_POOL_EXECUTOR

To view the source code for android.os AsyncTask THREAD_POOL_EXECUTOR.

Click Source Link

Document

An Executor that can be used to execute tasks in parallel.

Usage

From source file:org.thoughtcrime.securesms.conversation.ConversationFragment.java

private void handleDeleteMessages(final Set<MessageRecord> messageRecords) {
    int messagesCount = messageRecords.size();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setIconAttribute(R.attr.dialog_alert_icon);
    builder.setTitle(getActivity().getResources().getQuantityString(
            R.plurals.ConversationFragment_delete_selected_messages, messagesCount, messagesCount));
    builder.setMessage(getActivity().getResources().getQuantityString(
            R.plurals.ConversationFragment_this_will_permanently_delete_all_n_selected_messages, messagesCount,
            messagesCount));//from   w  ww  .  j a  v a2 s  .  co  m
    builder.setCancelable(true);

    builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            new ProgressDialogAsyncTask<MessageRecord, Void, Void>(getActivity(),
                    R.string.ConversationFragment_deleting, R.string.ConversationFragment_deleting_messages) {
                @Override
                protected Void doInBackground(MessageRecord... messageRecords) {
                    for (MessageRecord messageRecord : messageRecords) {
                        boolean threadDeleted;

                        if (messageRecord.isMms()) {
                            threadDeleted = DatabaseFactory.getMmsDatabase(getActivity())
                                    .delete(messageRecord.getId());
                        } else {
                            threadDeleted = DatabaseFactory.getSmsDatabase(getActivity())
                                    .deleteMessage(messageRecord.getId());
                        }

                        if (threadDeleted) {
                            threadId = -1;
                            listener.setThreadId(threadId);
                        }
                    }

                    return null;
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                    messageRecords.toArray(new MessageRecord[messageRecords.size()]));
        }
    });

    builder.setNegativeButton(android.R.string.cancel, null);
    builder.show();
}

From source file:com.secupwn.aimsicd.ui.activities.MapViewerOsmDroid.java

/**
 * Description:    Loads Signal Strength Database details to plot on the map,
 * only entries which have a location (lon, lat) are used.
 *//*w w  w .  j  a  va2 s .  c o  m*/
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            //int signal;

            mCellTowerGridMarkerClusterer.getItems().clear();

            loadOcidMarkersByNetwork();

            List<CellTowerMarker> items = new LinkedList<>();

            @Cleanup
            Realm realm = Realm.getDefaultInstance();

            RealmResults<BaseTransceiverStation> baseStations = realm.allObjects(BaseTransceiverStation.class);
            if (baseStations.size() > 0) {
                for (BaseTransceiverStation baseStation : baseStations) {
                    if (isCancelled()) {
                        return null;
                    }
                    // The indexing here is that of DB table
                    final int cellID = baseStation.getCellId();
                    final int lac = baseStation.getLocationAreaCode();
                    final int mcc = baseStation.getMobileCountryCode();
                    final int mnc = baseStation.getMobileNetworkCode();
                    final int psc = baseStation.getPrimaryScramblingCode();

                    final double dLat = baseStation.getGpsLocation().getLatitude();
                    final double dLng = baseStation.getGpsLocation().getLongitude();

                    if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) {
                        continue;
                    }
                    // TODO this (signal) is not in DBi_bts
                    // signal = 1;
                    //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL));  // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    //if (signal <= 0) {
                    //    signal = 20;
                    //}

                    if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) {
                        loc = new GeoPoint(dLat, dLng);

                        CellTowerMarker ovm = new CellTowerMarker(MapViewerOsmDroid.this, mMap,
                                "Cell ID: " + cellID, "", loc,
                                new MarkerData(getApplicationContext(), String.valueOf(cellID),
                                        String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                        String.valueOf(lac), String.valueOf(mcc), String.valueOf(mnc),
                                        String.valueOf(psc), null, "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));

                        items.add(ovm);
                    }

                }
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(MapViewerOsmDroid.this, getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMobileCountryCode();
                    GpsLocation d = mDbHelper.getDefaultLocation(realm, mcc);
                    ret = new GeoPoint(d.getLatitude(), d.getLongitude());
                } catch (Exception e) {
                    log.error("Error getting default location!", e);
                }
            }
            // plot neighboring cells
            while (mAimsicdService == null) {
                try {
                    if (isCancelled()) {
                        return null;
                    }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.warn("thread interrupted", e);
                }
            }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighboringCells();
            for (Cell cell : nc) {
                if (isCancelled()) {
                    return null;
                }
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(MapViewerOsmDroid.this, mMap,
                            getString(R.string.cell_id_label) + cell.getCellId(), "", loc,
                            new MarkerData(getApplicationContext(), String.valueOf(cell.getCellId()),
                                    String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                    String.valueOf(cell.getLocationAreaCode()),
                                    String.valueOf(cell.getMobileCountryCode()),
                                    String.valueOf(cell.getMobileNetworkCode()),
                                    String.valueOf(cell.getPrimaryScramblingCode()),
                                    String.valueOf(cell.getRat()), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    log.error("Error plotting neighboring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc Default location to open map on
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
                    && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
            if (mCellTowerGridMarkerClusterer != null) {
                if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) {
                    log.verbose("CellTowerMarkers.invalidate() markers.size():"
                            + mCellTowerGridMarkerClusterer.getItems().size());
                }
                //Drawing markers of cell tower immediately as possible
                mCellTowerGridMarkerClusterer.invalidate();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:eu.focusnet.app.ui.activity.ProjectsListingActivity.java

/**
 * When clicking the action bar buttons:
 * - display an alert dialog that allows to trigger data synchronization or displays the current
 * status of the synchronization.//  ww w  .  j av  a  2 s.co  m
 *
 * @param item Inherited.
 * @return Inherited.
 */
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_sync:

        if (!this.cronBound) {
            return false;
        }

        LayoutInflater inflater = getLayoutInflater();
        // FIXME pass a better Context than null.
        final LinearLayout dialogContent = (LinearLayout) inflater
                .inflate(R.layout.dialog_content_synchronization, null);

        final Context context = this;
        final FocusDialogBuilder builder = new FocusDialogBuilder(context).removeNeutralButton()
                .setNegativeButtonText(getString(R.string.cancel))
                .setPositiveButtonText(getString(R.string.start)).setCancelable(false)
                .insertContent(dialogContent).setTitle(getString(R.string.data_sync_title));
        final AlertDialog dialog = builder.create();
        dialog.show();

        // Cancelation listener
        builder.getNegativeButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                builder.setNegativeButtonText(getString(R.string.sync_continue_background));
                dialog.dismiss();
            }
        });

        final View instructions = dialogContent.findViewById(R.id.dialog_sync_instructions);
        final View progress = dialogContent.findViewById(R.id.dialog_sync_progress);
        final View status = dialogContent.findViewById(R.id.dialog_sync_status);
        final TextView instructionsField = (TextView) instructions
                .findViewById(R.id.dialog_sync_instructions_msg);
        final TextView statusField = (TextView) status.findViewById(R.id.dialog_sync_status_field);

        // update dynamic content (last sync and last data volume)
        String lastSync;
        if (this.cronService.getLastSync() == 0) {
            lastSync = getString(R.string.n_a);
        } else {
            DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance();
            lastSync = dateFormat.format(new Date(this.cronService.getLastSync()));
        }
        TextView lastSyncField = (TextView) instructions.findViewById(R.id.dialog_sync_last_sync_field);
        lastSyncField.setText(getString(R.string.last_sync_label) + lastSync);
        TextView lastDataVolumeField = (TextView) instructions.findViewById(R.id.dialog_sync_data_volume_field);

        long rawDbSize = FocusAppLogic.getDataManager().getDatabaseSize();
        lastDataVolumeField.setText(getString(R.string.last_sync_data_volume_label)
                + (rawDbSize == 0 ? "N/A" : UiHelper.getFileSize(rawDbSize)));

        // too early since last sync
        // display instructions with custom message, disable START
        if (cronService.getLastSync() >= System.currentTimeMillis()
                - Constant.AppConfig.CRON_SERVICE_MINIMUM_DURATION_BETWEEN_SYNC_DATA_IN_MILLISECONDS) {
            instructionsField.setText(R.string.sync_too_recent);
            builder.removePositiveButton();
            builder.setNegativeButtonText(getString(R.string.close));
        }
        // ongoing sync
        // display status and remove START
        else if (this.cronService.getSyncInProgress()) {
            builder.removePositiveButton();
            builder.setNegativeButtonText(getString(R.string.close));

            statusField.setText(R.string.sync_already_in_progress);
            statusField.setTextColor(getResources().getColor(R.color.orange));

            instructions.setVisibility(View.GONE);
            status.setVisibility(View.VISIBLE);
        }
        // Otherwise, set information about last synchronization and data volume and expect the user to start a manual synchronization
        else {
            // create START listener
            builder.getPositiveButton().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.removePositiveButton();
                    builder.setNegativeButtonText(getString(R.string.sync_continue_background));
                    instructions.setVisibility(View.GONE);
                    progress.setVisibility(View.VISIBLE);

                    // Run the periodic task
                    new SyncTask(builder, dialogContent, dialog)
                            .executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        }
        return true;

    default:
        // If we got here, the user's action was not recognized.
        // Invoke the superclass to handle it.
        // toggle nav drawer on selecting action bar app icon/title
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

From source file:org.dmfs.webcal.fragments.CalendarItemFragment.java

private void setCalendarSynced(final boolean status) {
    final Activity activity = getActivity();
    if (mSynced != status) {
        new ProtectedBackgroundJob<Void, Uri>(activity) {
            @Override//w ww . j a va 2  s .  c  o m
            protected void doPostExecute(Uri result) {
                mSubscriptionUri = result;
            }

            @Override
            protected Uri doInBackground(Void... params) {
                mSynced = status;
                if (status) {
                    if (mSubscriptionUri != null) {
                        // calendar already exists, we just have to enable sync
                        ContentValues values = new ContentValues();
                        values.put(SubscribedCalendars.SYNC_ENABLED, 1);
                        SubscribedCalendars.updateCalendar(activity, mSubscriptionUri, values);
                        return mSubscriptionUri;
                    } else {
                        return SubscribedCalendars.addCalendar(activity, ContentUris.parseId(mContentUri),
                                mCalendarName, (int) (Math.random() * 0x1000000) + 0xff000000);
                    }
                } else {
                    if (mSubscriptionUri != null) {
                        SubscribedCalendars.disableCalendar(activity, mSubscriptionUri);
                    }
                    return null;
                }
            }

        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

}

From source file:hr.abunicic.angular.CameraActivity.java

/**
 * Method that starts detection of shapes.
 *///from   w w w .java 2 s  .  c o m
public void startDetection() {
    startPreview = !startPreview;

    mCamera.startPreview();
    mCamera.setPreviewCallback(new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera camera) {

            //Getting engine results
            VisionEngineResults res = JobScheduler.getEngineResults();
            if (res != null) {
                rp = res;

                updateDescription();
            }

            if (inScheduler < 3 && startPreview) {

                inScheduler++;

                cornersView.setVisibility(View.VISIBLE);

                ByteArrayOutputStream out = new ByteArrayOutputStream();
                params = mCamera.getParameters();
                Camera.Size size = params.getPreviewSize();

                //Compressing frame image to JPEG and then to byte array
                YuvImage yuvImage = new YuvImage(data, ImageFormat.NV21, size.width, size.height, null);
                Rect rectangle = new Rect();
                rectangle.bottom = size.height;
                rectangle.top = 0;
                rectangle.left = 0;
                rectangle.right = size.width;
                yuvImage.compressToJpeg(rectangle, 20, out);
                byte[] imageBytes = out.toByteArray();

                //Starting the PrepareTask for this frame
                new PrepareTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageBytes);
                /*
                                    Bitmap bitmap = BitmapFactory.decodeByteArray(imageBytes , 0, imageBytes.length);
                                    try {
                Matrix matrix = new Matrix();
                        
                matrix.postRotate(90);
                        
                Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(),true);
                        
                Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);
                //storeImage(rotatedBitmap);
                if (mRecognizer.getCurrentState().equals(Recognizer.State.READY)) {
                    mRecognizer.recognizeBitmap(rotatedBitmap, Orientation.ORIENTATION_LANDSCAPE_RIGHT, CameraActivity.this);
                }
                                    } catch (IllegalStateException e) {
                        
                                    }
                */

                if (croppedBitmap != null) {
                    if (mRecognizer.getCurrentState().equals(Recognizer.State.READY)) {
                        storeImage(croppedBitmap);
                        mRecognizer.recognizeBitmap(croppedBitmap, Orientation.ORIENTATION_LANDSCAPE_RIGHT,
                                CameraActivity.this);
                    }
                } else {

                }

                camera.startPreview();

            } else if (!startPreview) {
                cornersView.setVisibility(View.GONE);
            }

        }
    });
}

From source file:org.brandroid.openmanager.util.EventHandler.java

private static Executor getExecutor() {
    if (ENABLE_MULTITHREADS)
        return AsyncTask.THREAD_POOL_EXECUTOR;
    else//from w  w  w .  j a v  a 2  s .  com
        return AsyncTask.SERIAL_EXECUTOR;
}

From source file:com.SecUpwN.AIMSICD.fragments.MapFragment.java

/**
 * Description:    Loads Signal Strength Database details to plot on the map,
 * only entries which have a location (lon, lat) are used.
 *//*from  www  . j  a va 2s .c o  m*/
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            //int signal;

            mCellTowerGridMarkerClusterer.getItems().clear();

            //New function only gets bts from DBe_import by sim network
            loadOcidMarkersByNetwork();

            List<CellTowerMarker> items = new LinkedList<>();

            Cursor c = null;
            try {
                // Grab cell data from CELL_TABLE (cellinfo) --> DBi_bts
                c = mDbHelper.getCellData();
            } catch (IllegalStateException ix) {
                log.error("Problem getting data from CELL_TABLE", ix);
            }

            /*
            This function is getting cells we logged from DBi_bts
             */
            if (c != null && c.moveToFirst()) {
                do {
                    if (isCancelled()) {
                        return null;
                    }
                    // The indexing here is that of DB table
                    final int cellID = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_CID)); // CID
                    final int lac = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAC)); // LAC
                    final int mcc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MCC)); // MCC
                    final int mnc = c.getInt(c.getColumnIndex(DBTableColumnIds.DBI_BTS_MNC)); // MNC
                    final double dLat = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LAT)); // Lat
                    final double dLng = c.getDouble(c.getColumnIndex(DBTableColumnIds.DBI_BTS_LON)); // Lon

                    if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) {
                        continue;
                    }
                    // TODO this (signal) is not in DBi_bts
                    // signal = 1;
                    //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL));  // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    //if (signal <= 0) {
                    //    signal = 20;
                    //}

                    if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) {
                        loc = new GeoPoint(dLat, dLng);

                        CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, "Cell ID: " + cellID, "",
                                loc,
                                new MarkerData(String.valueOf(cellID), String.valueOf(loc.getLatitude()),
                                        String.valueOf(loc.getLongitude()), String.valueOf(lac),
                                        String.valueOf(mcc), String.valueOf(mnc), "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));

                        items.add(ovm);
                    }

                } while (c.moveToNext());
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(getActivity(), getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMCC();
                    double[] d = mDbHelper.getDefaultLocation(mcc);
                    ret = new GeoPoint(d[0], d[1]);
                } catch (Exception e) {
                    log.error("Error getting default location!", e);
                }
            }
            if (c != null) {
                c.close();
            }
            // plot neighbouring cells
            while (mAimsicdService == null) {
                try {
                    if (isCancelled()) {
                        return null;
                    }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.warn("thread interrupted", e);
                }
            }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighbouringCells();
            for (Cell cell : nc) {
                if (isCancelled()) {
                    return null;
                }
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap,
                            getString(R.string.cell_id_label) + cell.getCID(), "", loc,
                            new MarkerData(String.valueOf(cell.getCID()), String.valueOf(loc.getLatitude()),
                                    String.valueOf(loc.getLongitude()), String.valueOf(cell.getLAC()),
                                    String.valueOf(cell.getMCC()), String.valueOf(cell.getMNC()), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    log.error("Error plotting neighbouring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc Default location to open map on
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
                    && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
            if (mCellTowerGridMarkerClusterer != null) {
                if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) {
                    log.verbose("CellTowerMarkers.invalidate() markers.size():"
                            + mCellTowerGridMarkerClusterer.getItems().size());
                }
                //Drawing markers of cell tower immediately as possible
                mCellTowerGridMarkerClusterer.invalidate();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:com.secupwn.aimsicd.ui.fragments.MapFragment.java

/**
 * Description:    Loads Signal Strength Database details to plot on the map,
 * only entries which have a location (lon, lat) are used.
 *///from  w  w  w.j  a v  a 2 s.  c om
private void loadEntries() {

    new AsyncTask<Void, Void, GeoPoint>() {
        @Override
        protected GeoPoint doInBackground(Void... voids) {
            //int signal;
            @Cleanup
            Realm realm = Realm.getDefaultInstance();

            mCellTowerGridMarkerClusterer.getItems().clear();

            loadOcidMarkersByNetwork();

            List<CellTowerMarker> items = new LinkedList<>();

            RealmResults<BaseTransceiverStation> baseStations = realm.where(BaseTransceiverStation.class)
                    .findAll();

            /*
            This function is getting cells we logged from DBi_bts
             */
            if (baseStations.size() > 0) {
                for (BaseTransceiverStation baseStation : baseStations) {

                    if (isCancelled() || !isAdded()) {
                        return null;
                    }
                    // The indexing here is that of DB table
                    final int cellID = baseStation.getCellId();
                    final int lac = baseStation.getLocationAreaCode();
                    final int mcc = baseStation.getMobileCountryCode();
                    final int mnc = baseStation.getMobileNetworkCode();
                    final int psc = baseStation.getPrimaryScramblingCode();

                    Measure first = realm.where(Measure.class)
                            .equalTo("baseStation.cellId", baseStation.getCellId()).findFirst();
                    final String rat = first.getRadioAccessTechnology();
                    final double dLat = baseStation.getGpsLocation().getLatitude();
                    final double dLng = baseStation.getGpsLocation().getLongitude();

                    if (Double.doubleToRawLongBits(dLat) == 0 && Double.doubleToRawLongBits(dLng) == 0) {
                        continue;
                    }
                    // TODO this (signal) is not in DBi_bts
                    // signal = 1;
                    //c.getInt(c.getColumnIndex(DBTableColumnIds.DBE_IMPORT_AVG_SIGNAL));  // signal
                    // In case of missing or negative signal, set a default fake signal,
                    // so that we can still draw signal circles.  ?
                    //if (signal <= 0) {
                    //    signal = 20;
                    //}

                    if (Double.doubleToRawLongBits(dLat) != 0 || Double.doubleToRawLongBits(dLng) != 0) {
                        loc = new GeoPoint(dLat, dLng);

                        CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap, "Cell ID: " + cellID, "",
                                loc,
                                new MarkerData(getContext(), String.valueOf(cellID),
                                        String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                        String.valueOf(lac), String.valueOf(mcc), String.valueOf(mnc),
                                        String.valueOf(psc), rat, "", false));
                        // The pin of our current position
                        ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_blue));

                        items.add(ovm);
                    }
                }
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Helpers.msgLong(getActivity(), getString(R.string.no_tracked_locations_found));
                    }
                });
            }

            GeoPoint ret = new GeoPoint(0, 0);
            if (mBound) {
                try {
                    int mcc = mAimsicdService.getCell().getMobileCountryCode();
                    GpsLocation d = mDbHelper.getDefaultLocation(realm, mcc);
                    ret = new GeoPoint(d.getLatitude(), d.getLongitude());
                } catch (Exception e) {
                    log.error("Error getting default location!", e);
                }
            }
            // plot neighboring cells
            while (mAimsicdService == null) {
                try {
                    if (isCancelled() || !isAdded()) {
                        return null;
                    }
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    log.warn("thread interrupted", e);
                }
            }
            List<Cell> nc = mAimsicdService.getCellTracker().updateNeighboringCells();
            for (Cell cell : nc) {
                if (isCancelled() || !isAdded()) {
                    return null;
                }
                try {
                    loc = new GeoPoint(cell.getLat(), cell.getLon());
                    CellTowerMarker ovm = new CellTowerMarker(getActivity(), mMap,
                            getString(R.string.cell_id_label) + cell.getCellId(), "", loc,
                            new MarkerData(getContext(), String.valueOf(cell.getCellId()),
                                    String.valueOf(loc.getLatitude()), String.valueOf(loc.getLongitude()),
                                    String.valueOf(cell.getLocationAreaCode()),
                                    String.valueOf(cell.getMobileCountryCode()),
                                    String.valueOf(cell.getMobileNetworkCode()),
                                    String.valueOf(cell.getPrimaryScramblingCode()),
                                    String.valueOf(cell.getRat()), "", false));

                    // The pin of other BTS
                    ovm.setIcon(getResources().getDrawable(R.drawable.ic_map_pin_orange));
                    items.add(ovm);
                } catch (Exception e) {
                    log.error("Error plotting neighboring cells", e);
                }
            }

            mCellTowerGridMarkerClusterer.addAll(items);

            return ret;
        }

        /**
         *  TODO:  We need a manual way to add our own location in case:
         *          a) GPS is jammed or not working
         *          b) WiFi location is not used
         *          c) Default MCC is too far off
         *
         * @param defaultLoc Default location to open map on
         */
        @Override
        protected void onPostExecute(GeoPoint defaultLoc) {
            if (loc != null && (Double.doubleToRawLongBits(loc.getLatitude()) != 0
                    && Double.doubleToRawLongBits(loc.getLongitude()) != 0)) {
                mMap.getController().setZoom(16);
                mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
            } else {
                if (mBound) {
                    // Try and find last known location and zoom there
                    GeoLocation lastLoc = mAimsicdService.lastKnownLocation();
                    if (lastLoc != null) {
                        loc = new GeoPoint(lastLoc.getLatitudeInDegrees(), lastLoc.getLongitudeInDegrees());

                        mMap.getController().setZoom(16);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    } else {
                        //Use MCC to move camera to an approximate location near Countries Capital
                        loc = defaultLoc;

                        mMap.getController().setZoom(12);
                        mMap.getController().animateTo(new GeoPoint(loc.getLatitude(), loc.getLongitude()));
                    }
                }
            }
            if (mCellTowerGridMarkerClusterer != null) {
                if (BuildConfig.DEBUG && mCellTowerGridMarkerClusterer.getItems() != null) {
                    log.verbose("CellTowerMarkers.invalidate() markers.size():"
                            + mCellTowerGridMarkerClusterer.getItems().size());
                }
                //Drawing markers of cell tower immediately as possible
                mCellTowerGridMarkerClusterer.invalidate();
            }
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:br.com.rescue_bots_android.bluetooth.MainActivity.java

@SuppressLint("NewApi")
public boolean sendToServer(String serverIP, String serverPort, StringBuilder message, String robotId) {
    if (serverIP != null && serverPort != null && !serverIP.equalsIgnoreCase("")
            && !serverPort.equalsIgnoreCase("")) {
        try {/*from  w ww.  j a v  a2s  .com*/
            myClient = new Client(serverIP, Integer.parseInt(serverPort), message.toString(), mTxtReceive);
            //myClient = new ClienteSocket(mTxtReceive,robotId,serverIP,Integer.parseInt(serverPort));
            //String usuario = "jalmeida";
            //myClient.initClient(serverIP, Integer.parseInt(serverPort) , robotId);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                //myClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"CONNECT");
                myClient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, message.toString());

            } else {
                myClient.execute(message.toString());
                //myClient.execute("CONNECT");
            }
            return true;
        } catch (Exception e) {
            Log.e(this.getLocalClassName(), e.getLocalizedMessage(), e);
        }
    }

    return false;
}

From source file:com.bt.heliniumstudentapp.GradesFragment.java

protected static void getGrades(final int term, String date, final int direction, final int transition) {
    MainActivity.setUI(HeliniumStudentApp.VIEW_GRADES, transition);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
        new GetGradesData().execute(HeliniumStudentApp.URL_GRADES + date + "&periode291=" + term, direction,
                transition + 1);/*from   www  . jav  a 2  s  . c  o m*/
    else
        new GetGradesData().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                HeliniumStudentApp.URL_GRADES + date + "&periode291=" + term, direction, transition + 1);
}