protected void addRouteOnMap(double fromLat, double fromLon, double toLat, double toLon) {

    progressdialog = ProgressDialog.show(NewOrdersRouteOptimizationMapActivity.this, null, null);
    progressdialog.setContentView(R.layout.loader);

    Log.i("", "kkk addRoute from" + fromLat + "," + fromLon);
    Log.i("", "kkk addRoute to" + toLat + "," + toLon);

    String directionUrl =
        String.format(
            "http://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&sensor=false&mode=driving",
            String.valueOf(fromLat),
            String.valueOf(fromLon),
            String.valueOf(toLat),
            String.valueOf(toLon));

    Log.i("", "kkk addRoute direction url" + directionUrl);

    DownloadTask downloadTask = new DownloadTask(mRouteHandler);

    // Start downloading json data from Google Directions API
    downloadTask.execute(directionUrl);

    // new
    // GetNoOfRoutesAPIResponseHandler(String.format("http://maps.googleapis.com/maps/api/directions/json?origin=%s,%s&destination=%s,%s&sensor=false&mode=driving",String.valueOf(fromLat),String.valueOf(fromLon),String.valueOf(toLat),String.valueOf(toLon)), mRouteHandler).start();

  }
Ejemplo n.º 2
0
  /**
   * 中心点的数据处理
   *
   * @param point
   */
  private void getAddress(LatLng point) {
    // 0. 设置中心位置
    aMap.moveCamera(CameraUpdateFactory.changeLatLng(point));
    aMap.moveCamera(
        CameraUpdateFactory.zoomTo(Integer.valueOf(getString(R.string.default_me_zoomlevel))));

    // 1. 清楚地图上的marker
    aMap.clear();

    // 2. 将地理坐标转换为中文地址
    mainMarkerLatLng = point;
    LatLonPoint latLonPoint = new LatLonPoint(point.latitude, point.longitude);
    GeocodeSearch geocoderSearch = new GeocodeSearch(this);
    geocoderSearch.setOnGeocodeSearchListener(this);
    // latLonPoint参数表示一个Latlng,第二参数表示范围多少米,GeocodeSearch.AMAP表示是国测局坐标系还是GPS原生坐标系
    RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 100, GeocodeSearch.AMAP);
    geocoderSearch.getFromLocationAsyn(query); // 设置同步逆地理编码请求

    // 3. 将坐标发送给服务器, 请求附近的停车场的坐标与停车场的信息
    // 初始化url
    String databaseUrl = null;
    databaseUrl = ParkingHttp.AddUrlType(databaseUrl, ParkingHttp.JSON_BASE_DATA);
    databaseUrl =
        ParkingHttp.AddUrlParms(databaseUrl, ParkingHttp.JSON_LAT, String.valueOf(point.latitude));
    databaseUrl =
        ParkingHttp.AddUrlParms(databaseUrl, ParkingHttp.JSON_LNG, String.valueOf(point.longitude));
    databaseUrl = ParkingHttp.AddUrlParms(databaseUrl, ParkingHttp.JSON_RANGE, RANGE_1000);
    Log.e(TAG, databaseUrl);

    if (downloadTask != null) Log.e(TAG, String.valueOf(downloadTask.cancel(true)));
    downloadTask = new DownloadTask();
    downloadTask.execute(databaseUrl);
    // 4. 将这些信息绘制在地图上
  }
 public synchronized void disconnect(Peer p) {
   DownloadTask dt = task.remove(p.toString());
   if (dt != null) {
     dt.end();
     dt = null;
   }
 }
Ejemplo n.º 4
0
 public void startDownload() {
   String strUrl = "http://www.google.com";
   String imgUrl =
       "http://icons.iconarchive.com/icons/position-relative/social-1/128/google-icon.png";
   DownloadTask dt = new DownloadTask(this);
   dt.execute(imgUrl); // strUrl
 }
 public synchronized void connect(Peer p) {
   DownloadTask dt =
       new DownloadTask(
           p, this.torrent.info_hash_as_binary, this.clientID, true, this.getBitField());
   dt.addDTListener(this);
   dt.start();
 }
Ejemplo n.º 6
0
 public void startDownload(Album album) {
   buttonParse.setEnabled(false);
   urlField.setEnabled(true);
   progressBar.setIndeterminate(false);
   progressBar.setString("");
   progressBar.setStringPainted(true);
   downloadTask = new DownloadTask(this, album);
   downloadTask.addPropertyChangeListener(this);
   downloadTask.execute();
 }
