Post Top Ad

Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts
September 13, 2014

How to send GPS cordinates from android app to web server

First of all this is my solution for a one of my SE project @ SLIIT. 

Here this solution sends the gps cordinaes of the users location in to the server and the server will be abele to capture the signels and show them in the defined page.

Later we can manipulate these data in the server and display them in a separate place. Ex: a dashboard



LocationGPSTrackerActivity class 

This class checkes wheter the network is availabale and the gps is working corretly in the device. if not it will
display on screen messages based on the results

public class LocationGPSTrackerActivity extends Activity implements LocationListener {

    private final static String CONNECTIVITY = "android.net.conn.CONNECTIVITY_CHANGE";

    private LocationManager locationManager;
    private ConnectivityManager connectivityManager;

    SharedPreferences preferences;
    private EditText edit_url;
    private TextView text_gps_status;
    private TextView text_network_status;
    private ToggleButton button_toggle;
    private TextView text_running_since;

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(LocationGPSTrackerService.NOTIFICATION)) {
                updateServiceStatus();
            }
            if (action.equals(CONNECTIVITY)) {
                updateNetworkStatus();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gpstracker);

        edit_url = (EditText)findViewById(R.id.edit_url);
        text_gps_status = (TextView)findViewById(R.id.text_gps_status);
        text_network_status = (TextView)findViewById(R.id.text_network_status);
        button_toggle = (ToggleButton)findViewById(R.id.button_toggle);
        text_running_since = (TextView)findViewById(R.id.text_running_since);

        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (preferences.contains("URL") && ! preferences.getString("URL", "").equals("")) {
            edit_url.setText(preferences.getString("URL", getString(R.string.hint_url)));
            edit_url.clearFocus();
        } else {
            edit_url.requestFocus();
        }
        edit_url.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                SharedPreferences.Editor editor = preferences.edit();
                editor.putString("URL", s.toString().trim());
                editor.commit();
            }
        });
       
        registerReceiver(receiver, new IntentFilter(LocationGPSTrackerService.NOTIFICATION));
        registerReceiver(receiver, new IntentFilter(LocationGPSTrackerActivity.CONNECTIVITY));
       
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

        int pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));   
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
    }

    @Override
    public void onResume() {
        super.onResume();

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            onProviderEnabled(LocationManager.GPS_PROVIDER);
        } else {
            onProviderDisabled(LocationManager.GPS_PROVIDER);
        }

        updateNetworkStatus();
       
        updateServiceStatus();
    }


