コード例 #1
0
ファイル: RouteFragment.java プロジェクト: haovn577/open
 private void logForDebugging(Location location, Location correctedLocation) {
   Logger.logToDatabase(
       act,
       db,
       ROUTE_TAG,
       "RouteFragment::onLocationChangeLocation: "
           + "new corrected location: "
           + correctedLocation.toString()
           + " from original: "
           + location.toString());
   Logger.logToDatabase(
       act,
       db,
       ROUTE_TAG,
       "RouteFragment::onLocationChangeLocation: "
           + "threshold: "
           + String.valueOf(getAdvanceRadius()));
   for (Instruction instruction : instructions) {
     Logger.logToDatabase(
         act,
         db,
         ROUTE_TAG,
         "RouteFragment::onLocationChangeLocation: " + "turnPoint: " + instruction.toString());
   }
 }
コード例 #2
0
ファイル: MapsActivity.java プロジェクト: Pastew/gdzieNaPiwo
  private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    Log.d("Lokacja", location.toString());

    // conversion to simple coordinate
    String goodFormatLocation = locationStringFromLocation(location);
    Log.d("Lokacja22", goodFormatLocation);

    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();

    a = currentLatitude;
    b = currentLongitude;

    this.onSearch();

    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    // mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude,
    // currentLongitude)).title("Current Location"));
    MarkerOptions options = new MarkerOptions().position(latLng).title("I am here!");
    mMap.addMarker(options);
    // mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    float zoomLevel = 16.0f; // This goes up to 21
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoomLevel));
  }
 @Override
 public void onLocationChanged(Location location) {
   if (location != null) {
     Log.i("GPS", location.toString());
     lastKnownLocation = location;
   }
 }
コード例 #4
0
  public static synchronized String getLocation(Context context) {
    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    String strLocationProvider = lm.getBestProvider(criteria, true);

    Location location = lm.getLastKnownLocation(strLocationProvider);

    if (location != null) {
      StringBuffer locationString = new StringBuffer();
      locationString.append("latitude=");
      locationString.append(location.getLatitude());
      locationString.append("&longitude=");
      locationString.append(location.getLongitude());
      Log.d(TAG, "Got location: " + location.toString());
      return locationString.toString();
    }

    return "";
    //		File location = new File(context.getFilesDir(), FILENAME);
    //		try {
    //			if (!location.exists()) {
    //				updateLocation(context);
    //			}
    //			return readLocationFile(location);
    //		} catch (Exception e) {
    //			throw new RuntimeException(e);
    //		}
  }
コード例 #5
0
 /**
  * Called each time we receive a new location notification. - sends the location back to the
  * LocationReceiver that requested the location.
  */
 public void onLocationChanged(Location loc) {
   Log.i(TAG, "onLocationChanged() - location found.");
   if (loc != null) {
     Log.i(TAG, "OnLocationChanged() - returning Location (" + loc.toString() + ")");
     Toast.makeText(
         mContext,
         "Location is (" + loc.getLatitude() + "," + loc.getLongitude() + ")",
         Toast.LENGTH_LONG);
     LonLat ll;
     ll =
         new LonLat(
             loc.getLongitude(),
             loc.getLatitude(),
             loc.getAccuracy(),
             loc.getProvider(),
             new Date(loc.getTime()));
     // Now we have a location, unsubscribe from location updates.
     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
     // And retrn the location to the requesting process.
     lr.onLocationFound(ll);
   } else {
     Log.i(TAG, "onLocationChanged() - Location is null????");
     Toast.makeText(mContext, "No Location Detected", Toast.LENGTH_LONG).show();
     lr.onLocationFound(null);
   }
 }
コード例 #6
0
  @Override
  public void onLocationChanged(Location location) {
    Log.d(TAG, "- onLocationChanged" + location.toString());

    if (config.isDebugging()) {
      Toast.makeText(
              FusedLocationService.this,
              "acy:"
                  + location.getAccuracy()
                  + ",v:"
                  + location.getSpeed()
                  + ",df:"
                  + config.getDistanceFilter(),
              Toast.LENGTH_LONG)
          .show();
    }

    // if (lastLocation != null && location.distanceTo(lastLocation) < config.getDistanceFilter()) {
    //     return;
    // }

    if (config.isDebugging()) {
      startTone("beep");
    }

    lastLocation = location;
    handleLocation(location);
  }