Ejemplo n.º 7
0
  /**
   * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件
   *
   * @param task
   * @return "ok" if download success (else return errmessage);
   */
  static String download(DownloadTask task) {
    if (!openedStatus && show) openStatus();

    URL url;
    HttpURLConnection conn;
    try {
      url = new URL(task.getOrigin());
      conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(30000);
      conn.setReadTimeout(30000);
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/"
              + Math.random());
      if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求
        conn.setRequestProperty(
            "User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36");
        // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229;
        // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800");
        conn.setRequestProperty(
            "Cookie",
            "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800");
        conn.setRequestProperty("Host", "www.imgjav.com");
      }
      Path directory = Paths.get(task.getDest()).getParent();
      if (!Files.exists(directory)) Files.createDirectories(directory);
    } catch (Exception e) {
      e.printStackTrace();
      return e.getMessage();
    }

    try (InputStream is = conn.getInputStream();
        BufferedInputStream in = new BufferedInputStream(is);
        FileOutputStream fos = new FileOutputStream(task.getDest());
        OutputStream out = new BufferedOutputStream(fos); ) {
      int length = conn.getContentLength();
      if (length < 1) throw new IOException("length<1");
      byte[] binary = new byte[length];
      byte[] buff = new byte[65536];
      int len;
      int index = 0;
      while ((len = in.read(buff)) != -1) {
        System.arraycopy(buff, 0, binary, index, len);
        index += len;
        allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了
        task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%");
      }
      out.write(binary);
    } catch (IOException e) {
      e.printStackTrace();
      return e.getMessage();
    }
    return "ok";
  }
        public void handleMessage(android.os.Message msg) {
          switch (msg.what) {
            case MSG_INIT:
              FileInfo fileInfo = (FileInfo) msg.obj;
              Log.i(TAG, "Init:" + fileInfo);
              DownloadTask task = new DownloadTask(DownloadService.this, fileInfo, 3);
              task.downLoad();
              mTasks.put(fileInfo.getId(), task);
              break;

            default:
              break;
          }
        };
Ejemplo n.º 9
0
  @Override
  public void propertyChange(PropertyChangeEvent evt) {
    if ("progress".equals(evt.getPropertyName())) {
      if (evt.getSource() instanceof DownloadTask) {
        DownloadTask task = (DownloadTask) evt.getSource();
        progressBar.setValue((Integer) evt.getNewValue());
        progressBar.setString(task.getLabel());
        progressBar.setStringPainted(true);
      }

      if (evt.getSource() instanceof ParseTask) {
        // ParseTask task = (ParseTask) evt.getSource();
        // progressBar.setStringPainted(true);
      }
    }
  }
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case MSG_INIT:
              // 获得初始化的结果
              FileInfo fileInfo = (FileInfo) msg.obj;
              Log.i("fileTest", fileInfo.toString());
              // 启动下载任务
              DownloadTask task = new DownloadTask(DownloadService.this, fileInfo, 3);
              task.download();

              // 把下载任务加入 到下载任务集合
              mTasks.put(fileInfo.getId(), task);
              break;
          }
        }
  /** @see Service#onStartCommand(Intent, int, int) */
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
    if (ACTION_START.equals(intent.getAction())) {
      FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
      Log.i(TAG, "Start:" + fileInfo.toString());
      new InitThread(fileInfo).start();
    } else if (ACTION_STOP.equals(intent.getAction())) {
      FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
      Log.i(TAG, "Stop:" + fileInfo.toString());

      DownloadTask task = mTasks.get(fileInfo.getId());
      if (task != null) {
        task.isPause = true;
      }
    }

    return super.onStartCommand(intent, flags, startId);
  }
  public String download(
      Context context, final String downloadUrl, String dir, String fileName, int threadNum) {
    final DownloadTask task = new DownloadTask(context, downloadUrl, dir, fileName, threadNum);
    task.addDownloadListener(
        new DownloadListener() {
          @Override
          public void onDownloading(int size, int length) {}

          @Override
          public void onDownloadFinish() {
            task.exit();
            tasks.remove(downloadUrl);
          }
        });
    tasks.put(downloadUrl, task);
    task.start();
    return task.getDownloadFilePath();
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // URL to the JSON data
    String strUrl =
        "https://spreadsheets.google.com/feeds/list/0AjImsUF0T00udEU4NWZhVkdnY294REVuMzRPUGxoQ1E/od6/public/values?alt=json";
    // Creating a new non-ui thread task to download json data
    DownloadTask downloadTask = new DownloadTask();
    // Starting the download process
    downloadTask.execute(strUrl);

    // storing string resources into Array
    // final String[] posts = getResources().getStringArray(R.array.posts);

    // Binding resources Array to ListAdapter
    // this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, posts));

    lv = getListView();
    @SuppressWarnings("unused")
    int x = 5;

    // Getting a reference to ListView of activity_main
    // lv = (ListView) findViewById(R.id.lv_posts);

    // listening to single list item on click

    lv.setOnItemClickListener(
        new OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            // selected item
            HashMap<String, Object> post = mPostsList.get(position);
            String loc = post.get("location").toString();
            Log.i("SLN", loc);

            // Launching new Activity on selecting single List Item
            Intent i = new Intent(getApplicationContext(), SingleListItem.class);
            // sending data to new activity
            i.putExtra("location", loc);
            startActivity(i);
          }
        });
  }
