Android Open Source - project2 Location Map Activity






From Project

Back to project page project2.

License

The source code is released under:

MIT License

If you think the Android project project2 listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package team2.scdm;
/*  w  w  w. ja va  2  s  .c  om*/
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class LocationMapActivity extends FragmentActivity implements SensorEventListener {

  private GoogleMap mMap;
  private LocationListener locationlistener; 
  private double lat; 
  private double lon; 
  private boolean initialSetupLoc; 
  private boolean initialSetupAcc; 
  private boolean initialSetupMove; 
  private boolean initialSetupCreate; 
  private double lastx, lasty, lastz;
  private SensorManager sensormanager;
  private Sensor acc;
  private final float NOISE = (float) 2.0;
  
  private Timer moveNPCs;
  private Timer createNPCs;
  
  private ArrayList<NPC> ppl; // ppl is easier to type than NPCs

  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    initialSetupLoc = true; 
    initialSetupAcc = true; 
    initialSetupMove = true; 
    initialSetupCreate = true; 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.location_map);
    
    createNPCs = new Timer();
    createNPCs.schedule(new TimerTask() {      
      @Override
      public void run() {
        createNPCs();
      }
      
    }, 0, 500); // TODO replace number with user's desired enemy frequency
    
    moveNPCs = new Timer();
    moveNPCs.schedule(new TimerTask() {      
      @Override
      public void run() {
        moveNPCs();
      }
      
    }, 0, 400); 

    mMap = ((SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map)).getMap();
    mMap.setMyLocationEnabled(false);
    LocationManager locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
    
    locationlistener = new LocationListener(){
      @Override
      public void onLocationChanged(Location location) {
        updateLocation(location); 
      }

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

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

      @Override
      public void onStatusChanged(String provider, int status,
          Bundle extras) {
        // TODO Auto-generated method stub
        
      }
    }; 
    
    String locationProvider = LocationManager.NETWORK_PROVIDER; 
    if (locationmanager != null) {
      updateLocation(locationmanager.getLastKnownLocation(locationProvider)); 
      
      locationmanager.requestLocationUpdates(locationProvider, 0, 0, locationlistener); 
      locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistener); // More precise, takes more battery
      
    }
    
    sensormanager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); // ??? what is getSystemService? 
    acc = sensormanager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); // What are other options here? 
    sensormanager.registerListener(this, acc, SensorManager.SENSOR_DELAY_NORMAL); // registerListener? 

  }
  
  private void updateLocation(Location loc) {
    if (loc != null) {
      lat = loc.getLatitude();
      lon = loc.getLongitude(); 
      BitmapDescriptor bdPlayer = BitmapDescriptorFactory.fromResource(R.drawable.player); 
      mMap.clear(); 
      mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
          .icon(bdPlayer)
          .anchor((float) 0.5, (float) 0.5));
      if (initialSetupLoc) { // If this is the initial setup
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), (float) 18)); 
        moveNPCs(); 
        initialSetupLoc = false; 
      } else {
        moveNPCs(); 
        mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(lat, lon))); 
      }
    }
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.map_location, menu);
    return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      // Handle item selection
      switch (item.getItemId()) {
          case R.id.action_menu:
            startActivity(new Intent(this, MenuActivity.class)); ;
              return true;
          case R.id.action_inventory:
          startActivity(new Intent(this, InventoryActivity.class)); 
              return true;
          case R.id.action_settings:
          startActivity(new Intent(this, SettingsActivity.class)); 
              return true;
          default:
              return super.onOptionsItemSelected(item);
      }
  }
  
  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
    // can be ignored
  }
  
  @Override
  public void onSensorChanged(SensorEvent event) {
//    ImageView action = (ImageView) findViewById(R.id.action); 
    double x = event.values[0]; 
    double y = event.values[1]; 
    double z = event.values[2]; 
    if (initialSetupAcc) {
      lastx = x; 
      lasty = y; 
      lastz = z; 
      initialSetupAcc = false; 
    } else {
      double diffx = lastx - x; 
      double diffy = lasty - y; 
      double diffz = lastz - z; 
      double magnitude = Math.sqrt(Math.pow(diffx, 2) + Math.pow(diffy, 2)
          + Math.pow(diffz, 2)); 
      if (magnitude > NOISE) {
        // This shouldn't do anything right now
        
      } else {
        
      }
    }
  }
  

  
  private void createNPCs() {
    this.runOnUiThread(createNPCs_tick);
  }


  private Runnable createNPCs_tick = new Runnable() {
    public void run() {
      Random rand = new Random(); 
      if (initialSetupCreate) {
        ppl = new ArrayList<NPC>(); 
        initialSetupCreate = false; 
      }
      int tossup = rand.nextInt((int) Math.pow((ppl.size() + 2), 3) * 2); // TODO fine tune & make dependent on user settings
      if (tossup == 0 && ppl.size() < 10) { // TODO replace number with user's desired enemy frequency
        ppl.add(new Enemy(new LatLng(lat, lon))); 
      }
    }
  };
  
  
  private void moveNPCs()
  {
    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(moveNPCs_tick);
  }


  private Runnable moveNPCs_tick = new Runnable() {
    public void run() {
    
      //This method runs in the same thread as the UI.             
      
      //Do something to the UI thread here
      
      if (initialSetupMove) {
        createNPCs(); 
        initialSetupMove = false; 
      }
      Random rand = new Random(); 
      int tossup = rand.nextInt(4); // TODO fine tune & make dependent on user settings
      BitmapDescriptor bdPlayer = BitmapDescriptorFactory.fromResource(R.drawable.player); 
      mMap.clear(); 
      mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
          .icon(bdPlayer)
          .anchor((float) 0.5, (float) 0.5));
      for (int i = 0; i < ppl.size(); i++) {
        if (tossup == 0) { // There's a random chance of each enemy moving
          ppl.get(i).move(new LatLng(lat, lon)); 
        }
        mMap.addMarker(new MarkerOptions().position(ppl.get(i).getPosition())
            .icon(BitmapDescriptorFactory.fromResource(ppl.get(i).getType()))
            .anchor((float) 0.5, (float) 0.5)); 
        if (ppl.get(i).action(new LatLng(lat, lon))) {
          actionWithNPC(i); 
        } else if (!ppl.get(i).withinMaxBounds(new LatLng(lat, lon))) {
          ppl.remove(i); 
          Context context = getApplicationContext();
          CharSequence text = "Removed faraway enemy!";
          int duration = Toast.LENGTH_SHORT;

          Toast toast = Toast.makeText(context, text, duration);
          toast.show();
        }
      }
    
    }
  };
  
  private void actionWithNPC(int NPC) {
    if (ppl.get(NPC).getClass() == Enemy.class) {
      battle(NPC); 
    } else {
      grab(NPC); 
    }
  }
  
  private void battle(int enemy) {
    Context context = getApplicationContext();
    CharSequence text = "Time to battle!";
    int duration = Toast.LENGTH_SHORT;
    
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
    
    vibrate(); 
    
    // TODO: startActivity(new Intent(this, BattleActivity.class)); 
    
    ppl.remove(enemy); // TODO: Remove this line when real fighting is implemented
  }
  
  private void grab(int folk) {
    // User grabs a Folk; adds to their stats
    Context context = getApplicationContext();
    CharSequence text = "You saved a carnie!";
    int duration = Toast.LENGTH_SHORT;
    
    Toast toast = Toast.makeText(context, text, duration);
    toast.show();
    
    vibrate(); 
    
    // TODO: Add to user's stats here
    
    ppl.remove(folk); 
  }
  
  private void vibrate() {
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
    v.vibrate(100); 
  }
  
}




Java Source Code List

team2.scdm.AboutActivity.java
team2.scdm.Armor.java
team2.scdm.Assets.java
team2.scdm.Audio.java
team2.scdm.BattleActivity.java
team2.scdm.Enemy.java
team2.scdm.Folk.java
team2.scdm.GameAudio.java
team2.scdm.GameMusic.java
team2.scdm.GameOverActivity.java
team2.scdm.GameSound.java
team2.scdm.GestureListener.java
team2.scdm.Intro1.java
team2.scdm.Intro2.java
team2.scdm.Intro3.java
team2.scdm.Intro4.java
team2.scdm.Intro5.java
team2.scdm.Intro6.java
team2.scdm.InventoryActivity.java
team2.scdm.Item.java
team2.scdm.LocationMapActivity.java
team2.scdm.Media.java
team2.scdm.MenuActivity.java
team2.scdm.NPC.java
team2.scdm.NameActivity.java
team2.scdm.Player.java
team2.scdm.SettingsActivity.java
team2.scdm.Sound.java
team2.scdm.TitleActivity.java
team2.scdm.Weapon.java