Java tutorial
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fr.matthiasbosc.translucentmap; import android.app.ActionBar; import android.app.ActivityManager; import android.app.SearchManager; import android.content.Intent; import android.content.res.Configuration; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.location.Criteria; import android.location.Location; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.support.v4.app.FragmentActivity; import android.support.v4.app.LoaderManager.LoaderCallbacks; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.SupportMapFragment; import java.lang.String; public class MainActivity extends FragmentActivity implements LoaderCallbacks<Cursor> { private static final String MAP_TYPE = "MAP_TYPE_NORMAL"; private int mapType; double latitude, longitude; public boolean hasTranslucentBars = false; public boolean RamDeviceStatus; ActionBar mActionBar; LocationManager mLocationManager; Location mLocation; GoogleMap mMap; TypedValue mTypedValue; LatLng latLng; Window mWindow; private static final String PREFERENCES = "PREF"; private SharedPreferences settings; private SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getWindow().requestFeature(Window.FEATURE_ACTION_BAR_OVERLAY); super.onCreate(savedInstanceState); settings = getSharedPreferences(PREFERENCES, 0); editor = settings.edit(); setContentView(R.layout.activity_main); if (isGMSInstalled() == ConnectionResult.SUCCESS) { if ((Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) && (!isLowRamDevice())) { mWindow = getWindow(); mWindow.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); mWindow.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); hasTranslucentBars = true; firstRun(); } mActionBar = getActionBar(); if (mActionBar != null) { mActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3F000000"))); mActionBar.setStackedBackgroundDrawable(new ColorDrawable(Color.parseColor("#3F000000"))); getMap(); } } else { FrameLayout fl = (FrameLayout) findViewById(R.id.map); fl.setPadding(0, getActionBarHeight(), 0, 0); } } public void firstRun() { boolean firstrun = getSharedPreferences(PREFERENCES, MODE_PRIVATE).getBoolean("fistrun", true); if (firstrun) { getSharedPreferences(PREFERENCES, MODE_PRIVATE).edit().putInt("actionbar_height", getActionBarHeight()) .putInt("statusbar_height", getStatusBarHeight()).putInt("navbar_height", getNavBarHeight()) .putBoolean("firstrun", false).commit(); } } public int isGMSInstalled() { int GmsStatus; GmsStatus = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); return GmsStatus; } public int getStatusBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } public int getNavBarHeight() { int result = 0; int resourceId = getResources().getIdentifier("navigation_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } public int getActionBarHeight() { int result = 0; mTypedValue = new TypedValue(); if (getTheme() != null) { if (getTheme().resolveAttribute(android.R.attr.actionBarSize, mTypedValue, true)) { result = TypedValue.complexToDimensionPixelSize(mTypedValue.data, getResources().getDisplayMetrics()); } } return result; } public boolean isLowRamDevice() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); RamDeviceStatus = activityManager.isLowRamDevice(); } return RamDeviceStatus; } public boolean deviceType() { return getResources().getBoolean(R.bool.isTablet); } public int actionBarHeight() { return settings.getInt("actionbar_height", 45); } public int statusBarHeight() { return settings.getInt("statusbar_height", 24); } public int navBarHeight() { return settings.getInt("navbar_height", 45); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); setMapPadding(); } private void handleIntent(Intent intent) { if (intent.getAction().equals(Intent.ACTION_SEARCH)) { doSearch(intent.getStringExtra(SearchManager.QUERY)); } else if (intent.getAction().equals(Intent.ACTION_VIEW)) { getPlace(intent.getStringExtra(SearchManager.EXTRA_DATA_KEY)); } } public void onResume() { super.onResume(); if (isGMSInstalled() == ConnectionResult.SUCCESS) { getMap(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case R.id.action_search: onSearchRequested(); break; case R.id.action_settings: Intent intent = new Intent(this, SetPrefActivity.class); startActivity(intent); break; } return super.onMenuItemSelected(featureId, item); } public void getMap() { SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); String pref_map_type = SP.getString("map_type", MAP_TYPE); if ("MAP_TYPE_NORMAL".equals(pref_map_type)) { mapType = GoogleMap.MAP_TYPE_NORMAL; } else if ("MAP_TYPE_SATELLITE".equals(pref_map_type)) { mapType = GoogleMap.MAP_TYPE_SATELLITE; } else if ("MAP_TYPE_HYBRID".equals(pref_map_type)) { mapType = GoogleMap.MAP_TYPE_HYBRID; } else if ("MAP_TYPE_TERRAIN".equals(pref_map_type)) { mapType = GoogleMap.MAP_TYPE_TERRAIN; } mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = mLocationManager.getBestProvider(criteria, true); mLocation = mLocationManager.getLastKnownLocation(provider); if (mLocation == null) { Toast.makeText(this, R.string.location_unavailable, Toast.LENGTH_SHORT).show(); latitude = 45.759723; longitude = 4.842223; latLng = new LatLng(latitude, longitude); } else { latitude = mLocation.getLatitude(); longitude = mLocation.getLongitude(); latLng = new LatLng(latitude, longitude); } if (mMap == null) { SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); mMap = fragment.getMap(); mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); mMap.animateCamera(CameraUpdateFactory.zoomTo(13)); mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Ma position")); } mMap.setMapType(mapType); setMapPadding(); mMap.setMyLocationEnabled(true); mMap.setBuildingsEnabled(true); mMap.getUiSettings().setCompassEnabled(true); mMap.setTrafficEnabled(SP.getBoolean("traffic_layout", false)); handleIntent(getIntent()); } public void setMapPadding() { int topPadding = actionBarHeight() + statusBarHeight(); int orientation = this.getResources().getConfiguration().orientation; if ((orientation == Configuration.ORIENTATION_PORTRAIT) && (hasTranslucentBars)) { mMap.setPadding(0, topPadding, 0, navBarHeight()); } else if ((orientation == Configuration.ORIENTATION_LANDSCAPE && (deviceType()) && (hasTranslucentBars))) { mMap.setPadding(0, topPadding, 0, navBarHeight()); } else if ((orientation == Configuration.ORIENTATION_LANDSCAPE && (!deviceType()) && (hasTranslucentBars))) { mMap.setPadding(0, topPadding, navBarHeight(), 0); } else if ((orientation == Configuration.ORIENTATION_PORTRAIT && (!hasTranslucentBars))) { mMap.setPadding(0, actionBarHeight(), 0, 0); } else if ((orientation == Configuration.ORIENTATION_LANDSCAPE && (!hasTranslucentBars))) { mMap.setPadding(0, actionBarHeight(), 0, 0); } } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); setIntent(intent); handleIntent(intent); } private void doSearch(String query) { Bundle data = new Bundle(); data.putString("query", query); getSupportLoaderManager().restartLoader(0, data, this); } private void getPlace(String query) { Bundle data = new Bundle(); data.putString("query", query); getSupportLoaderManager().restartLoader(1, data, this); } @Override public Loader<Cursor> onCreateLoader(int arg0, Bundle query) { CursorLoader cLoader = null; if (arg0 == 0) { cLoader = new CursorLoader(getBaseContext(), PlaceProvider.SEARCH_URI, null, null, new String[] { query.getString("query") }, null); } else if (arg0 == 1) { cLoader = new CursorLoader(getBaseContext(), PlaceProvider.DETAILS_URI, null, null, new String[] { query.getString("query") }, null); } return cLoader; } @Override public void onLoadFinished(Loader<Cursor> arg0, Cursor c) { showLocations(c); } @Override public void onLoaderReset(Loader<Cursor> arg0) { // TODO Auto-generated method stub } private void showLocations(Cursor c) { MarkerOptions markerOptions = null; LatLng position = null; mMap.clear(); while (c.moveToNext()) { markerOptions = new MarkerOptions(); position = new LatLng(Double.parseDouble(c.getString(1)), Double.parseDouble(c.getString(2))); markerOptions.position(position); markerOptions.title(c.getString(0)); mMap.addMarker(markerOptions); } if (position != null) { mMap.moveCamera(CameraUpdateFactory.newLatLng(position)); mMap.animateCamera(CameraUpdateFactory.zoomTo(13)); } } }