Learn Android for Free,issues for developers, mobengineers website provide complete solutions for developers issues posts.It also provides online training for android development

Monday, October 29, 2012

Service in android

Activity is a foreground process. It contains user interaction. To run long running operations, we have to create a service.It will run in background. It does not contain user interaction.

Types of services:

1. Unbound Service: it runs in the background indefinitely even started activity with service ends also.
2. Bound Service : it will run till life time of activity.

 Activity can start service via startService()and it will stop via stopService().
If activity want to interact with service,it can use bindService().

first onCreate() is called, after onStartCommand is called with the intent data provided by the activity.


Android provides many predefined services exposed via Manager class.


Own services must be declared in the manifest file..


Some methods:

An activity can start a service via startService() method.

stop the service by using stopService() method.

bindService() - this is for activity to interact with service.

it needs "ServiceConnection" object.


Once service is started    onCreate()  is called.
onStart()



onBind()- the system calls when other component want to bind the service.

onStop() - for stopping the service.

OnDestroy()- called when service is no longer used. and it is destroyed.



Own services must be declared in manifest file.

how to declare own service:

<service android:name="your class"></service>
implementing class must extend the class   " service or one of its subclasses.


Ex: AsyncTask:
using services in android allows to have app running inthe background. if u want to do a simple task run in the background, use AsyncTask.

AsyncTask class:


private class someclassname extends AsyncTask<x,y,z>

protected void onPreExecute()
{
// starting new thread i.e    initilizing


protected void doInBackground()

// perform the action or do the task


protected void onPostExecute(){
// closing the process
}


 Example:

MainActivity.java
package com.example.servicetest;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this,ServiceAct.class));
    }

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


ServiceAct.java
package com.example.servicetest;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class ServiceAct extends Service{
    String tag="service tag";
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Log.d(tag, "service destroyed");   
    }
   
@Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Log.d(tag, "service started");
        stopSelf();
    }}

manifest permission

<service android:name="ServiceAct" />

Tuesday, October 23, 2012

Camera:

in android, we can access camera from app by 2 ways.

implicit intent launches default camera

Intent i=new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(i);
permission in manifest.xml


<uses-permission android:name="android.permission.CAMERA"/>


 Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener() {
           
            public void onClick(View v) {
                // TODO Auto-generated method stub
                 Intent  i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    i.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                    startActivityForResult(i, cameraData);
            }
        });



Other way is creating Camera class


camera class: to access camera hardware
SurfaceView class : dedicate a drawing surface at lowest level of the view as a placeholder to display the camera preview before describing how these are tied together and the layout structure we have to declare.



















WifiManager

java.lang.object

-  android.net.wifi.wifimanager

WifiManager class provides primary api for managing all aspects of wifi connectivity.

get the instance of this class by calling

contaxt.getSystemService(context.WIFI_Service);

it deals with list of configured networks. this can be viewed, updated.


check wifi status:

ConnectivityManager conMgr;
NetworkInfo netInfo;
WifiManager wifiMgr;

conMgr=(ConnectivityManager)getSystemService(context.WIFI_Service);
netInfo=conMgr.getActiveNetworkInfo();
if(!(netInfo==null))
{
if(WifiMgr.isWifiEnabled())
{
//wifi  enabled
}
else
{
//wifi disabled i.e not available
}
}







WifiManager in Android

java.lang.object

-  android.net.wifi.wifimanager

WifiManager class provides primary api for managing all aspects of wifi connectivity.

get the instance of this class by calling

contaxt.getSystemService(context.WIFI_Service);

it deals with list of configured networks. this can be viewed, updated.


check wifi status:

ConnectivityManager conMgr;
NetworkInfo netInfo;
WifiManager wifiMgr;

conMgr=(ConnectivityManager)getSystemService(context.WIFI_Service);
netInfo=conMgr.getActiveNetworkInfo();
if(!(netInfo==null))
{
if(WifiMgr.isWifiEnabled())
{
//wifi  enabled
}
else
{
//wifi disabled i.e not available
}
}







TelephonyManager

java.lang.object
android.telephony.TelephonyManager

it provides access to the info about telephony services.
we can register services to receive notification of telephony state changes.


context.getSystemService(context.TELEPHONY_SERVICE);


SOME METHODS:

public int getCallState()-    get the call state

public cellLocation getCellLocation()- returns current location of the device.. returns null if the current location not available.

this requires permission in the manifest file.

what permissions we need to declare:

ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION

some more methods:

we can get device id


public string getDeviceId()

we can get network operator

public string getNetworkOperator()


we can get sim operator name

public string getSimOperatorName()







Bluetooth in Android



package:
import package:
import android.bluetooth.*;

<uses-permission android:name="android.permission.BLUETOOTH"/>
 for more advanced bluetooth tasks , like setting name, connecting....

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>


ACCESS THE BLUETOOTH ADAPTER

Android bluetooth apis include bluetooth adapter class.
if we want to perform any action
BluetoothAdapter class must be instantiated.

BluetoothAdapter bluetooth=BluetoothAdapter.getDefaultAdapter();
if(bluetooth!=null)
{
// work with bluetooth
}
else
{
//disabled// switch on bluetooth
}



for displaying name of bluetooth

String status;
if(bluetooth.isEnabled)
{
String mydeviceaddress=bluetooth.getAddress();
String mydevicename=bluetooth.getName();
status=mydeviceaddress+:+mydevicename;
}
else
{
status="bluetooth is not enabled"
}



}


setting name
bluetooth.setName("Mydevice");







Pending Intent in Android


Pending intent is a token to the other application, which allows the other application to use your application’s permissions to execute a predefined piece of code.
Here other applications means  it may be an alarm manager, home screen widget manager etc......

