Android Open Source - mitlocate Main Activity






From Project

Back to project page mitlocate.

License

The source code is released under:

MIT License

If you think the Android project mitlocate 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 edu.mit.locate;
/*from  w ww  .jav  a 2  s  .  c  o m*/
import java.util.Arrays;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import edu.mit.locate.tabs.TabPageIndicator;
import edu.mit.locate.tabs.TabPagerAdapter;

public class MainActivity extends FragmentActivity implements OnClickListener {
  private WifiManager wifi;
  private TextView status;
  private SharedPreferences prefs;
  private String deviceID, fullname, email;

  private Editor editor;

  Intent MITLocationServiceIntent, MITLocationReporterIntent;
  private AlarmManager am;
  private LocationManager lm;
  private PendingIntent pi;

  private ArrayAdapter<String> autocompleteAdapter;
  private ViewPager mPager;
  private PagerAdapter mPagerAdapter;
  private final String TAG = "MainActivity";

  // Service variables

  /* Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    /**
     * GET PREFERENCES
     */
    prefs = getSharedPreferences("MITLOCATE", 0);
    editor = prefs.edit();
    deviceID = prefs.getString("DeviceID", null);
    fullname = prefs.getString("FullName", null);
    email = prefs.getString("Email", null);

    //overridePendingTransition(R.anim.fadein, R.anim.fadeout);
    setContentView(R.layout.activity_main);