コード例 #7
0
ファイル: helloAndroid.java プロジェクト: wkliang/android
 // Called when location has changed
 public void onLocationChanged(Location location) {
   if (location == null) {
     Log.d(TAG, "onLocationChanged is null");
   } else {
     Log.d(TAG, "onLocationChanged:" + location.toString());
     lastLocation = location;
   }
 }
コード例 #8
0
ファイル: MapsActivity.java プロジェクト: Kwapi/ParkingAid
  private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());

    LatLng currentPosition = new LatLng(location.getLatitude(), location.getLongitude());

    mMap.clear();
    mMap.addMarker(new MarkerOptions().position(currentPosition).title("You are here"));
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 20.0f));
  }
  private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();
    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    MarkerOptions options = new MarkerOptions().position(latLng);
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
  }
コード例 #10
0
ファイル: MainActivity.java プロジェクト: kkopsa/android_fire
 private String getGPSLocation() {
   String coords;
   if (mGPSLocation == null) {
     Location locationGPS = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
     coords = locationGPS.toString();
     return coords;
   } else {
     return mGPSLocation;
   }
 }
コード例 #11
0
 @Override
 public void onGetLocationSuccess(Location loc) {
   // TODO Auto-generated method stub
   Log.v(
       TAG,
       "调用onGetLocationSuccess,线程ID是:"
           + Thread.currentThread().getId()
           + " name: "
           + Thread.currentThread().getName());
   Log.v(TAG, "位置是:" + loc.toString());
 }
コード例 #12
0
  @Override
  public void locationUpdate(Location update, boolean initial) {
    if (LocationController.isBetterLocation(update, mLastLocation)) {
      mLastLocation = update;
    }

    Log.d("Location SERVICE", "Location Update:" + update.toString());
    if (!initial) {
      mUpdateController.update(update);
      passiveLocationController.stop();
    }
  }
コード例 #13
0
ファイル: BaseActivity.java プロジェクト: MaTriXy/CofShop
 @Override
 public void onConnected(Bundle bundle) {
   L.m("onConnected");
   mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
   if (mLocation == null) {
     LocationServices.FusedLocationApi.requestLocationUpdates(
         mGoogleApiClient, mLocationRequest, this);
   } else {
     L.s(this, mLocation.toString());
     updateLocation(mLocation);
   }
 }
        @Override
        public void onReceive(Context context, Intent intent) {
          Log.d(TAG, "- locationUpdateReceiver TRIGGERED!!!!!!!!!!");
          String key = FusedLocationProviderApi.KEY_LOCATION_CHANGED;
          Location location = (Location) intent.getExtras().get(key);

          if (location != null) {
            Log.d(TAG, "- locationUpdateReceiver" + location.toString());

            lastLocation = location;
            broadcastLocation(location);
          }
        }
コード例 #15
0
        @Override
        public void onReceive(Context context, Intent intent) {
          if (intent.getAction().equalsIgnoreCase(LOCATION_UPDATE_ACTION)) {
            //				try {
            Location location = intent.getParcelableExtra(LocationManager.KEY_LOCATION_CHANGED);
            //				location = null;
            Log.d(TAG, "New location: [" + location.getProvider() + "]" + location.toString());

            LocationUtil.setAtHome(location.getLatitude(), location.getLongitude(), 100);
            Log.d(TAG, "At home? " + LocationUtil.isAtHome());
            //				} catch (Exception ex) {
            //					Log.e(ex.getClass().getName(), "", ex);
            //				}

          }
        }
コード例 #16
0
 @Override
 public void run() {
   lastLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
   currLocation = LocationServices.FusedLocationApi.getLastLocation(apiClient);
   if (lastLocation != null) {
     currLocation.setLatitude(latIntrepid);
     currLocation.setLongitude(longIntrepid);
     locationDifference = lastLocation.distanceTo(currLocation);
     if (locationDifference < DISPLACEMENT) {
       Log.e("location", "im within radius");
       chechIn = true;
     } else {
       Log.e("location", "in else of display");
       Log.e("location", lastLocation.toString() + ",");
     }
   }
 }