To perform a broadcast via a pending intent, so get a pendingIntent via PendingIntent.getBroadcast().
To perform an activity via pending intent, you receive the activity via PendingIntent.getActivity.

Notifications -Toast, Dialogs,Statusbar Notifications


 Notifications:
toast notification
statusbar notification
dialogboxes

Adding sound
notification.defaults|=Notification.DEFAULT_SOUND;


Adding Vibration:

notification.defauls|=Notification.DEFAULT_VIBRATE;

adding flash lights:
notification.defauls|=Notification.DEFAULT_LIGHTS;


dialog is small window on the screen. when dialog is executed the activity losses its focus and dialog gets total control of app.

android.app. dialog package


alert dialog
progress dialog
date picker dialog
time picker dialog


alert dialog: it is a small window. it contains 0,1,2 or 3 buttons combination.It contains max 3 buttons like +ve ,-ve, neutral buttons.



Progress  Dialog:

its an extension of alert dialog class that can display progress animation in the form of spinning wheel.











Saturday, October 20, 2012

Service in Android




 MainActivity.java
package com.example.serviceexample;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
            Button b1;
            Button b2;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
         b1=(Button)findViewById(R.id.button1);
         b2=(Button)findViewById(R.id.button2);
        b1.setOnClickListener(this);
        b2.setOnClickListener(this);   
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

     public void onClick(View v) {
                        // TODO Auto-generated method stub
                        switch(v.getId())
                        {
                        case R.id.button1:
                                    startService(new Intent(this,ServiceDemo.class));
                                    break;
                        case R.id.button2:
                                    startService(new Intent(this,ServiceDemo.class));
                                   
                        }
            }
}


 ServiceDemo.java
package com.example.serviceexample;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;

public class ServiceDemo extends Service{
     
      MediaPlayer mediaplayer;

      @Override
      public IBinder onBind(Intent arg0) {
            // TODO Auto-generated method stub
            return null;
      }

      @Override
      public void onCreate() {
            // TODO Auto-generated method stub
            super.onCreate();
           
            mediaplayer=MediaPlayer.create(this, R.raw.newsong);
      }

      @Override
      public void onDestroy() {
            // TODO Auto-generated method stub
            super.onDestroy();
            mediaplayer.stop();
      }
      @Override
      public void onStart(Intent intent, int startId) {
            // TODO Auto-generated method stub
            super.onStart(intent, startId);
            mediaplayer.start();
      }
}

Declare manifest permission for service

 <service android:name="ServiceDemo"></service>



you can download source code here

http://www.4shared.com/rar/O39SukJ_/ServiceExample.html?



Monday, October 15, 2012

Creating Resources for multiple screens



          Android application runs on many android devices. To work with multiple devices, it will make scaling and resizing to make work with the devices. Even it adjust the screen, the user may experience bad with the application due to blurring of images, stretching the images, overlapping views etc.

          To work with the multiple resolutions, we have to design multiple layouts.
Some important terms:

Screen density:
         The quantity of pixels within a physical area of the screen is known as dpi(dots per inch).
Low density screen contains less pixels where as high density screen contains more pixels within given physical area.
Android groups all actual densities into 4 general densities
Low density, medium density, high density and extra high density pixels.
Hdpi, mdpi, hdpi,xhdpi.

Screen size:
          Actual physical size of screen, measured as the screen’s diagonal. Android combined all the screens into 4 generalized screens.
Those are  small, normal, large and extra large.
Orientation:
         Orientation will change dynamically when rotate the mobile. we have to consider orientation when designing screen.
Resolutions:
         Different screen contain different resolutions. We have to consider the resolutions  and we have to design different screens for different resolutions.



Different screen resolutions
Extra large screens are atleast   960dp x 720dp
 Large screens are atleast   640dp x 480dp
Normal screens are atleast   470dp x 320dp
Small screens are atleast   426dp x 320dp





Seo Directory List

Tuesday, October 9, 2012

Android Introduction


Android is a Linux based operating system for mobiles such as smart mobiles and tablets.
It was developed by OHA.
Android Incorporation is a small company established in 2003 at California.
This company is acquired by the google in 2005.
Google formed a group  “Open Hanset Alliance” in 2007.
To develop open standards for mobile devices , in this group 40+ companies joined.
The group contains Mobile Manufaturing companies, network companies, Mobile operators, semi conductor companies joined.


Definition of Android:

Android is a software stack comprising not only operating system but also middleware( the programming allows applications to talk to a network) and applications.
Features of Android:
Android Os supports Camera, Bluetooth, compass and Accelerometer, Wifi.
Runtime environment is Dalvik Virtual Machine. It is a register based Virtual Machine.
Integrated browser based on Webkit engine.
Sqlite for storing the data.
Support for GSM, CDMA technologies.

Versions:

Versions
Name
API level
Android
Apple Pie
1
Android
Banana Bread
2
Android    1.5
Cupcake
3
Android    1.6
Donut
4
Android    2.1
Eclair
7
Android    2.2
Froyo
8
Android 2.3 to 2.3.2
 Gingerbread
9
Android 2.3.3 to 2.3.7
Gingerbread
10
Android 3.0
Honeycomb
11
Android 3.1
Honeycomb
12
Android 3.2
Honeycomb
13
Android 4.0-4.0.2
Ice Cream Sand witch
14
Android 4.0.3 to 4.0.4
Ice Cream Sand witch
15
Android 4.1
Jelly Bean
16


Seo Directory List

20% off

Online Training

Your Name :
Your Email: (required)
Your Message: (required)

NDTV Gadgets360

Powered by Blogger.

Recent Posts

Find Us On Facebook

Popular Posts