<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Android on Abdullah Diab&#39;s Blog</title>
    <link>https://mpcabd.xyz/tags/android/</link>
    <description>Recent content in Android on Abdullah Diab&#39;s Blog</description>
    <generator>Hugo</generator>
    <language>en-us</language>
    <lastBuildDate>Thu, 15 Dec 2011 18:29:51 +0000</lastBuildDate>
    <atom:link href="https://mpcabd.xyz/tags/android/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>Android Map View With Pan &amp; Zoom Events</title>
      <link>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</link>
      <pubDate>Thu, 15 Dec 2011 18:29:51 +0000</pubDate>
      <guid>https://mpcabd.xyz/android-map-view-with-pan-zoom-events/</guid>
      <description>&lt;p&gt;I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a &lt;a href=&#34;http://developer.android.com/resources/tutorials/views/hello-mapview.html&#34;&gt;MapView&lt;/a&gt;. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.&lt;/p&gt;
&lt;p&gt;Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>I was working an Android application, and I had an activity that contains a map in it, the map is hosted inside a <a href="http://developer.android.com/resources/tutorials/views/hello-mapview.html">MapView</a>. The application had to show some pins over the map, the pins locations are obtained from a web service. I had to retrieve the pins locations after the user pans the map or zooms in or out.</p>
<p>Google didn’t provide events for panning and zooming inside MapView class, but you can extend the class and do it your self, and that’s what I did.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[320]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a></p>
<h3 id="listener-interface">Listener Interface</h3>
<pre class="lang:java decode:true">import com.google.android.maps.GeoPoint;

public interface MapViewListener {
	void onPan(GeoPoint oldTopLeft,
			   GeoPoint oldCenter,
			   GeoPoint oldBottomRight,
			   GeoPoint newTopLeft,
			   GeoPoint newCenter,
			   GeoPoint newBottomRight);
	void onZoom(GeoPoint oldTopLeft,
				GeoPoint oldCenter,
				GeoPoint oldBottomRight,
				GeoPoint newTopLeft,
				GeoPoint newCenter,
				GeoPoint newBottomRight,
				int oldZoomLevel,
				int newZoomLevel);
	void onClick(GeoPoint clickedPoint);
}
</pre>
<p>This listener will receive three events, onPan when the user pans the map, onZoom when the user zooms in or out, onClick when the user taps on the map without panning.</p>
<p>Each event will pass useful parameters, which are old and new values for the top left corner, bottom right corner, center point and zoom level.</p>
<h3 id="map-view-code">Map View Code</h3>
<p>The new map view will inherit the MapView class, and define some useful variables:</p>
<pre class="lang:java decode:true">import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;

public class ObservableMapView extends MapView {
	public ObservableMapView(Context context, String apiKey) { super(context, apiKey); }
	public ObservableMapView(Context context, AttributeSet attrs) { super(context, attrs); }
	public ObservableMapView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }
	
	private GeoPoint mOldTopLeft;
	private GeoPoint mOldCenter;
	private GeoPoint mOldBottomRight;
	private int mOldZoomLevel = -1;
	
	private MapViewListener mMapViewListener;
	public MapViewListener getMapViewListener() { return mMapViewListener; }
	public void setMapViewListener(MapViewListener value) { mMapViewListener = value; }

// ...
}
</pre>
<p>To get touch events we’re going to override the onTouchEvent:</p>
<pre class="lang:java decode:true">@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (ev.getAction() == MotionEvent.ACTION_UP) {
			GeoPoint newCenter = this.getMapCenter();
			GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
			GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
			
			if (this.mMapViewListener != null &&
				newTopLeft.getLatitudeE6() == mOldTopLeft.getLatitudeE6() &&
				newTopLeft.getLongitudeE6() == mOldTopLeft.getLongitudeE6()) {
				mMapViewListener.onClick(this.getProjection().fromPixels((int)ev.getX(), (int)ev.getY()));
			}
		}
		return super.onTouchEvent(ev);
	}