コード例 #17
0
  private Location registerProvider(String provider) {
    long minTime = this.getPeriodTime() < MIN_RATE_TIME ? MIN_RATE_TIME : getPeriodTime();
    Location location = null;
    try {
      Log.d(TAG, "Time rate: " + minTime);
      locationManager.requestLocationUpdates(provider, minTime, MIN_DISTANCE, pendingIntent);

      // Initialize it with the last known location (it is better than nothing at all).
      location = locationManager.getLastKnownLocation(provider);
      if (location != null) {
        Log.d(TAG, "New location: " + location.toString());
      }
    } catch (Exception e) {
      Log.e(TAG, "Requesting location updates failed", e);
    }
    Log.d(TAG, "Location Provider registered: " + provider);
    return location;
  }
コード例 #18
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Organize Location Manager
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new NachbarschaftsLocationListener(this);
    locationManager.requestLocationUpdates(
        LocationManager.GPS_PROVIDER, 300000, 100, locationListener);
    currentLocation = getLastBestLocation();
    Log.i(TAG, "Location: " + currentLocation.toString());

    swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
    swipeView.setOnRefreshListener(this);

    // Greet the user, or ask for their name if new
    displayWelcome();

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            addNewItem();
          }
        });

    mDialog = new ProgressDialog(this);
    mDialog.setMessage("Searching for items");
    mDialog.setCancelable(false);

    // Create a JSONAdapter for the ListView
    mJSONAdapter = new JSONAdapter(this, getLayoutInflater());

    // Set the ListView to use the ArrayAdapter
    mainListView = (ListView) findViewById(R.id.main_listview);
    mainListView.setOnItemClickListener(this);
    mainListView.setAdapter(mJSONAdapter);

    queryItems(currentLocation);
  }
コード例 #19
0
  public void locationCb(String url, Location loc, AjaxStatus status) {

    if (loc != null) {
      Log.d("Location:" + loc.toString());
      mLatitude = String.valueOf(loc.getLatitude());
      mLongitude = String.valueOf(loc.getLongitude());

      // PlaceAPI api = new PlaceAPI(mAccessToken);
      // api.nearbyPois(mLatitude, mLongitude, range, q, category, count, page, offset, listener);

      mIsLocation = true;

      aq.id(R.id.ly_loadlocation).gone();
      aq.id(R.id.tv_location).visible();
      aq.id(R.id.ib_insert_location).image(R.drawable.btn_insert_location_nor_2);
    } else {
      Log.w("loc is null!");
    }
  }
 private void updateLocation() {
   switch (locationManagementMethod) {
     case GPS:
       Criteria c = new Criteria();
       if (locationManager == null) {
         Log.e("GPS", "No locationManager found");
         return;
       }
       // it will check first satellite location than Internet and than Sim Network
       String provider = locationManager.getBestProvider(c, false);
       if (provider == null) {
         Log.e("GPS", "No providers found");
         lastKnownLocation = new Location("Manual");
         double latitude = 2.345689;
         double longitude = 45.4567806;
         lastKnownLocation.setLatitude(latitude);
         lastKnownLocation.setLongitude(longitude);
         break;
       }
       Location location = locationManager.getLastKnownLocation(provider);
       if (location != null) {
         Log.i("GPS", location.toString());
         lastKnownLocation = location;
       }
       break;
     case MANUAL_COORDINATES:
       lastKnownLocation = new Location("Manual");
       double latitude = 2.345689;
       double longitude = 45.4567806;
       lastKnownLocation.setLatitude(latitude);
       lastKnownLocation.setLongitude(longitude);
       break;
     default:
       break;
   }
   if (textLatitude != null && textLongitude != null) {
     textLatitude.setText(String.valueOf(lastKnownLocation.getLatitude()));
     textLongitude.setText(String.valueOf(lastKnownLocation.getLongitude()));
   }
 }
