Monday, September 2, 2013

How can we generate the Notifications In android



private static void generateNotification(Context context, String message,int receiverId) {
        int icon = R.drawable.on;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager)
        context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);
        String title = context.getString(R.string.title);
        Intent notificationIntent = new Intent(context, Activity_name.class);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP );
        PendingIntent intent =PendingIntent.getActivity(context, 0, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;    
        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(receiverId, notification);  

    }

Sunday, June 9, 2013

Getting Device width / height in android

 Display dispDefault = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int     totalwidth = dispDefault.getWidth();
int      totalheight = dispDefault.getHeight();

Load Images dynamically from drawable folder

private ImageView imge;
imge=(ImageView) findViewById(R.id.img);        //image


String Img_Name = Image_name dynamically;

    try {
int id = R.drawable.class.getField(Img_Name).getInt(null);
imge.setImageResource( id );
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Wednesday, November 28, 2012

Remove Tittle bar

Add following code to the manifest file :-

android:theme="@android:style/Theme.NoTitleBar"

<application android:icon="@drawable/app_icon" android:theme="@android:style/Theme.NoTitleBar" android:label="@string/app_name" >

Tuesday, July 10, 2012

URL Hitting in android


In android URL hitting mainly use 4-Connection Varibles

  • DefaultHttpClient
  • HttpPost   
  • HttpResponse
  • HttpEntity
             !    DefaultHttpClient  it use to establish the connection between server and android 

                  DefaultHttpClient  varible_name = new DefaultHttpClient();      

             !  HttpPost  which is used to communicate the php file(Server) with android.during the http post time varibles\values are posted.

                  HttpPost  varible_name = new HttpPost("http://server/projectlocation/phpfile.php?username="+mainusername+"&password="+mainpass);

                  In the above web address username and password are 2 field in php file

               !   HttpResponse this variable used to get the response from the server. Commonly the response in JSON(Java script object notation).


    try
              {
          DefaultHttpClient httpClient = new DefaultHttpClient();
          HttpPost httpPost = new HttpPost("http://projects.jishocom/rahulrk/locAdsLogin.php?username="+mainusername+"&password="+mainpass);

          HttpResponse httpResponse = httpClient.execute(httpPost);
          HttpEntity httpEntity = httpResponse.getEntity();
        String  line = EntityUtils.toString(httpEntity);
           System.out.println("the res"+line);

      } catch (UnsupportedEncodingException e) {
          line = "<results status=\"error\"><msg>Can't connect to serverlllllllll</msg></results>";
     } catch (MalformedURLException e) {
          line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
      } catch (IOException e) {
          line = "<results status=\"error\"><msg>Can't connect to serverjjjjjjjj</msg></results>";
      }


Sunday, June 24, 2012

image switcher in android

Image switcher which  help to Switch between images in android.

public class ImageswitcherActivity extends Activity implements ViewFactory
{
}


Here ViewFactory is the interface used in Image Switcher and also the interface provides the so many properties for images transaction like FADE IN FADE OUT etc...

The following Code illustrate how can we implement Image Switcher in android..


package a.b;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;

public class ImageswitcherActivity extends Activity implements ViewFactory {

        // A reference to the images contained into the drawable folder
        private Integer[] m_ImageIds = {
            R.drawable.ttttt,
            R.drawable.tttttt,
            R.drawable.gg,R.drawable.imagemmm,R.drawable.imagesh,R.drawable.imageww,
            R.drawable.ff,R.drawable.ffff,R.drawable.fgg
        };

        // The ImageSwitcher
        ImageSwitcher m_ImageSwitcher;

        // The Handler used for manage the Runnable that switch the images
        Handler m_Handler = new Handler();

        // The index of the current image
        int m_imageIndex = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
     
        // assign the ImageSwitcher
        m_ImageSwitcher = (ImageSwitcher)findViewById(R.id.img);
        m_ImageSwitcher.setFactory(this);
        // Create the Fade in animation
        Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        fadeIn.setDuration(4000);
        // Create the Fade out animation
        Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
        fadeOut.setDuration(4000);
        // Assign the two animations to the ImageSwitcher
        m_ImageSwitcher.setInAnimation(fadeIn);
        m_ImageSwitcher.setOutAnimation(fadeOut);

        // Start the Runnable
        m_Handler.post(m_UpdateTimeTask);
     
    }

        @Override
        public View makeView() {
                ImageView i = new ImageView(this);
                i.setBackgroundColor(0xFF000000);
                i.setScaleType(ImageView.ScaleType.FIT_CENTER);
                i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
                return i;
        }

        /*
         * Set the image to show into the ImageSwitcher, then post his execution after 5 seconds
         */
        Runnable m_UpdateTimeTask = new Runnable() {
                   public void run() {
                           // Set the Image to show
                           m_ImageSwitcher.setImageResource(m_ImageIds[m_imageIndex]);
                           // Increment the index
                           m_imageIndex++;
                           // if necessary restart from the first image
                           if(m_imageIndex > (m_ImageIds.length-1)){
                                   m_imageIndex = 0;
                           }
                           // Set the execution after 5 seconds
                           m_Handler.postDelayed(this, (5 * 1000));
                   }
        };

}






