Friday, December 14, 2012

Android FAQ


Android application on startup
******************************
Also, in
your manifest, define your service and listen for the boot-completed action:




android:name=".receiver.StartMyServiceAtBootReceiver"
android:enabled="true"
android:exported="true"
android:label="StartMyServiceAtBootReceiver">




Then you need to define the receiver that will get the BOOT_COMPLETED action andstart your service.
public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceIntent = new Intent("com.myapp.MySystemService");
context.startService(serviceIntent);
}
}
}
Intent Filters:
******************
Android components like activities can also serve implicit intents. but to do so they have to filter all
implicit intents in order to serve only the intents they desire to serve. this is done using intent filters.
Suppose you want to create an activity that acts as the default dialer activity. You must associate an
intent filter with this activity in order to that this activity serve the dial intents only.
Let’s demonstrate a simple example which is creating an application with one activity that we want to
make it a dialer activity.
Create a new android project, create an activity and name it Dialer.
In the AndroidManifest.xml file of this application add the following to the Dialer activity:





to become:android:label="@string/app_name">










Now what we have done is adding an intent filter to that activity. this intent filter hasthe following properties:
A.Action: the type of implicit intents that this activity responds to. in our case it is the dial action.
higher numbers represent higher priority.
B.Priority: about the priority of that activity over other activities that respond to the same type of
intents.
C.Category: Implicit intents have built-in categories. in order that an implicit intent be captured by our
activity, the implicit intent category must match our activity category.
D.Data: adds data specification scheme to the intent filter.
So if any other application has the following module to launch the dialer:
Intent in=new Intent(Intent.ACTION_DIAL, Uri.parse("tel:000"));
startActivity(in);The user will see the following dialog offering him/her the choice between the
default dialer and our custom dialer.
Layouts in Android
****************
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View
In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is an
example of the linear layouts), either Horizontally or Vertically and this behavior is set in
android:orientation which is an attribute of the node LinearLayout.
In a relative layout every element arranges itself relative to other elements or a parent element.
Android Components :
******************
Indent
Services
Broadcast Receiver
Content Provider
Widget
Intents are asynchronous messages which allow the application to request functionality from other
components of the Android system,
Services perform background tasks without providing a user interface
A ContentProvider provides a structured interface to application data. Via a ContentProvider your
application can share data with other applications. Android contains an SQLite database which is
frequently used in conjunction with a ContentProvider. The SQLite database would store the data,
which would be accessed via the ContentProvider.
BroadcastReceiver can be registered to receive system messages and Intents. A BroadcastReceiver
will get notified by the Android system, if the specified situation happens. For example a
BroadcastReceiver could get called once the Android system completed
the boot process or if a phone call is received.
Widgets are interactive components which are primarily used on the Android homescreen. ex: Weather
Widget
Application shared preferences allows you to save and retrieve key, value pair data. Before getting
into tutorial, I am giving basic information needed to work with shared preferences.
Initialization
Application shared preferences can be fetched using getSharedPreferences() method.You also need an
editor to edit and save the changes in shared preferences. The following code can be used to get
application shared preferences.
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private
mode
Editor editor = pref.edit();
Storing Data
You can save data into shared preferences using editor. All the primitive data types like booleans,
floats, ints, longs, and strings are supported. Call editor.commit() in order to save changes to shared
preferences.
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
Data can be retrived from saved preferences by calling getString() (For string) method. Remember this
method should be called on Shared Preferences not on Editor.
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Clearing / Deleting Data
If you want to delete from shared preferences you can call remove(“key_name”) to delete that
particular value. If you want to delete all the data, call clear()
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Following will clear all the data from shared preferences
editor.clear();
editor.commit(); // commit changes
Calling Webservice in android
*****************************
public class WebserviceActivity extends Activity {
private static final String NAMESPACE = "https://api.authorize.net/soap/v1/";
private static final String URL ="https://apitest.authorize.net/soap/v1/Service.asmx?wsdl";
private static final String SOAP_ACTION = "https://api.authorize.net/soap/v1/AuthenticateTest";
private static final String METHOD_NAME = "AuthenticateTest";
private TextView lblResult;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lblResult = (TextView) findViewById(R.id.tv);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name","44vmMAYrhjfhj66fhJN");
request.addProperty("transactionKey","9MDQ7fghjghjh53H48k7e7n");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
//SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
// SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
lblResult.setText(resultsRequestSOAP.toString());
System.out.println("Response::"+resultsRequestSOAP.toString());
} catch (Exception e) {
System.out.println("Error"+e);
}
}
}
Calling HTTPPOST
****************
ArrayList nameValuePairs = new ArrayList();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("pass", pass));
nameValuePairs.add(new BasicNameValuePair("email", email));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2:8084/Login/form");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
TextView lbl = (TextView) findViewById(R.id.lbl);
lbl.setText(result);
} catch (Exception e) {
TextView tv = (TextView) findViewById(R.id.err);
tv.setText("Error parsing data " + e.toString());
System.out.println("Error parsing data " + e.toString());
}
Calling HTTPGET
***************
try {
HttpClient client = new DefaultHttpClient();
String getURL = "http://www.google.com";
HttpGet get = new HttpGet(getURL);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
// do something with the response
String response = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", response);
}
} catch (Exception e) {
e.printStackTrace();
}