</pre>
<p>Here we’re checking the new coordinates with the old coordinates, if they haven’t changed then the user has tapped on the map, but if they changed then it is a panning event, we’re not going to emit the event of panning now.</p>
<p>To be able to find if the user has zoomed we’re going to override the dispatchDraw method, because it will be called when the user pans or zooms, so it is the place we’re going to check for events in it.</p>
<pre class="lang:java decode:true">@Override
	protected void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		
		GeoPoint newCenter = this.getMapCenter();
		GeoPoint newTopLeft = this.getProjection().fromPixels(0, 0);
		GeoPoint newBottomRight = this.getProjection().fromPixels(this.getWidth(), this.getHeight());
		int newZoomLevel = this.getZoomLevel();
		
		if (mOldCenter == null)
			mOldCenter = newCenter;
		
		if (mOldTopLeft == null)
			mOldTopLeft = newTopLeft;

		if (mOldBottomRight == null)
			mOldBottomRight = newBottomRight;

		if (newTopLeft.getLatitudeE6() != mOldTopLeft.getLatitudeE6() || newTopLeft.getLongitudeE6() != mOldTopLeft.getLongitudeE6()) {
			if (this.mMapViewListener != null) {
				GeoPoint oldTopLeft, oldCenter, oldBottomRight;
				
				oldTopLeft = mOldTopLeft;
				oldCenter = mOldCenter;
				oldBottomRight = mOldBottomRight;
		
				mOldBottomRight = newBottomRight;
				mOldTopLeft = newTopLeft;
				mOldCenter = newCenter;
				
				mMapViewListener.onPan(oldTopLeft,
									   oldCenter,
									   oldBottomRight,
									   newTopLeft,
									   newCenter,
									   newBottomRight);
			}
		}
		
		if (mOldZoomLevel == -1)
			mOldZoomLevel = newZoomLevel;
		else if (mOldZoomLevel != newZoomLevel && mMapViewListener != null) {
			int oldZoomLevel = mOldZoomLevel;
			GeoPoint oldTopLeft, oldCenter, oldBottomRight;
			oldTopLeft = mOldTopLeft;
			oldCenter = mOldCenter;
			oldBottomRight = mOldBottomRight;
	
			mOldZoomLevel = newZoomLevel;
			mOldBottomRight = newBottomRight;
			mOldTopLeft = newTopLeft;
			mOldCenter = newCenter;
			
			mMapViewListener.onZoom(oldTopLeft,
									oldCenter,
									oldBottomRight,
									newTopLeft,
									newCenter,
									newBottomRight,
									oldZoomLevel,
									newZoomLevel);
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom">Project on GitHub</a></p>
<p><a href="https://github.com/mpcabd/android-map-view-pan-zoom/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
    <item>
      <title>Log to a file on computer in Android</title>
      <link>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</link>
      <pubDate>Mon, 12 Dec 2011 19:53:04 +0000</pubDate>
      <guid>https://mpcabd.xyz/log-to-a-file-on-computer-in-android/</guid>
      <description>&lt;p&gt;It’s been a long time since the last time I blogged about something, and many things have changed since then,&lt;/p&gt;
&lt;p&gt;I graduated, got engaged and moved to Dubai.&lt;/p&gt;
&lt;p&gt;I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.&lt;/p&gt;
&lt;p&gt;&lt;a href=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png&#34; rel=&#34;lightbox[310]&#34; title=&#34;Androids&#34;&gt;&lt;img src=&#34;http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png&#34; alt=&#34;&#34; title=&#34;Androids&#34; width=&#34;300&#34; height=&#34;105&#34; class=&#34;aligncenter size-medium wp-image-315&#34; srcset=&#34;https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w&#34; sizes=&#34;(max-width: 300px) 100vw, 300px&#34; /&gt;&lt;/a&gt;Now let’s move to business, so I was working on an &lt;a href=&#34;http://developer.android.com/index.html&#34; title=&#34;Android Developers&#34;&gt;Android&lt;/a&gt; application and I needed to log some debug messages, normally I’d use &lt;code&gt;Log.d(TAG, message);&lt;/code&gt; and this will send the message to &lt;a href=&#34;http://developer.android.com/guide/developing/tools/logcat.html&#34; title=&#34;logcat | Android Developers&#34;&gt;logcat&lt;/a&gt;, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.&lt;/p&gt;</description>
      <content:encoded><![CDATA[<p>It’s been a long time since the last time I blogged about something, and many things have changed since then,</p>
<p>I graduated, got engaged and moved to Dubai.</p>
<p>I have plenty of things in my mind to blog about, many solutions and many tools that I developed that I’d like to share it with everyone, but I haven’t settled down, and my schedule is not stable yet, so I haven’t got enough time to sort things out and start blogging, anyway this post is simple and it doesn’t need much description so I thought I’d share it with you now.</p>
<p><a href="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png" rel="lightbox[310]" title="Androids"><img src="http://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png" alt="" title="Androids" width="300" height="105" class="aligncenter size-medium wp-image-315" srcset="https://mpcabd.xyz/wp-content/uploads/2011/12/Androids-300x105.png 300w, https://mpcabd.xyz/wp-content/uploads/2011/12/Androids.png 766w" sizes="(max-width: 300px) 100vw, 300px" /></a>Now let’s move to business, so I was working on an <a href="http://developer.android.com/index.html" title="Android Developers">Android</a> application and I needed to log some debug messages, normally I’d use <code>Log.d(TAG, message);</code> and this will send the message to <a href="http://developer.android.com/guide/developing/tools/logcat.html" title="logcat | Android Developers">logcat</a>, but logcat is not useful for long messages, like for example if I needed to log the response I received from a web service, this response might be long and sending it to logcat will truncate it.</p>
<p>So usually in such situations we use files and log whatever we need inside them, but I’m working on an Android phone/emulator, and dealing with files and logging to them and reading them later from the computer will be a tedious thing to do, so I came up with a simple solution to log messages from Android to my computer.</p>
<p>The idea is to create a simple web server that accepts POST requests, these requests have only one parameter which is the data to be logged. I made it as simple as possible, I could have defined levels for logging and tags and other sorts of things, but I wanted a simple solution that wouldn’t take more than five minutes to write and get it working.</p>
<h3 id="simple-web-server">Simple web server</h3>
<p>Since I’m a pythonist geek I couldn’t think of anything better than Python to implement the simple web server, and it was really great, since I didn’t have to write so much code!</p>
<p>I’ll be using <code>HTTPServer</code> and <code>BaseHTTPRequestHandler</code> from <a href="http://docs.python.org/library/basehttpserver.html">BaseHTTPServer</a> module, some <a href="http://docs.python.org/library/threading.html">threading</a> and <a href="http://docs.python.org/library/cgi.html">cgi</a>.</p>
<pre class="lang:python decode:true">from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

import threading
import cgi
import time

IP = '192.168.1.3'
PORT = 5500

LOG_FILE = r'C:\AndroidLogFile.log'

POST_PARAMETER = 'log'
</pre>
<p>I set the server to run on port 5500, don’t ask why I chose this number, I didn’t think of it 😛</p>
<p>I define a function that will execute a function in a separate thread as a daemon thread:</p>
<pre class="lang:python decode:true">def startThread(fn):
    thread = threading.Thread(target=fn)
    thread.setDaemon(True)
    thread.start()
    return thread
</pre>
<p>I define the block of code to be executed when running the server:</p>
<pre class="lang:python decode:true">if __name__ == '__main__':
    httpd = HTTPServer((IP, PORT), lambda *args, **kwargs: LogHandler(*args, **kwargs))
    serve_thread  = startThread(httpd.serve_forever)
    while serve_thread.isAlive():
        serve_thread.join(timeout=1)
</pre>
<p>Here I created an HTTP web server that is bound to the IP/PORT set at the beginning of the script, and I mapped the handler for this web server to a class called LogHandler.</p>
<p>This handler will handle the requests, and hence it’ll handle POST requests and save their contents into the specified file.</p>
<pre class="lang:python decode:true">class LogHandler(BaseHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        BaseHTTPRequestHandler.__init__(self, *args, **kwargs)

    def do_POST(self):
        length = int(self.headers.getheader('content-length'))
        postvars = cgi.parse_qs(self.rfile.read(length), keep_blank_values=1)
        f = open(LOG_FILE, 'a')
        f.write('%s:\n%s\n%s\n' % (time.strftime('%Y/%m/%d %H:%M:%S'), postvars[POST_PARAMETER][0], '*' * 20))
        f.close()

        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.send_header('Cache-Control', 'no-cache')
        self.end_headers()
        self.wfile.write('Saved!')
</pre>
<p>Pretty simple, not more than 35 lines of code!</p>
<p>Now let’s move to the Android/Java side.</p>
<h3 id="androidjava-class">Android/Java class</h3>
<p>This class will be responsible for sending POST requests to the server, I’ll be using Apache classes to do the HTTP requests, and I’ll use some other classes from Java standard library, along with Android log class to log exceptions.</p>
<pre class="lang:java decode:true">import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
</pre>
<p>The class starts with defining some constants:</p>
<pre class="lang:java decode:true">public class LogToFile {
	private static final String LOG_TO_FILE_ADDRESS = "http://192.168.1.3";
	private static final String LOG_TO_FILE_URL = "/";
	private static final String LOG_TO_FILE_LOG_PARAMETER = "log";
	private static final int LOG_TO_FILE_PORT = 5500;
</pre>
<p>Then I define a method that constructs an HTTP POST request to the specified url along with the specified parameters:</p>
<pre class="lang:java decode:true">private static HttpPost Post(String url, HashMap&lt;String, String> params, HashMap&lt;String, ArrayList&lt;String>> arrayParams) {
		try {
			if (!url.endsWith("/"))
				url += "/";
			List&lt;NameValuePair> params_list = null;
			if (params != null) {
				params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, String> entry : params.entrySet())
					params_list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			if (arrayParams != null) {
				if (params_list == null)
					params_list = new LinkedList&lt;NameValuePair>();
				for (Entry&lt;String, ArrayList&lt;String>> entry : arrayParams.entrySet())
					for (String value : entry.getValue())
						params_list.add(new BasicNameValuePair(entry.getKey(), value));
			}
			HttpPost request = new HttpPost(url);
			if (params != null)
				request.setEntity(new UrlEncodedFormEntity(params_list, "utf-8"));
			return request;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>I know this is a lot of code for such thing, but this method is used elsewhere in my application and that’s why it had to be this generic.</p>
<p>Another method will be used to execute the request, also it is generic to be used elsewhere, you can edit the code and make it more specific to your needs.</p>
<pre class="lang:java decode:true">private static HttpResponse ExecuteRequest(HttpUriRequest request) {
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(request);
			return response;
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
		return null;
	}
</pre>
<p>And now to the final piece of code here, this is the method that you’ll call from anywhere in your application to log messages to the file:</p>
<pre class="lang:java decode:true">public static void LogToFile(String log) {
		try {
			HashMap&lt;String, String> params = new HashMap&lt;String, String>();
			params.put(LOG_TO_FILE_LOG_PARAMETER, log);
			HttpPost request = Post(String.format("%s:%d%s", LOG_TO_FILE_ADDRESS, LOG_TO_FILE_PORT, LOG_TO_FILE_URL), params, null);
			HttpResponse response = ExecuteRequest(request);
			response.getEntity().consumeContent();
		} catch (Exception e) {
			Log.e("", e.getClass().getName() + "\n" + e.getMessage());
		}
	}
</pre>
<h3 id="download">Download</h3>
<p>The source code is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU Public License (GPL)</a>.</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file">Project on GitHub</a></p>
<p>You can download the source code from here:</p>
<p><a href="https://github.com/mpcabd/android-log-to-pc-file/tarball/master">Source code from GitHub</a></p>]]></content:encoded>
    </item>
  </channel>
</rss>