Xml file which describe how can we Implement switcher in Xml:-


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

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:orientation="vertical" >
     <ImageSwitcher android:layout_margin="10dp" 
     android:layout_width="fill_parent" 
     android:id="@+id/img" android:layout_height="212dp">
     </ImageSwitcher>
</LinearLayout>

DOWNLOAD THE FULL CODE

Thursday, May 17, 2012

Emulator shortcuts


Android Emulator Shortcuts

Keyboard Commands



Emulated Device KeyKeyboard Key
HomeHOME
Menu (left softkey)F2 or Page-up button
Star (right softkey)Shift-F2 or Page Down
BackESC
Call/dial buttonF3
Hangup/end call buttonF4
SearchF5
Power buttonF7
Audio volume up buttonKEYPAD_PLUS, Ctrl-F5
Audio volume down buttonKEYPAD_MINUS, Ctrl-F6
Camera buttonCtrl-KEYPAD_5, Ctrl-F3
Switch to previous layout orientation (for example, portrait, landscape)KEYPAD_7, Ctrl-F11
Switch to next layout orientation (for example, portrait, landscape)KEYPAD_9, Ctrl-F12
Toggle cell networking on/offF8
Toggle code profilingF9 (only with -trace startup option)
Toggle fullscreen modeAlt-Enter
Toggle trackball modeF6
Enter trackball mode temporarily (while key is pressed)Delete
DPad left/up/right/downKEYPAD_4/8/6/2
DPad center clickKEYPAD_5
Onion alpha increase/decreaseKEYPAD_MULTIPLY(*) / KEYPAD_DIVIDE(/)

logcat

The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various applications and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command. You can use logcat from an ADB shell to view the log messages.

DDMS


Android ships with a debugging tool called the Dalvik Debug Monitor Server (DDMS), which provides port-forwarding services, screen capture on the device, thread and heap information on the device, logcat, process, and radio state information, incoming call and SMS spoofing, location data spoofing, and more. This page provides a modest discussion of DDMS features; it is not an exhaustive exploration of all the features and capabilities.

Running DDMS

DDMS is integrated into Eclipse and is also shipped in thetools/ directory of the SDK. DDMS works with both the emulator and a connected device. If both are connected and running simultaneously, DDMS defaults to the emulator.
  • From Eclipse: Click Window > Open Perspective > Other... > DDMS.
  • From the command line: Type ddms (or ./ddms on Mac/Linux) from the tools/ directory.

How DDMS Interacts with a Debugger

On Android, every application runs in its own process, each of which runs in its own virtual machine (VM). Each VM exposes a unique port that a debugger can attach to.
When DDMS starts, it connects to adb. When a device is connected, a VM monitoring service is created between adb and DDMS, which notifies DDMS when a VM on the device is started or terminated. Once a VM is running, DDMS retrieves the the VM's process ID (pid), via adb, and opens a connection to the VM's debugger, through the adb daemon (adbd) on the device. DDMS can now talk to the VM using a custom wire protocol.
DDMS assigns a debugging port to each VM on the device. Typically, DDMS assigns port 8600 for the first debuggable VM, the next on 8601, and so on. When a debugger connects to one of these ports, all traffic is forwarded to the debugger from the associated VM. You can only attach a single debugger to a single port, but DDMS can handle multiple, attached debuggers.
By default, DDMS also listens on another debugging port, the DDMS "base port" (8700, by default). The base port is a port forwarder, which can accept VM traffic from any debugging port and forward it to the debugger on port 8700. This allows you to attach one debugger to port 8700, and debug all the VMs on a device. The traffic that is forwarded is determined by the currently selected process in the DDMS Devices view.
The following screenshot shows a typical DDMS screen in Eclipse. If you are starting DDMS from the command line, the screen is slightly different, but much of the functionality is identical. Notice that the highlighted process,com.android.email, that is running in the emulator has the debugging port 8700 assigned to it as well as 8606. This signifies that DDMS is currently forwarding port 8606 to the static debugging port of 8700.

Android Emulator



The emulator which act as an android OS devices.Our application can run only the Emulator.Emulator is the Interface between our android program or application.During the call,message services to emulator can communicate to each other.Emulator property can edit using AVD manager.New Emulator is also can start using AVD manager.
In Eclipse AVD manager can easily lunched by Eclipse->windows->Android SDK and AVD manager.And also during the cration of new AVD\Emulator we have to mention the SD card space. .

Android Layout Tutorial

An Android layout is a class that handles arranging the way its children appear on the screen.  Anything that is a View (or inherits from View) can be a child of a layout. All of the layouts inherit from ViewGroup (which inherits from View) so you can nest layouts.  You could also create your own custom layout by making a class that inherits from ViewGroup


AbsoluteLayout  FrameLayout   LinearLayout   RelativeLayout   TableLayout
 


AbsoluteLayout

AbsoluteLayout is based on the simple idea of placing each control at an absolute position.  You specify the exact x and y coordinates on the screen for each control.  This is not recommended for most UI development (in fact AbsoluteLayout is currently deprecated) since absolutely positioning every element on the screen makes an inflexible UI that is much more difficult to maintain.  Consider what happens if a control needs to be added to the UI. You would have to change the position of every single element that is shifted by the new control.