コード例 #21
0
  @Override
  public void onLocationChanged(Location location) {
    if (DEBUG) Log.d(TAG, location.toString());
    String provider = location.getProvider();
    if (LocationManager.GPS_PROVIDER.equals(provider)) {
      mLocation = new Location(location);
      if (mStartTime == 0) {
        mStartTime = System.currentTimeMillis();
        Message msg = Message.obtain(mHandler, MSG_REPORT_LOCATION);
        // Improve the precision, collect location after 3 second.
        mHandler.sendMessageDelayed(msg, 3100);

        // When get first position, set self stop timer
        mHandler.sendEmptyMessageDelayed(MSG_STOP_SELF, mTrack * mPrecise * 1000 + 5000);
      } else {
        long current = System.currentTimeMillis();
        long elapse = current - mStartTime;
        if (elapse > (mPrecise * 1000)) {
          mStartTime = current;
          Message msg = Message.obtain(mHandler, MSG_REPORT_LOCATION);
          mHandler.removeMessages(MSG_REPORT_LOCATION);
          mHandler.sendMessage(msg);
        } else {
          Message msg = Message.obtain(mHandler, MSG_REPORT_LOCATION);
          mHandler.removeMessages(MSG_REPORT_LOCATION);
          mHandler.sendMessageDelayed(msg, mPrecise * 1000 - elapse);
        }
      }
    } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
      // only update network once
      // if (mNetworkLocation == null) {
      mNetworkLocation = new Location(location);
      Message msg = Message.obtain(mHandler, MSG_REPORT_COARSE_LOCATION);
      mHandler.sendMessage(msg);
      // }
    }
  }
コード例 #22
0
ファイル: MapsFragment.java プロジェクト: pratincola/myRepo
  public void updateMap(Location location) {
    Log.i(TAG, " Holy Moley ..." + location.toString());
    UserObject o =
        new UserObject("user", "" + location.getLatitude(), "" + location.getLongitude());

    userInfo.enqueue(o);
    userInfo.enqueueLoc(location);
    Log.i(TAG, "new co-ordinates: ========> " + o.getLast_lat() + o.getLast_long());
    userSession.setCurrLat(location.getLatitude());
    userSession.setCurrLng(location.getLongitude());

    // To avoid the case where we don't have enough data points
    if (userInfo.size() > 1) {
      UserObject lastInfo = userInfo.dequeue();
      Location dest = userInfo.dequeueLoc();

      //            calcSpeed(location.getLatitude(), location.getLongitude(),
      //                        lastInfo.getLast_lat_double(), lastInfo.getLast_long_double());
      calcSpeed(location, dest);
    }

    // Update friends locations
    if (!userSession.friends.isEmpty()) {
      Enumeration e = userSession.friends.elements();
      while (e.hasMoreElements()) {
        Log.i(TAG, " next friend ");
        updateFriendMarker((UserObject) e.nextElement());
      }
    }

    if (location.hasBearing()) {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), location.getBearing());
    } else {
      gotoMyLocation(location.getLatitude(), location.getLongitude(), 0f);
    }
  }
コード例 #23
0
        @Override
        public void onLocationChanged(Location location) {

          mTextView.setText(location.toString());
        }
コード例 #24
0
 private void handleNewLocation(Location location) {
   mCurrentLatitude = location.getLatitude();
   mCurrentLongitude = location.getLongitude();
   getForcast();
   Log.d(TAG, location.toString());
 }
コード例 #25
0
 private void handleNewLocation(Location location) {
   Log.d(TAG, "New location: " + location.toString());
   userLatitude = location.getLatitude();
   userLongitude = location.getLongitude();
   Log.d(TAG, "Lat & Long updated. Lat: " + userLatitude + " Long: " + userLongitude);
 }
コード例 #26
0
 @Override
 public void onLocationChanged(Location location) {
   Log.d(TAG, location.toString());
   CommManager.currentLocation = location;
   CommManager.locationChangedListener.onLocationChanged(location);
 }