    View mEasterEgg = (View) findViewById(R.id.MIT_I2);
    mEasterEgg.setOnLongClickListener(new OnLongClickListener(){
      @Override
      public boolean onLongClick(View v) {
        Intent editorActivityIntent = new Intent(MainActivity.this, APEditorActivity.class);
        editorActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(editorActivityIntent);
        return true;
      }
    });

    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new TabPagerAdapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);
    TabPageIndicator tabIndicator = (TabPageIndicator) findViewById(R.id.titles);
    tabIndicator.setViewPager(mPager, 0);
    tabIndicator.setOnPageChangeListener(new OnPageChangeListener() {
      @Override
      public void onPageScrollStateChanged(int arg0) {}

      @Override
      public void onPageScrolled(int arg0, float arg1, int arg2) {}

      @Override
      public void onPageSelected(int arg0) {
        //                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //                if(arg0 == 0) imm.showSoftInput(findViewById(R.id.searchBar), 0);
        //                else
        //                    imm.hideSoftInputFromWindow(findViewById(android.R.id.content).getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
      }
    });

    // Set up AlarmManager and LocationManager

    am = (AlarmManager) getSystemService(ALARM_SERVICE);
    lm = (LocationManager) getSystemService(LOCATION_SERVICE);

    MITLocationServiceIntent = new Intent(this, MITLocationService.class);
    pi = PendingIntent.getService(this, 1, MITLocationServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    MITLocationReporterIntent = new Intent(this, MITLocationService.class);
    MITLocationReporterIntent.putExtra("add", true);

    /**
     * INITIALIZE UI VARIABLES
     */
    // TODO:Move to settings fragment/view:
    // authenticatedAs = (TextView) findViewById(R.id.authenticatedAs);
    status = (TextView) findViewById(R.id.status);
    // locText = (TextView) findViewById(R.id.locText);

    /**
     * SET UP FONTS
     */
    Typeface lumos = Typeface.createFromAsset(getAssets(), "lumos.ttf");
    Typeface quint = Typeface.createFromAsset(getAssets(), "Quintessential.ttf");
    // status.setTypeface(lumos);

    status.setText("Locating...");
  }

  // Processes the results from MITLocationService (adds location to the UI)
  private BroadcastReceiver LocationServiceBR = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      final String response = intent.getStringExtra("response");
      if(response!=null){
        Log.w(TAG,response);
        try{
          JSONObject responseObject = new JSONObject(response);
          int statusCode = responseObject.getInt("status");
          if(statusCode==0){
            status.setText(Html.fromHtml(responseObject.optString("location")));
            editor.putInt("SharingMode", responseObject.optInt("sharing"));
          }else if(statusCode==1){
            editor.putInt("Authorization", -1);
            editor.commit();
          }else if(statusCode==2){
            editor.putInt("Authorization", 0);
            editor.commit();
          }
        }catch(JSONException pe){
          Log.e(TAG,"JSON parse failure");
        }
        disableIfNecessary();
      }
    }
  };

  // Processes the results from MITLocationReporter (send toasts)
  private BroadcastReceiver LocationReporterBR = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      String response = intent.getStringExtra("response");
      if(response.equals("_DISABLED")){
        editor.putInt("Authorization", -1);
        editor.commit();
      }else if(response.equals("_DEACT")){
        editor.putInt("Authorization", 0);
        editor.commit();
      }else{
        if(response.startsWith("OK")) Toast.makeText(getApplicationContext(), "Location data received. Thanks!", Toast.LENGTH_LONG).show();
        else
          Toast.makeText(getApplicationContext(), "Sending location data failed!", Toast.LENGTH_LONG).show();
      }
      disableIfNecessary();
    }
  };

  private boolean disableIfNecessary() {
    if(prefs.getInt("Authorization", 0) < 1){
      am.cancel(pi);
      Intent i = new Intent(this, LoginActivity.class);
      i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      startActivity(i);
      finish();
      return false;
    }else
      return true;
  }

  @Override
  public void onResume() {
    super.onResume();
    pi = PendingIntent.getService(this, 1, MITLocationServiceIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 100, 8 * 1000, pi);
    // startService(MITLocationServiceIntent);
    lm.removeUpdates(pi);
    LocalBroadcastManager.getInstance(this).registerReceiver(LocationServiceBR, new IntentFilter(MITLocationService.BROADCAST_LOCATOR));
    LocalBroadcastManager.getInstance(this).registerReceiver(LocationReporterBR, new IntentFilter(MITLocationService.BROADCAST_ADDLOCATION));

    disableIfNecessary();
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    if(!wifi.isWifiEnabled()){
      Toast.makeText(this, "This app requires WiFi to locate you.", Toast.LENGTH_LONG).show();
      //wifi.setWifiEnabled(true);
      new AlertDialog.Builder(this)
      .setMessage("No Internet Connection")
      .setTitle("Error").setPositiveButton("OK", null).show();
    }
  }

  @Override
  public void onPause() {
    super.onPause();
    disableIfNecessary();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(LocationReporterBR);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(LocationServiceBR);
    am.cancel(pi);
    if(prefs.getInt("SharingMode", 1) < 3){
      lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 30, 5, pi);
    }
  }

  @Override
  public void onClick(View v) {}

  // public void onConfigurationChanged(){
  //
  // }

  //    @Override
  //    public boolean onSearchRequested() {
  //        mPager.setCurrentItem(0, true);
  //        return super.onSearchRequested();
  //    }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_options, menu);
    return true;
  }

  private static final String MIT_BUILDINGS[] = {"Media Lab","Simmons Hall","Senior House","Stata Center","W20","Student Center","Baker House","Maseeh Hall"};