<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <Button 
     android:id="@+id/backbutton"
     android:text="Back"
     android:layout_x="10px"
     android:layout_y="5px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:layout_x="10px"
     android:layout_y="110px"
     android:text="First Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <EditText
     android:layout_x="150px"
     android:layout_y="100px"
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:layout_x="10px"
     android:layout_y="160px"
     android:text="Last Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
     <EditText
     android:layout_x="150px"
     android:layout_y="150px"
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
</AbsoluteLayout>

FrameLayout
FrameLayout is designed to display a single item at a time. You can have multiple elements within a FrameLayout but each element will be positioned based on the top left of the screen. Elements that overlap will be displayed overlapping. I have created a simple XML layout using FrameLayout that shows how this works.
<FrameLayout 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android">
 <ImageView 
  android:src="@drawable/icon"
  android:scaleType="fitCenter"
  android:layout_height="fill_parent"
  android:layout_width="fill_parent"/>
 <TextView
  android:text="Learn-Android.com"
  android:textSize="24sp"
  android:textColor="#000000"
  android:layout_height="fill_parent"
  android:layout_width="fill_parent"
  android:gravity="center"/>
</FrameLayout>


LinearLayout
LinearLayout organizes elements along a single line. You specify whether that line is verticle or horizontal using android:orientation. Here is a sample Layout XML using LinearLayout.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
     android:id="@+id/backbutton"
     android:text="Back"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:text="First Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <EditText
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <TextView
     android:text="Last Name"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" />
    <EditText
     android:width="100px"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content" /> 
</LinearLayout>

TableLayout
TableLayout organizes content into rows and columns. The rows are defined in the layout XML, and the columns are determined automatically by Android. This is done by creating at least one column for each element. So, for example, if you had a row with two elements and a row with five elements then you would have a layout with two rows and five columns.
You can specify that an element should occupy more than one column using android:layout_span. This can increase the total column count as well, so if we have a row with two elements and each element has android:layout_span=”3″ then you will have at least six columns in your table.
By default, Android places each element in the first unused column in the row. You can, however, specify the column an element should occupy using android:layout_column.
Here is some sample XML using TableLayout.
<TableLayout 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 xmlns:android="http://schemas.android.com/apk/res/android">
 <TableRow>
  <Button 
      android:id="@+id/backbutton"
      android:text="Back"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 </TableRow>
 <TableRow>
  <TextView
      android:text="First Name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_column="1" />
      <EditText
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
 </TableRow>
 <TableRow>
  <TextView
      android:text="Last Name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_column="1" />
      <EditText
      android:width="100px"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" /> 
 </TableRow>
</TableLayout>

Wednesday, May 16, 2012

assets in Android

Android offers one more directory where you can keep files which also will be included in package. This directory called /assets. The difference between/res and /assets is that Android doesn’t generate IDs for assets content. You need to specify relative path and name for files inside /assets. 


uses-permission

Uses Permission


Syntax

<uses-permission android:name="string" />

contained in
<manifest>
Explanation
Permission which allow to run the application correctly.Manifest file which describe what permissions are used in the android application.



The AndroidManifest.xml File


All android project contains the Manifest file in the root directory,The manifest file which keep the essential details about the application.The Manifest file which explain the following facts:-
  • It keep the application name and Image thump
  • It give the information about the package of the application
  • It mainly provide the components used in the Application
  • And also define the permissions used in the application.
  • It provide the API level of the application.
  • And then manifest file provide the information about the libraries used in the application. 

Android API Levels

Android API Levels

 API which means application program interface.API useful to understand the platform's  approach to API change management. It's also important to understand the API Level identifier and the role it plays in ensuring your application's compatibility with devices on which it may be installed.

What is API Level?
  • It is the core set of packages and classes
  • Set of XML elements and attributes for declaring a manifest file
  • It is set of XML elements and attributes for declaring and accessing resources
  • Set of Intents
  • And also the  set of permissions that applications can request, as well as permission enforcements included in the system

Platform VersionAPI LevelVERSION_CODENotes
Android 4.0.315ICE_CREAM_SANDWICH_MR1Platform Highlights
Android 4.0, 4.0.1, 4.0.214ICE_CREAM_SANDWICH
Android 3.213HONEYCOMB_MR2
Android 3.1.x12HONEYCOMB_MR1Platform Highlights
Android 3.0.x11HONEYCOMBPlatform Highlights
Android 2.3.4
Android 2.3.3
10GINGERBREAD_MR1Platform Highlights
Android 2.3.2
Android 2.3.1
Android 2.3
9GINGERBREAD
Android 2.2.x8FROYOPlatform Highlights
Android 2.1.x7ECLAIR_MR1Platform Highlights
Android 2.0.16ECLAIR_0_1
Android 2.05ECLAIR
Android 1.64DONUTPlatform Highlights
Android 1.53CUPCAKEPlatform Highlights
Android 1.12BASE_1_1
Android 1.01BASE