コード例 #27
0
  @Override
  public List<SimpleSection<StopStub>> loadInBackground() {
    // Stops is the return value it will hold headers as well as stops
    final List<SimpleSection<StopStub>> stops = new ArrayList<>();
    // Nearby stops are one of the sections in stops
    final List<StopStub> nearbyStops = new ArrayList<>();
    stops.add(new SimpleSection<>(getContext().getString(R.string.nearby_bus_header), nearbyStops));

    // Check for location services
    if (location != null) {
      if (BuildConfig.DEBUG) LOGD(TAG, "Current location: " + location.toString());
      LOGI(TAG, "Updating nearby active stops");

      try {
        // Get nearby stops from the api
        final List<StopGroup> nbNearbyStops =
            NextbusAPI.getActiveStopsByTitleNear(
                NextbusAPI.AGENCY_NB,
                (float) location.getLatitude(),
                (float) location.getLongitude());
        final List<StopGroup> nwkNearbyStops =
            NextbusAPI.getActiveStopsByTitleNear(
                NextbusAPI.AGENCY_NWK,
                (float) location.getLatitude(),
                (float) location.getLongitude());
        if (nbNearbyStops.isEmpty() && nwkNearbyStops.isEmpty()) {
          // If there aren't any results, put a "no stops nearby" message
          // addNearbyRow(1, new RMenuItemRow(noneNearbyString));
        } else {
          // Add all the stops
          for (StopGroup stopGroup : nbNearbyStops) nearbyStops.add(new StopStub(stopGroup));
          for (StopGroup stopGroup : nwkNearbyStops) nearbyStops.add(new StopStub(stopGroup));
        }
      } catch (JsonSyntaxException | IOException e) {
        LOGE(TAG, e.getMessage());
      }
    } else {
      LOGW(TAG, "Couldn't get location, can't find nearby stops");
      // addNearbyRow(1, new RMenuItemRow(getString(R.string.failed_location)));
    }

    // Get home campus for result ordering
    final String userHome = RutgersUtils.getHomeCampus(getContext());
    final boolean nbHome = userHome.equals(getContext().getString(R.string.campus_nb_full));

    try {
      // Get active stops
      final List<StopStub> nbActiveStops = NextbusAPI.getActiveStops(NextbusAPI.AGENCY_NB);
      final List<StopStub> nwkActiveStops = NextbusAPI.getActiveStops(NextbusAPI.AGENCY_NWK);

      if (nbHome) {
        stops.add(loadAgency(NextbusAPI.AGENCY_NB, nbActiveStops));
        stops.add(loadAgency(NextbusAPI.AGENCY_NWK, nwkActiveStops));
      } else {
        stops.add(loadAgency(NextbusAPI.AGENCY_NWK, nwkActiveStops));
        stops.add(loadAgency(NextbusAPI.AGENCY_NB, nbActiveStops));
      }
    } catch (JsonSyntaxException | IOException e) {
      LOGE(TAG, e.getMessage());
    }
    return stops;
  }
コード例 #28
0
 /** Describe the given location, which might be null */
 private void dumpLocation(Location location) {
   if (location == null) log(" ");
   else {
     log("\n" + location.toString());
   }
 }