//  final View addLocationView = LayoutInflater.from(this).inflate(R.layout.dialog_add_location, null);
//  AlertDialog.Builder adb = new AlertDialog.Builder(this).setView(addLocationView);
//
//  AutoCompleteTextView buildingAutocomplete = (AutoCompleteTextView) addLocationView.findViewById(R.id.building_autocomplete);
//  String lastBuilding = prefs.getString("LastBuilding", null);
//  if(lastBuilding != null){
//    buildingAutocomplete.setText(lastBuilding);
//    ((EditText) addLocationView.findViewById(R.id.description)).requestFocus();
//  }
//  autocompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, MIT_BUILDINGS);
//  buildingAutocomplete.setAdapter(autocompleteAdapter);
//
//  // Spinner buildingSpinner = (Spinner)
//  // addLocationView.findViewById(R.id.building);
//  // List<String> list = new ArrayList<String>();
//  // for(String bldg: MIT_BUILDINGS){
//  // list.add(bldg);
//  // }
//  // ArrayAdapter<String> dataAdapter = new
//  // ArrayAdapter<String>(this,
//  // android.R.layout.simple_spinner_item, list);
//  // dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//  // buildingSpinner.setAdapter(dataAdapter);
//
//  adb.setIcon(android.R.drawable.ic_input_add).setTitle("Add Location").setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
//    @Override
//    public void onClick(DialogInterface dialog, int id) {
//      // User cancelled the dialog
//    }
//
//  }).setPositiveButton("Add", new DialogInterface.OnClickListener() {
//    @Override
//    public void onClick(DialogInterface dialog, int id) {
//      // RequestParams params = new RequestParams();
//      String building = ((EditText) ((Dialog) dialog).findViewById(R.id.building_autocomplete)).getText().toString();
//      String desc = ((EditText) ((Dialog) dialog).findViewById(R.id.description)).getText().toString();
//      if(!desc.equals("")){
//        if(Arrays.asList(MIT_BUILDINGS).contains(building)){
//          // params.put("UUID",installID);
//          // params.put("building",building);
//          // params.put("location",location);
//          editor.putString("LastBuilding", building);
//          editor.commit();
//          MITLocationReporterIntent.putExtra("building", building);
//          MITLocationReporterIntent.putExtra("desc", desc);
//          startService(MITLocationReporterIntent);
//          // MITHttpsClient.post("add/", params, new
//          // AsyncHttpResponseHandler() {
//          // @Override
//          // public void onSuccess(String response) {
//          // if(response.equals("OK")){
//          // Toast.makeText(getApplicationContext(),
//          // "Collecting data...",
//          // Toast.LENGTH_LONG).show();
//          // Toast.makeText(getApplicationContext(),
//          // "Location submitted!",
//          // Toast.LENGTH_SHORT).show();
//          // } else {
//          // Log.e(TAG,"Unmatched HTTP response: "+response);
//          // }
//          // }
//          //
//          // @Override
//          // public void onFailure(Throwable e, String
//          // response) {
//          // Toast.makeText(getApplicationContext(),
//          // "Sending failed!",
//          // Toast.LENGTH_SHORT).show();
//          // }
//          // });
//        }else{
//          Toast.makeText(getApplicationContext(), "Unknown building.", Toast.LENGTH_SHORT).show();
//        }
//      }else{
//        Toast.makeText(getApplicationContext(), "Describe the location.", Toast.LENGTH_SHORT).show();
//      }
//    }
//  }).create().show();
}




Java Source Code List

edu.mit.locate.APEditorActivity.java
edu.mit.locate.BootLocationService.java
edu.mit.locate.LoginActivity.java
edu.mit.locate.MITHttpsClient.java
edu.mit.locate.MITLocationService.java
edu.mit.locate.MainActivity.java
edu.mit.locate.alerts.Alert.java
edu.mit.locate.alerts.AlertsListAdapter.java
edu.mit.locate.alerts.AlertsTab.java
edu.mit.locate.apeditor.APListAdapter.java
edu.mit.locate.apeditor.APScanResult.java
edu.mit.locate.friends.FriendActivity.java
edu.mit.locate.friends.Friend.java
edu.mit.locate.friends.FriendsListAdapter.java
edu.mit.locate.friends.FriendsTab.java
edu.mit.locate.tabs.IconPagerAdapter.java
edu.mit.locate.tabs.IcsLinearLayout.java
edu.mit.locate.tabs.NavigationTab.java
edu.mit.locate.tabs.PageIndicator.java
edu.mit.locate.tabs.SearchTab.java
edu.mit.locate.tabs.SettingsTab.java
edu.mit.locate.tabs.TabPageIndicator.java
edu.mit.locate.tabs.TabPagerAdapter.java