Ejemplo n.º 14
0
  public void installApp(View v) {

    if (installUninstall.getText().equals("Uninstall")) {
      Intent intent = new Intent(Intent.ACTION_DELETE);
      intent.setData(Uri.parse("package:" + news.getPackageName()));
      startActivity(intent);
    } else {
      File sdCard = Environment.getExternalStorageDirectory();
      //		String fileStr=sdCard.getAbsolutePath()+""+"app-release.apk";
      DownloadTask downloadTask = new DownloadTask();
      downloadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, news.getWhatsNew());
      Utilities.writeToSharedPref(getApplicationContext(), "INSTALLING", news.getPackageName());
    }
    //		File file=new File(sdCard,"app-release.apk");
    //		Intent prompInstall=new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
    // "application/vnd.android.package-archive");
    //		startActivity(prompInstall);
    layout1.setVisibility(View.VISIBLE);
  }
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
   if (ACTION_START.equals(intent.getAction())) {
     FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
     Log.i("fileInfo", "start:" + fileInfo.toString());
     // 启动初始化线程
     DownloadTask.sExecutorService.execute(new InitThread(fileInfo));
   } else if (ACTION_PAUSE.equals(intent.getAction())) {
     FileInfo fileInfo = (FileInfo) intent.getSerializableExtra("fileInfo");
     Log.i("fileInfo", "pause:" + fileInfo.toString());
     // 从任务集合获得任务
     DownloadTask task = mTasks.get(fileInfo.getId());
     // 暂停下载
     if (task != null) {
       task.isPause = true;
     }
   }
   return super.onStartCommand(intent, flags, startId);
 }
 @Override
 protected Void runInBackground() {
   super.runInBackground();
   if (isCancelled()) {
     return null;
   }
   setStatusMessage("Extracting GeneMANIA files...");
   GenemaniaInfoRetriever.extractGM(getDestPath());
   return null;
 }
Ejemplo n.º 17
0
        @Override
        public void onClick(View v) {

          int id = v.getId();
          if (id == R.id.btn_cancel) {
            finish();
            if (downloadTask != null) {
              downloadTask.isCancelled = true;
            }
            manager.cancel(R.drawable.ic_launcher);
          }
        }
Ejemplo n.º 18
0
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case DOWNLOAD_COMPLETE:
              Place_Latln_Get = true;
              Log.d("TAG", "place_latlng_get");
              Log.d("TAG", "count=" + String.valueOf(ret_place_Name.size()));
              end.setText("終點: " + ret_place_Name.get(ret_place_Name.size() - 1));
              XY =
                  new LatLng(
                      Double.parseDouble(ret_place_Y.get(0)),
                      Double.parseDouble(ret_place_X.get(0)));
              Log.d("TAG", "destination mark");

              break;
            case LOCATION_GET:
              Location_Get = true;
              Log.d("TAG", "location_get");
              break;
            default:
              break;
          }
          if (Place_Latln_Get && Location_Get) {
            if (lat != null && lng != null) {
              Log.d("TAG", "handler");
              mode = "mode=driving";
              url = getDirectionsUrl(mode);
              DownloadTask downloadTask = new DownloadTask();
              downloadTask.execute(url);
              ArrayList<LatLng> center =
                  compareLatLng(
                      ret_place_Y.get(0),
                      ret_place_X.get(0),
                      String.valueOf(lat),
                      String.valueOf(lng));
              LatLngBounds bounds = new LatLngBounds(center.get(1), center.get(0));
              map.moveCamera(CameraUpdateFactory.newLatLngZoom(bounds.getCenter(), 8));
            }
          }
        }
  public Entry download(final JobContext jc, final URL url) {
    if (!mInitialized) {
      initialize();
    }

    final String stringUrl = url.toString();

    // First find in the entry-pool
    synchronized (mEntryMap) {
      final Entry entry = mEntryMap.get(stringUrl);
      if (entry != null) {
        updateLastAccess(entry.mId);
        return entry;
      }
    }

    // Then, find it in database
    final TaskProxy proxy = new TaskProxy();
    synchronized (mTaskMap) {
      final Entry entry = findEntryInDatabase(stringUrl);
      if (entry != null) {
        updateLastAccess(entry.mId);
        return entry;
      }

      // Finally, we need to download the file ....
      // First check if we are downloading it now ...
      DownloadTask task = mTaskMap.get(stringUrl);
      if (task == null) { // if not, start the download task now
        task = new DownloadTask(stringUrl);
        mTaskMap.put(stringUrl, task);
        task.mFuture = mApplication.getThreadPool().submit(task, task);
      }
      task.addProxy(proxy);
    }

    return proxy.get(jc);
  }