private void updateServiceStatus() {
       
        if (LocationGPSTrackerService.isRunning) {
            Toast.makeText(this, getString(R.string.toast_service_running), Toast.LENGTH_SHORT).show();
            button_toggle.setChecked(true);
            text_running_since.setText(getString(R.string.text_running_since) + " "
                    + DateFormat.getDateTimeInstance().format(LocationGPSTrackerService.runningSince.getTime()));
        } else {
            Toast.makeText(this, getString(R.string.toast_service_stopped), Toast.LENGTH_SHORT).show();
            button_toggle.setChecked(false);
            if (preferences.contains("stoppedOn")) {
                long stoppedOn = preferences.getLong("stoppedOn", 0);
                if (stoppedOn > 0) {
                    text_running_since.setText(getString(R.string.text_stopped_on) + " "
                            + DateFormat.getDateTimeInstance().format(new Date(stoppedOn)));
                } else {
                    text_running_since.setText(getText(R.string.text_killed));
                }
            }
        }
    }
   
    private void updateNetworkStatus() {
        NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnectedOrConnecting()) {
            text_network_status.setText(getString(R.string.text_network_status_enabled));
            text_network_status.setTextColor(Color.BLACK);
        } else {
            text_network_status.setText(getString(R.string.text_network_status_disabled));
            text_network_status.setTextColor(Color.RED);
        }
    }
    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        locationManager.removeUpdates(this);
        unregisterReceiver(receiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menue, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent i;
        switch (item.getItemId()) {
        case R.id.menu_settings:
            i = new Intent(this, LocationGPSTrackerPrefs.class);
            startActivity(i);
            break;
        default:
        }
        return super.onOptionsItemSelected(item);
    }

    public void onToggleClicked(View view) {
        Intent intent = new Intent(this, LocationGPSTrackerService.class);
        if (((ToggleButton) view).isChecked()) {
            startService(intent);
        } else {
            stopService(intent);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
    }

    @Override
    public void onProviderDisabled(String provider) {
        text_gps_status.setText(getString(R.string.text_gps_status_disabled));
        text_gps_status.setTextColor(Color.RED);
    }

    @Override
    public void onProviderEnabled(String provider) {
        text_gps_status.setText(getString(R.string.text_gps_status_enabled));
        text_gps_status.setTextColor(Color.BLACK);
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

}

LocationGPSTrackerService

This class is used to display tracking details on the tracker app and to call the LocationGPSTrackerRequest class to open a Http request to the server

public class LocationGPSTrackerService extends IntentService implements LocationListener {

    public static final String NOTIFICATION = "com.example.testmapv2";

    public static boolean isRunning;
    public static Calendar runningSince;
    public Calendar stoppedOn;

    private final static String MY_TAG = "LocationGPSTrackerService";
   
    private SharedPreferences preferences;
    private String urlText;
    private LocationManager locationManager;
    private int pref_gps_updates;
    private long latestUpdate;
    private int pref_max_run_time;

    public LocationGPSTrackerService() {
        super("LocationGPSTrackerService");
    }
   
    @Override
    public void onCreate() {
        super.onCreate();       
        Log.d(MY_TAG, "in onCreate, init GPS stuff");
       
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            onProviderEnabled(LocationManager.GPS_PROVIDER);
        } else {
            onProviderDisabled(LocationManager.GPS_PROVIDER);
        }
       
        preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong("stoppedOn", 0);
        editor.commit();
        pref_gps_updates = Integer.parseInt(preferences.getString("pref_gps_updates", "30"));
        pref_max_run_time = Integer.parseInt(preferences.getString("pref_max_run_time", "24"));
        urlText = preferences.getString("URL", "");
        if (urlText.contains("?")) {
            urlText = urlText + "&";
        } else {
            urlText = urlText + "?";
        }
       
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, pref_gps_updates * 1000, 1, this);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(MY_TAG, "in onHandleIntent, run for maximum time set in preferences");
        new LocationGPSTrackerRequest().execute(urlText + "tracker=start");
               
        isRunning = true;
        runningSince = Calendar.getInstance();
        Intent i = new Intent(NOTIFICATION);
        sendBroadcast(i);
   
        Notification notification = new Notification(R.drawable.ic_launcher, getText(R.string.toast_service_running), System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, LocationGPSTrackerActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(this, getText(R.string.app_name), getText(R.string.toast_service_running), pendingIntent);
        startForeground(R.id.logo, notification);
               
    }
   
    @Override
    public void onDestroy() {
        // destroy when user clicked the stop button or maximum run time has been reached
        Log.d(MY_TAG, "in onDestroy, stop listening to the GPS");
        new LocationGPSTrackerRequest().execute(urlText + "tracker=stop");
       
        locationManager.removeUpdates(this);
       
        isRunning = false;
        stoppedOn = Calendar.getInstance();
       
        SharedPreferences.Editor editor = preferences.edit();
        editor.putLong("stoppedOn", stoppedOn.getTimeInMillis());
        editor.commit();
       
        Intent intent = new Intent(NOTIFICATION);
        sendBroadcast(intent);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(MY_TAG, "in onLocationChanged, latestUpdate == " + latestUpdate);
       
        if ((System.currentTimeMillis() - latestUpdate) < pref_gps_updates*1000) {
            return;
        } else {
            latestUpdate = System.currentTimeMillis();
        }
       
        new LocationGPSTrackerRequest().execute(urlText + "lat=" + location.getLatitude() + "&lon=" + location.getLongitude());
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

 Sending Http request to the server

 public class LocationGPSTrackerRequest extends AsyncTask<String, Void, Void> {
    private final static String MY_TAG = "LocationGPSTrackerRequest";
  
    protected Void doInBackground(String... urlText) {
        try {
            URL url = new URL(urlText[0]);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 );
            conn.setConnectTimeout(15000 );
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            Log.d(MY_TAG, "HTTP request done : " + response);
          
        } catch (Exception e) {
            // whrn network down
            Log.d(MY_TAG, "HTTP request failed");
        }
        return null;
    }
}







July 22, 2014

Android Google Maps Chapter 2

This is the second chapter about creating a android google map with google map api v2




In the previous chapter i have explained about main layout file and the manifest file to load a map inside the emulator. Now this chapter will explain about the main activity of the map.

public class MainActivity extends FragmentActivity {
   
    private static final int GPS_ERRORDIALOG_REQUEST = 9001;
    private GoogleMap mMap;
    private static final double SEATTLE_LAT = 6.939378, // if you want to enable satellite views
            SEATTLE_LNG = 79.840336;
        //    SYDNEY_LAT =  ;
        //    SYDNEY_LNG = 151.20699,
        //    NEWYORK_LAT = 40.714353,
        //    NEWYORK_LNG = -74.005973;
    private static final float DEFAULTZOOM = 7; // to set the zoom level

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        if (servicesOK()) {
            setContentView(R.layout.activity_main);
       
            if (initMap()) {
                Toast.makeText(this, "Ready to map!", Toast.LENGTH_SHORT).show();
            //    gotoLocation(SEATTLE_LAT, SEATTLE_LNG,DEFAULTZOOM);
                mMap.setMyLocationEnabled(true); 
            }
            else {
                Toast.makeText(this, "Map not available!", Toast.LENGTH_SHORT).show();
            }
        }
        else {
            setContentView(R.layout.activity_main);
        }
             mMap=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
//        if(mMap!=null)
//            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
       
    }

    private void hideSoftKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }
   
    public void geoLocate(View v){ //Geocoder may return IOException
        hideSoftKeyboard(v);

        EditText et = (EditText) findViewById(R.id.editText1);
        String location = et.getText().toString();

        try {
            Geocoder gc = new Geocoder(this); //    when you search you will get back a java list
            List<Address> list = gc.getFromLocationName(location, 1); // Address is Android thing
            //getFromLocationName is a method of Geocoder class
            // i only want a single  item
            Address add = list.get(0); // give me the first and only item in the list
            String locality = add.getLocality();
           
            Toast.makeText(this, locality, Toast.LENGTH_LONG).show(); // To check whether Geocoder  is working or not
            //Toast.makeText(this, locality, Toast.LENGTH_LONG).show();

/*    double lat = add.getLatitude();
            double lng = add.getLongitude();

            gotoLocation(lat, lng, DEFAULTZOOM);
*/
        } catch (IOException e) {

            Log.d("EXCEPTION:", "Failed to do something: " + e.getMessage());
            Log.d("EXCEPTION: " + method,  message);
        }
    }
   
    private void gotoLocation(double lat, double lng,float zoom) {
        LatLng ll = new LatLng(lat, lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        mMap.moveCamera(update);
       
    }
   
    public boolean servicesOK() {
        int isAvailable = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
       
        if (isAvailable == ConnectionResult.SUCCESS) {
            return true;
        }
        else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable, this, GPS_ERRORDIALOG_REQUEST);
            dialog.show();
        }
        else {
            Toast.makeText(this, "Can't connect to Google Play services", Toast.LENGTH_SHORT).show();
        }
        return false;
    }
   
    private boolean initMap() {
        if (mMap == null) {
            SupportMapFragment mapFrag =
                    (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mMap = mapFrag.getMap();
        }
        return (mMap != null);
    }
   

    private void messageBox(String method, String message)
    {
        Log.d("EXCEPTION: " + method,  message);

        AlertDialog.Builder messageBox = new AlertDialog.Builder(this);
        messageBox.setTitle(method);
        messageBox.setMessage(message);
        messageBox.setCancelable(false);
        messageBox.setNeutralButton("OK", null);
        messageBox.show();
    }

// if you want to load different map versions according to user selection

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.mapTypeNone:
            mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
            break;
        case R.id.mapTypeNormal:
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            break;
        case R.id.mapTypeSatellite:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
            break;
        case R.id.mapTypeHybrid:
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            break;
        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }
}

