Friday, October 25, 2013

MVC in android




There is no universally unique MVC pattern in android . MVC is a concept rather than a solid programming framework, so it is about conceptual understanding of MVC. We can implement our own MVC in any platforms. As long as we stick to the following basic idea, we are implementing MVC:
  • Model: What to render
  • View: How to render
  • Controller: Events, user input
we can say MVC is already implemented in Android as:
  1. View = layout, resources and built-in classes like Button derived from android.view.View.
  2. Controller = Activity
  3. Model = the classes that implement the application logic
Also we can  think about this way, when we program our model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, we don't care our rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform specific rendering code.
This is particularly useful when you use Mono to share the model in order to develop cross platform applications.
  • You define your user interface in various XML files by resolution/hardware etc.
  • You define your resources in various XML files by locale etc.
  • You extend clases like ListActivity, TabActivity and make use of the XML file by inflaters
  • You can create as many classes as you wish for your model
  • A lot of Utils have been already written for you. DatabaseUtils, Html,
Please visit the Blog for information.

Tuesday, October 15, 2013

Special cases When the Services running in the background can be destroy?


 Services should carry out long running operations indefinitely, they are fated to be killed by the Android android system, if they are running in the back-ground.  

This is how it happens: 

 1) When a Service starts, it runs in the main process: A service when created does not create a separate thread/process for itself (unless instructed to do so); instead, it runs in the main thread of the running application, thus consuming the memory resources of the main system. 

 2) What happens in case of low system memory? The system would choose to close the components that are low priority, but are still consuming the system resources. Thus, the background components not in user focus are the first ones the system kills. Therefore, it would destroy the services running in the background. This is to free system resources for more important components (Example: for the activity in the foreground interacting with the user).

  3) Does system follow a pattern while killing services to free resources? Yes it does! Read on to find out:  a) Unbound Service: Over time, the system pushes down a long-running service to lower priority in the list of background tasks, and this service is more likely to close first (if unbound), when memory shortage occurs.  b) Services bound to foreground activity: The services that are bound to an activity or any other application component running in the foreground are less likely to be killed than an unbound activity.  c) Foreground Services: The system would never kill a service if it were declared to run in the foreground. We would discuss more about this in later Android tutorials. Stay put!  

4) How to keep a Service from being killed? a) You can create separate threads while creating services for the services to run. Thus, there is reduced consumption of main application memory, and the likelihood of the service being destroyed due to memory shortage is lower than otherwise.  b) As discussed before, you can declare a Service to run in the foreground. This can prevent the system from killing the Service

Difference between bound and unbound service in Android

Android Bound Service and Unbound Service run in Background Android Services is used to do any background task in current activity.There is two types of Services available in android.Service class is responsible for using Services in android for that we need to extends Services class in out Custom service. 

 Bound Service :Service which call indefinitely in between activity 
An Android component may bind itself to a Service using bindservice (). A bound service would run as long as the other application components are bound to it. As soon as they unbind, the service destroys itself. 

Unbound Service :Service which call at the life span of calling activity 
In this case, an application component starts the service, and it would continue to run in the background, even if the original component that initiated it is destroyed. For instance, when started, a service would continue to play music in the background indefinitely.

Services has different life cycle from Activity. Services has different method for their life cycle which is startService(),stopService(),onBindService()  



Monday, October 14, 2013

Android Application class and it's use

 The Application class is  in the Android api and according to the class name it's used for global settings or running entrance.
We can specify its name in your AndroidManifest.xml's tag
1
<application android:icon="@drawable/icon" 
android:label=
"@string/app_name" android:name="MyApplication">
We can create our own subclass of Application like this:
public class MyApplication extends Application {
 
       @Override
       public void onConfigurationChanged(Configuration newConfig) {
           super.onConfigurationChanged(newConfig);
        }
 
      @Override
       public void onCreate() {
                super.onCreate();
       }
 
      @Override
       public void onLowMemory() {
             super.onLowMemory();
    }
 
      @Override
       public void onTerminate() {
             super.onTerminate();
    }
 
}



Application level callbacks

  • onConfigurationChanged( ) Called by the system when the device configuration changes while your component is running.
  • onCreate( ) Called when the application is starting, before any other application objects have been created.
  • onLowMemory( ) This is called when the overall system is running low on memory, and would like actively running processes to tighten their belts.
  • onTerminate( ) This method is for use in emulated process environments. It will never be called on a production Android device, where processes are removed by simply killing them; no user code (including this callback) is executed when doing so.


    
    

An eye over Google Cloud Messaging (GCM)


Wednesday, September 25, 2013

using IBinder class to Bind service

There are total 3 ways to bind a service with application components
  1. Using IBinder class
  2. Using Messanger class
  3. Using AIDL
The life is a process of learning even after some bad happening we are going on and learning things. someone asked me about the Binding Services and i was unable to answer  and that after i tried to work on the same.

Create a project and have a main activity with Name MainActivity.