Ejemplo n.º 20
0
  // region Map Path & Marker Setups
  private void initMap() {
    // Getting reference to SupportMapFragment of the activity_main
    SupportMapFragment fm =
        (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

    // Getting Map for the SupportMapFragment
    map = fm.getMap();

    // Enable MyLocation Button in the Map
    map.setMyLocationEnabled(true);

    // Draws Start and Stop markers on the Google Map
    drawStartEndMarkers();

    // Checks, whether start and end locations are captured
    if (markerPoints.size() >= 2) {
      LatLng origin = markerPoints.get(0);
      LatLng dest = markerPoints.get(1);

      // Getting URL to the Google Directions API
      String url = getDirectionsUrl(origin, dest);

      DownloadTask downloadTask = new DownloadTask();

      // Start downloading json data from Google Directions API
      downloadTask.execute(url);

      // move Map Camera
      map.moveCamera(
          CameraUpdateFactory.newLatLngZoom(
              new LatLngBounds(markerPoints.get(0), markerPoints.get(1)).getCenter(), 10));
      // map.animateCamera(cameraUpdate);
      // locationManager.removeUpdates(this);
    } else if (markerPoints.size() == 1) {
      map.moveCamera(CameraUpdateFactory.newLatLngZoom(markerPoints.get(0), 15));
    }
  }
Ejemplo n.º 21
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.upgrade_progress_update);
    mInfo = (VersionInfo) getIntent().getSerializableExtra("versionInfo");
    if (mInfo == null) {
      getNewVersionInfo();
    }
    if (mInfo == null) return;
    initApkFile();
    setupView();

    downloadTask = new DownloadTask();
    downloadTask.execute(mInfo.updateURL);
  }
 /**
  * Called when a new peer connects to the client. Check if it is already registered in the peer
  * list, and if not, create a new DownloadTask for it
  *
  * @param s Socket
  */
 public synchronized void connectionAccepted(Socket s) {
   synchronized (this.task) {
     String id = s.getInetAddress().getHostAddress() + ":" + s.getPort();
     if (!this.task.containsKey(id)) {
       DownloadTask dt =
           new DownloadTask(
               null,
               this.torrent.info_hash_as_binary,
               this.clientID,
               false,
               this.getBitField(),
               s);
       dt.addDTListener(this);
       this.peerList.put(dt.getPeer().toString(), dt.getPeer());
       this.task.put(dt.getPeer().toString(), dt);
       dt.start();
     }
   }
 }