Most probably when you run this code you will not see any output in the default android emulator and it will ask to update google play services. The simple answer for this problem is to try and run your map using a mobile phone. otherwise you can use install the google play services into your android emulator which shoud be done in a simple work around.
May 29, 2014

Android 3rd Tutorial: Layout Options FILL_PARENT, MATCH_PARENT , WRAP_CONTENT


• FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the View wants to be as big as its parent (minus padding)
•WRAP_CONTENT, which means that the View wants to be just big enough to enclose its content (plus padding)
Either attribute can be applied to View's (visual control) horizontal or vertical size. It's used to set a View or Layouts size based on either it's contents or the size of it's parent layout rather than explicitly specifying a dimension.

fill_parent
(deprecated and renamed MATCH_PARENT in API Level 8 and higher)
Setting the layout of a widget to fill parent will force it to expand to take up as much space as is available within the layout element it's been placed in. It's roughly equivalent of setting the dock style of a Windows Form Control to Fill.
Setting a top level layout or control to fill parent will force it to take up the whole screen.

wrap_content
Setting a View's size to wrap content will force it to expand only far enough to contain the values (or child controls) it contains. For controls -- like text boxes (TextView) or images (ImageView) -- this will wrap the text or image being shown. For layout elements it will resize the layout to fit the controls / layouts added as its children.
It's roughly the equivalent of setting a Windows Form Control's Auto size property to True.