Implementing the Binder

to implement the binder creat a class SomeServic which extends Service class, i create an inner class with name LocalBinder which is inner class and inside SomeService.

package com.example.bindserviceusingbinderclass;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class SomeService extends Service {

IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

public class LocalBinder extends Binder {
public SomeService getServerInstance() {
return SomeService.this;
}
}

public String getTime() {
SimpleDateFormat mDateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
}


finally we need to start service at Mainactivity

Binding the Client to the Service

package com.example.bindserviceusingbinderclass;

import com.example.bindserviceusingbinderclass.SomeService.LocalBinder;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;



public class MainActivity extends Activity {

boolean mBounded;
SomeService mServer;
TextView text;
Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {

public void onClick(View v) {
text.setText(mServer.getTime());
}
});
}

@Override
protected void onStart() {
super.onStart();
Intent mIntent = new Intent(this, SomeService.class);
bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};

ServiceConnection mConnection = new ServiceConnection() {

public void onServiceDisconnected(ComponentName name) {
Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
mBounded = false;
mServer = null;
}

public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
mBounded = true;
LocalBinder mLocalBinder = (LocalBinder) service;
mServer = mLocalBinder.getServerInstance();
}
};

@Override
protected void onStop() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
@Override
protected void onDestroy() {
super.onStop();
if (mBounded) {
unbindService(mConnection);
mBounded = false;
}
};
}


do not forget to work with manifest for the service.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bindserviceusingbinderclass"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.bindserviceusingbinderclass.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".SomeService" />
    </application>
    

</manifest>

the activity_main.xml looks like

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/text"
        android:layout_below="@+id/text"
        android:layout_marginLeft="36dp"
        android:layout_marginTop="54dp"
        android:text="Button" />

</RelativeLayout>



Wednesday, June 26, 2013

Android Downloading MP3 to sd card

Some guy asked me the question regarding to how to download the mp3 files to the sd card and i wrote the program for this purpose please have a look and enjoy the practices.

Create a project with the name DownloadMp3 and have a main activity with following code

package com.jitesh.downloadmp3;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

private static String fileName = "file.mp3";
private static final String MY_URL = "http://www.virginmegastore.me/Library/Music/CD_001214/Tracks/Track1.mp3";

private Button play;
private TextView message;

private ProgressDialog pDialog;

// Progress dialog type (0 - for Horizontal progress bar)
public static final int progress_bar_type = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

play = (Button) findViewById(R.id.download);
message=(TextView)findViewById(R.id.message);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new DownloadFileFromURL().execute(MY_URL);
}
});

}

/**
* Showing Dialog
* */
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
pDialog = new ProgressDialog(this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
pDialog.show();
return pDialog;
default:
return null;
}
}

public void downloadStreams() {
try {
URL url = new URL(MY_URL);
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();

String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("log_tag", "PATH: " + PATH);
File file = new File(PATH);
if (!file.exists()) {
file.mkdirs();
}
File outputFile = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);

InputStream is = c.getInputStream();

byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
} catch (IOException e) {
Log.e("log_tag", "Error: " + e);
}
Log.v("log_tag", "Check: ");
}

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
showDialog(progress_bar_type);
}

/**
* Downloading file in background thread
* */
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();

// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(),
8192);

// Output stream to write file
OutputStream output = new FileOutputStream("/sdcard/"
+ fileName);

byte data[] = new byte[1024];

long total = 0;

while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress("" + (int) ((total * 100) / lenghtOfFile));

// writing data to file
output.write(data, 0, count);
}

// flushing output
output.flush();

// closing streams
output.close();
input.close();

} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}

return null;
}

/**
* Updating progress bar
* */
protected void onProgressUpdate(String... progress) {
// setting progress percentage
pDialog.setProgress(Integer.parseInt(progress[0]));
}

/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
dismissDialog(progress_bar_type);

// Displaying downloaded image into image view
// Reading image path from sdcard
String imagePath = Environment.getExternalStorageDirectory()
.toString() + fileName;
// setting downloaded into image view
// my_image.setImageDrawable(Drawable.createFromPath(imagePath));
message.setText("File downloaded and saved to directory==>"+imagePath);
}

}
}


the main layout file is presented here which is activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/download"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Download" >
    </Button>

</RelativeLayout>

the strings.xml is having following attributes

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">DownloadMp3</string>
    <string name="hello_world">please click the button to download the stream!</string>
    <string name="menu_settings">Settings</string>

</resources>


the manifest should have following permissions

<uses-permission android:name="android.permission.INTERNET" />
     
    <!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

and it should look like below given manifest attributes

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jitesh.downloadmp3"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.jitesh.downloadmp3.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        
    </application>
<uses-permission android:name="android.permission.INTERNET" />
     
    <!-- Permission to write to external storage -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

the screenshots are given below



Also the source code can be downloaded from http://www.mediafire.com/download/18axcocxot725pl/DownloadMp3.zip