Ejemplo n.º 23
0
  @Override
  public void onConnected(Bundle bundle) {
    Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (l != null) {
      mCurrentLatLn = new LatLng(l.getLatitude(), l.getLongitude());
      UIUtils.moveCameraTo(mGoogleMap, mCurrentLatLn, this);
    }

    if (mCurrentLatLn != null) {
      final Parish mostClosed = CoreUtils.getMinLatLng(mCurrentLatLn);

      if (mostClosed != null) {
        // Creating MarkerOptions
        MarkerOptions options = new MarkerOptions();

        // Setting the position of the marker
        options.position(mostClosed.getLatLng());
        options.snippet(mostClosed.getDisplayName());
        options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        mGoogleMap.addMarker(options);

        // Getting URL to the Google Directions API
        String url = getDirectionsUrl(mCurrentLatLn, mostClosed.getLatLng());

        DownloadTask downloadTask = new DownloadTask();

        // Start downloading json data from Google Directions API
        downloadTask.execute(url);
      }
      progressDialog.dismiss();
      showGroup(mCurrentLatLn, mostClosed.getLatLng());

      btnDraw.setOnClickListener(
          new View.OnClickListener() {

            @Override
            public void onClick(View v) {
              String uri =
                  String.format(
                      Locale.ENGLISH,
                      "http://maps.google.com/maps?saddr=%f,%f(%s)&daddr=%f,%f (%s)",
                      mCurrentLatLn.latitude,
                      mCurrentLatLn.longitude,
                      "My position",
                      mostClosed.getLatLng().latitude,
                      mostClosed.getLatLng().longitude,
                      "" + mostClosed.getDisplayName());
              Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
              intent.setClassName(
                  "com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
              startActivity(intent);
            }
          });
      //            btnDraw.setVisibility(View.VISIBLE);

    } else {
      progressDialog.dismiss();
      Toast.makeText(GoActivity.this, "Please enable your location service.", Toast.LENGTH_SHORT)
          .show();
    }
  }
 @Override
 public void jobDone() {
   super.jobDone();
   MedSavantFrame.getInstance()
       .showNotficationMessage("GeneMANIA has finished downloading, and is ready to use.");
 }
Ejemplo n.º 25
0
 @Override
 public void cancel() {
   if (downloadTask != null) {
     downloadTask.cancel();
   }
 }
Ejemplo n.º 26
0
 public void download(String url, String fileName, String title, String text) {
   DownloadTask downloadTask = new DownloadTask(title, text);
   downloadTask.execute(url, fileName);
 }
Ejemplo n.º 27
0
  /**
   * Manipulates the map once available. This callback is triggered when the map is ready to be
   * used. This is where we can add markers or lines, add listeners or move the camera. In this
   * case, we just add a marker near Sydney, Australia. If Google Play services is not installed on
   * the device, the user will be prompted to install it inside the SupportMapFragment. This method
   * will only be triggered once the user has installed Google Play services and returned to the
   * app.
   */
  @Override
  public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    // mMap.setMyLocationEnabled(true);
    mMap.setBuildingsEnabled(true);
    mMap.setTrafficEnabled(true);

    UiSettings gmapsettings = mMap.getUiSettings();
    gmapsettings.setMyLocationButtonEnabled(true);
    gmapsettings.setCompassEnabled(true);
    gmapsettings.setZoomControlsEnabled(true);
    gmapsettings.setZoomControlsEnabled(true);
    gmapsettings.setScrollGesturesEnabled(true);
    gmapsettings.setRotateGesturesEnabled(true);

    Intent ri = getIntent();
    Bundle a = ri.getExtras();
    String start = a.getString("start");
    String end = a.getString("end");

    Geocoder geocoder = new Geocoder(this);
    List<Address> addresses = null;
    try {
      addresses = geocoder.getFromLocationName(start, 1);
    } catch (IOException e) {
      e.printStackTrace();
    }

    double slatitude = addresses.get(0).getLatitude();
    double slongitude = addresses.get(0).getLongitude();

    // Add a marker to start
    LatLng smarker = new LatLng(slatitude, slongitude);
    mMap.addMarker(
        new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.markers1))
            .position(smarker)
            .title("Pick Up"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(smarker));

    try {
      addresses = geocoder.getFromLocationName(end, 1);
    } catch (IOException e) {
      e.printStackTrace();
    }

    double elatitude = addresses.get(0).getLatitude();
    double elongitude = addresses.get(0).getLongitude();

    // Add a marker to end
    LatLng emarker = new LatLng(elatitude, elongitude);
    mMap.addMarker(
        new MarkerOptions()
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.markers2))
            .position(emarker)
            .title("Destination"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(emarker));

    LatLng origin = smarker;
    LatLng dest = emarker;

    // Getting URL to the Google Directions API
    String url = getDirectionsUrl(origin, dest);

    DownloadTask downloadTask = new DownloadTask();

    // Start downloading json data from Google Directions API
    downloadTask.execute(url);

    mMap.animateCamera(CameraUpdateFactory.newLatLng(smarker));
  }
Ejemplo n.º 28
0
 private void downloadUpdate(String url, CallbackContext callbackContext) {
   final DownloadTask downloadTask = new DownloadTask(this.myContext, callbackContext);
   downloadTask.execute(url);
 }
