Saturday, September 27, 2014

IntentService

IntentService allows execution of asynchronous Tasks on Separate Threads.

It is important to note that once your service has finished executing a task, it should be stopped as soon as possible so that it does not unnecessarily hold up valuable resources.

Unfortunately, a lot of developers often forgot to terminate a service when it is done performing its task.

It executes its task within a worker thread and terminates itself when the task is completed

    public void startService(View view)
    {
    startService(new Intent(getBaseContext(), MyIntentService.class));
    }

public class MyIntentService extends IntentService 
{

public MyIntentService(String name) {
super("MyIntentServiceName");
// TODO Auto-generated constructor stub
}

protected void onHandleIntent(Intent intent)
{
try
{
int result = downloadFile(new URL("http://www.amazon.com/somefile.pdf"));
}catch(MalformedURLException e)
{
e.printStackTrace();
}
}

private int downloadFile(URL url)
{
try
{
Thread.sleep(5000);
}catch(InterruptedException e)
{
e.printStackTrace();
}

return 100;
}
}    

Friday, September 12, 2014

Context Object

Activity class is a subclass of Context, you can use the this keyword to represent the Context object.

Instances of the Context class are often used to provide references to your application.

Context 
    ^
    |
    |
Activity

When creating a view dynamically in an activity.
The constructor for the TextView class takes a Context object.

TextView tv = new TextView(this);


Because the Toast() class is not used directly in the activity (it is used within the AlertDialog class), you need to return an instance of the Context class by using the getBaseContext() method.

.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
Toast.makeText(getBaseContext(),
"OK clicked!", Toast.LENGTH_SHORT)
.show();
}