コード例 #29
0
  @Override
  public void onClick(View v) {
    int i;
    TelephonyManager tMgr;
    LocationManager lm;
    ContentResolver cr;
    Intent intent;
    switch (v.getId()) {
      case R.id.btnTest:
        String Eval_result = "";
        tMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        long t0 = System.currentTimeMillis();
        for (i = 0; i < 200; i++) {
          String PhoneNo = tMgr.getLine1Number();
          //				String IMEI = tMgr.getDeviceId();
          //				String IMSI = tMgr.getSubscriberId();
        }
        t0 = System.currentTimeMillis() - t0;
        Eval_result += String.format("200 PhoneInfo: %d ", t0);

        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        t0 = System.currentTimeMillis();
        for (i = 0; i < 200; i++) {
          Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        }
        t0 = System.currentTimeMillis() - t0;
        Eval_result += String.format("200 Location: %d ", t0);

        cr = getContentResolver();
        t0 = System.currentTimeMillis();
        for (i = 0; i < 200; i++) {
          Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
          cursor.close();
        }
        t0 = System.currentTimeMillis() - t0;
        Eval_result += String.format("200 ContactList: %d ", t0);

        Log.i("apihook", Eval_result);
        break;
      case R.id.btnSendSMS:
        final Handler SMShandler = new Handler();
        for (i = 0; i < 1; i++) {
          Thread showdlgthrd =
              new Thread(
                  new Runnable() {
                    @Override
                    public void run() {
                      //						try
                      {
                        SmsManager sm = SmsManager.getDefault();
                        String number = "5556";
                        sm.sendTextMessage(number, null, "Test SMS Message", null, null);
                        SMShandler.post(
                            new Runnable() {
                              public void run() {
                                Toast.makeText(
                                        ApkMonitorActivity.this, "SMS is sent.", Toast.LENGTH_SHORT)
                                    .show();
                              }
                            });
                      }
                      //						catch(final Exception e)
                      //						{
                      //					    	SMShandler.post(new Runnable() {
                      //								public void run() {
                      //									Toast.makeText(ApkMonitorActivity.this, "SendSMS Exception:" +
                      // e.toString(), Toast.LENGTH_SHORT).show();
                      //								}
                      //					    	});
                      //						}
                    }
                  });
          showdlgthrd.start();
        }
        break;
      case R.id.btnGetPhoneInfo:
        tMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String PhoneNo = tMgr.getLine1Number();
        String IMEI = tMgr.getDeviceId();
        String IMSI = tMgr.getSubscriberId();
        Toast.makeText(
                this,
                String.format("IMEI: %s\nIMSI: %s\nPhone No: %s", IMEI, IMSI, PhoneNo),
                Toast.LENGTH_SHORT)
            .show();
        break;
      case R.id.btnInternet:
        try {
          TrustManager[] trustAllCerts =
              new TrustManager[] {
                new X509TrustManager() {
                  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                  }

                  public void checkClientTrusted(
                      java.security.cert.X509Certificate[] certs, String authType) {}

                  public void checkServerTrusted(
                      java.security.cert.X509Certificate[] certs, String authType) {}
                }
              };

          // Install the all-trusting trust manager
          try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
          } catch (Exception e) {
          }

          String line, alllines;
          BufferedReader rd;

          URL url = new URL("http://www.cl.cam.ac.uk/~rx201/test.txt");
          URLConnection conn = url.openConnection();
          // Get the response
          rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          line = "";
          alllines = "";
          while ((line = rd.readLine()) != null) {
            alllines = alllines + line;
          }
          Toast.makeText(this, alllines, Toast.LENGTH_LONG).show();

          URL https_url = new URL("https://www.google.com/robots.txt");
          HttpsURLConnection con = (HttpsURLConnection) https_url.openConnection();

          rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
          line = "";
          alllines = "";
          int lineno = 0;
          while ((line = rd.readLine()) != null && lineno < 5) {
            alllines = alllines + line + "\n";
            lineno++;
          }
          Toast.makeText(this, "SSL: Google robots.txt\n" + alllines, Toast.LENGTH_LONG).show();

        } catch (Exception e) {
          Toast.makeText(this, "Internet Exception:" + e.toString(), Toast.LENGTH_SHORT).show();
        }
        break;
      case R.id.btnDial:
        try {
          System.loadLibrary("/data/data/com.zft/lib/libzftnative.so");
          Runtime.getRuntime().exec("su");
        } catch (IOException e1) {
          // TODO Auto-generated catch block
          e1.printStackTrace();
        }
        break;
        //			for(int i=0;i<4;i++)
        //			{
        //		    	Thread showdlgthrd = new Thread(new Runnable(){
        //					@Override
        //					public void run() {
        //						Intent i = new Intent( Intent.ACTION_CALL );
        //						i.setData( Uri.parse( "tel:5556" ) );
        //						i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //						APIHook.LowlevelStartActivity( i );
        //					}
        //		    	});
        //		    	showdlgthrd.start();
        //		    	try {
        //		    		showdlgthrd.join();
        //		    	}catch(Exception e) {}
        //				Log.i("apihook_Dial", "Thread complete.");
        //			}
        //			intent = new Intent( Intent.ACTION_CALL );
        //			intent.setData( Uri.parse( "tel:5556" ) );
        //			startActivity( intent );
        //			Toast.makeText(this, "Dailing 5556..", Toast.LENGTH_SHORT).show();
        //			break;
      case R.id.btnService:
        intent = new Intent(IMyService.class.getName());
        startService(intent);
        bindService(
            intent,
            new ServiceConnection() {
              @Override
              public void onServiceConnected(ComponentName name, IBinder service) {
                final IMyService api = IMyService.Stub.asInterface(service);
                try {
                  int r =
                      api.add(
                          1,
                          1,
                          new IAddResultCallback.Stub() {
                            @Override
                            public int onResult(int i1, int i2) throws RemoteException {
                              if (i1 == 0 && i2 == 0) {
                                Log.i("apihook_AddCallback", "returns");
                                return 0;
                              }
                              Log.i("apihook_AddCallback", String.format("RECURSE:%d %d", i1, i2));
                              return 1 + api.add(i2 - 1, i1, this);
                            }
                          });
                  Log.i("apihook_service", String.format("1 + 1 = %d", r));
                } catch (RemoteException e) {
                  Log.e("apihook", "Failed to add listener", e);
                }
              }

              @Override
              public void onServiceDisconnected(ComponentName name) {
                Log.i("apihook", "Service connection closed");
              }
            },
            0);
        break;
      case R.id.btnReadContact:
        String s = "";
        cr = getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
          String[] columns = cursor.getColumnNames();
          for (i = 0; i < columns.length; i++) s = s + columns[i] + "    ";
          s += "\n";
          do {
            for (i = 0; i < columns.length; i++) s = s + cursor.getString(i) + "    ";
            s += "\n";
          } while (cursor.moveToNext());
          Toast.makeText(ApkMonitorActivity.this, s, Toast.LENGTH_SHORT).show();
        } else
          Toast.makeText(ApkMonitorActivity.this, "Empty Content Provider.", Toast.LENGTH_SHORT)
              .show();

        break;
      case R.id.btnExecve:
        final Handler ExecvpHandler = new Handler();
        final String[] commands = new String[] {"uptime", "ls", "cat /proc/cpuinfo"};
        for (i = 0; i < commands.length; i++) {
          final String command = commands[i];
          Thread showdlgthrd =
              new Thread(
                  new Runnable() {
                    @Override
                    public void run() {
                      try {
                        Process p = Runtime.getRuntime().exec(command);
                        BufferedReader rdr =
                            (new BufferedReader(new InputStreamReader(p.getInputStream())));
                        String t;
                        StringBuilder sb = new StringBuilder();
                        while ((t = rdr.readLine()) != null) {
                          sb.append(t);
                          sb.append('\n');
                        }
                        final String txt = sb.toString();
                        ExecvpHandler.post(
                            new Runnable() {
                              public void run() {
                                Toast.makeText(
                                        ApkMonitorActivity.this,
                                        "Execvp - '" + command + "': " + txt,
                                        Toast.LENGTH_SHORT)
                                    .show();
                              }
                            });
                      } catch (IOException e) {
                        e.printStackTrace();
                        ExecvpHandler.post(
                            new Runnable() {
                              public void run() {
                                Toast.makeText(
                                        ApkMonitorActivity.this,
                                        "Execute " + command + " failed.",
                                        Toast.LENGTH_SHORT)
                                    .show();
                              }
                            });
                      }
                    }
                  });
          showdlgthrd.start();
        }
        break;
      case R.id.btnGetLocation:
        lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //			List<String> lps = lm.getAllProviders();
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null)
          Toast.makeText(ApkMonitorActivity.this, location.toString(), Toast.LENGTH_LONG);
        else Toast.makeText(ApkMonitorActivity.this, "No known last position.", Toast.LENGTH_LONG);

        intent = new Intent("com.rx201.apkmon.ProximityAlert");
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
        lm.addProximityAlert(123, 123, 10, -1, pIntent);

        lm.requestLocationUpdates(
            "gps",
            0,
            0,
            new LocationListener() {

              @Override
              public void onLocationChanged(Location location) {
                Toast.makeText(
                    ApkMonitorActivity.this,
                    "Location update: " + location.toString(),
                    Toast.LENGTH_LONG);
              }

              @Override
              public void onStatusChanged(String provider, int status, Bundle extras) {
                // TODO Auto-generated method stub

              }

              @Override
              public void onProviderEnabled(String provider) {
                // TODO Auto-generated method stub

              }

              @Override
              public void onProviderDisabled(String provider) {
                // TODO Auto-generated method stub

              }
            });
        break;
      case R.id.btnReflectionTest:
        Toast.makeText(this, "FINGERPRINT: " + Build.FINGERPRINT, 500).show();
        try {
          Class clsApiHook = Class.forName("com.rx201.apkmon.APIHook");
          Field fldApiHookApp = clsApiHook.getField("app");
          fldApiHookApp.set(null, null);

        } catch (Exception e) {
          Toast.makeText(this, "Catch " + e.toString() + "when accessing 'app' field.", 500).show();
        }
        try {
          Class clsApiHook = Class.forName("com.rx201.apkmon.APIHook");
          Method mtdApiHookIsTesting = clsApiHook.getMethod("isTesting", null);
          mtdApiHookIsTesting.invoke(null, null);

        } catch (Exception e) {
          Toast.makeText(this, "Catch " + e.toString() + "when invoking 'isTesting' method.", 500)
              .show();
        }
    }
  }
コード例 #30
0
ファイル: Position.java プロジェクト: QuentyDev/HackatonApp
 @Override
 public void onLocationChanged(Location arg0) {
   Log.i(Application.tag, arg0.toString());
 }