Ejemplo n.º 29
0
  /** function to load map. If map is not created it will create it for you */
  private void initilizeMap() {
    if (googleMap == null) {
      try {
        prefs = getSharedPreferences("Zira", MODE_PRIVATE);
        curLatitude = Double.parseDouble(prefs.getString("tripstarttlat", ""));
        curLongitude = Double.parseDouble(prefs.getString("tripstartlong", ""));
        destLongitude = Double.parseDouble(prefs.getString("tripdestlong", ""));
        destLatitude = Double.parseDouble(prefs.getString("tripdestlat", ""));
      } catch (Exception e) {
        e.printStackTrace();
      }
      googleMap =
          ((MapFragment) getFragmentManager().findFragmentById(R.id.rider_ride_map)).getMap();
      googleMap.setMyLocationEnabled(true);
      googleMap.getUiSettings().setRotateGesturesEnabled(true);
      googleMap.getUiSettings().setZoomControlsEnabled(false);
      CameraPosition cameraPosition =
          new CameraPosition.Builder()
              .target(new LatLng(curLatitude, curLongitude))
              .zoom(15)
              .build();

      googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

      placeMarker();

      LatLng curLatLng = new LatLng(curLatitude, curLongitude);
      LatLng destLatLng = new LatLng(destLatitude, destLongitude);

      Log.i("tag", "Longitude:" + curLongitude);
      Log.i("tag", "Latitude:" + curLongitude);
      Log.i("tag", "destLongitude:" + destLongitude);
      Log.i("tag", "destLatitude:" + destLatitude);

      String url = getDirectionsUrl(curLatLng, destLatLng);
      DownloadTask downloadTask = new DownloadTask();
      downloadTask.execute(url);

      // check if map is created successfully or not
      if (googleMap == null) {
        Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT)
            .show();
      }
      locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
      criteria = new Criteria();

      // Getting the name of the best provider
      provider = locationManager.getBestProvider(criteria, true);

      try {
        boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        // Check if enabled and if not send user to the GSP settings
        if (!enabledGPS && !enabledWiFi) {
          Toast.makeText(EndRideActivity.this, "GPS signal not found", Toast.LENGTH_LONG).show();
          Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
          startActivity(intent);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      locationManager.requestLocationUpdates(provider, 15000, 0, this);
    }
  }
Ejemplo n.º 30
0
  public void reloadSubreddits(final ISubredditChangedListener subredditChangedListener) {
    DownloadTask downloadTask =
        new DownloadTask(sessionManager) {
          @Override
          protected void onDownloadComplete(List<RedditPost> results) {
            LogMe.e("Downloaded " + results.size() + " subreddit categories");

            subredditList.clear();
            subredditList.add(DEFAULT_SUBREDDIT);
            for (RedditPost redditPost : results) {
              String subredditUrl = redditPost.getUrl().toString();
              if (subredditUrl.startsWith(SUBREDDIT_PREFIX)) {
                subredditUrl = subredditUrl.substring(3);
              }
              subredditList.add(subredditUrl);
            }

            progressBar.setVisibility(View.INVISIBLE);

            subredditSpinnerView.setOnItemSelectedListener(
                new OnItemSelectedListener() {
                  public void onItemSelected(
                      AdapterView<?> parent, View view, int position, long id) {
                    String subredditName = subredditList.get(position);
                    changeSubreddit(subredditChangedListener, subredditName);
                  }

                  public void onNothingSelected(AdapterView<?> parent) {
                    subredditSpinnerView.setSelection(0);
                  }
                });

            subredditSpinnerView.setOnLongClickListener(
                new OnLongClickListener() {
                  public boolean onLongClick(View view) {
                    final EditText editText = new EditText(SubredditController.this.activity);

                    new AlertDialog.Builder(SubredditController.this.activity)
                        //
                        .setTitle("Enter subreddit")
                        .setView(editText)
                        .setPositiveButton(
                            "Ok",
                            new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialog, int whichButton) {
                                String newSubreddit = editText.getText().toString();
                                addNewSubreddit(subredditChangedListener, newSubreddit);
                              }
                            })
                        .setNegativeButton(
                            "Cancel",
                            new DialogInterface.OnClickListener() {
                              public void onClick(DialogInterface dialog, int whichButton) {
                                // Do nothing.
                              }
                            })
                        .show();

                    return true;
                  }
                });

            subredditSpinnerView.setAdapter(createNewSubredditAdapter());
            subredditSpinnerView.setSelection(0);
          }
        };

    String subredditUrl = dataSourceUrl + REDDITS_URL;
    LogMe.e("Subreddits from: " + subredditUrl);
    downloadTask.execute(subredditUrl);
  }