Online Documentation
There's some details in the Android code documentation here


May 29, 2014

Styling Android: Online Tools

As mobile developers Styling Android Application is the biggest pain. But thanks to this Online tool
you can reduce your hard times.

Try it,


Android Asset Studio

Icon generators — Make icons for your app

Icon generators allow you to quickly and easily generate icons from existing source images, clipart, or text.
May 24, 2014

Android : Difference between px, dp, dip and sp

Most of the newbie's are bit complicated about how to handle images and font sizes in android, because
there are several terms relating to them. Today i hoped to discuss some of them. Here, i'll share most of the important information which i found referring developers site and others.    

  • px is one pixel.
  • sp is scale-independent pixels.
  • dip is Density-independent pixels.
You would use
  • sp for font sizes
  • dip for everything else.
dip==dp
px
Pixels - corresponds to actual pixels on the screen.

in
Inches - based on the physical size of the screen.

mm
Millimeters - based on the physical size of the screen.

pt
Points - 1/72 of an inch based on the physical size of the screen.

dp
Density-independent Pixels - an abstract unit that is based on the physical density of the screen. These units are relative to a 160 dpi screen, so one dp is one pixel on a 160 dpi screen. The ratio of dp-to-pixel will change with the screen density, but not necessarily in direct proportion. Note: The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".

sp
Scale-independent Pixels - this is like the dp unit, but it is also scaled by the user's font size preference. It is recommend you use this unit when specifying font sizes, so they will be adjusted for both the screen density and user's preference.


More Description.

Screen size : Actual physical size, measured as the screen's diagonal. For simplicity, Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra large.

Screen density : The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen. For simplicity, Android groups all actual screen densities into four generalized densities: low, medium, high, and extra high.

Orientation : The orientation of the screen from the user's point of view. This is either landscape or portrait, meaning that the screen's aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation can change at runtime when the user rotates the device.

Resolution : The total number of physical pixels on a screen. When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.

Density-independent pixel (dp) :A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.



 

My Instagram