This android tutorial is to help learn location based service in android platform. Knowing the current location in an android mobile will pave the way for developing many innovative Android apps to solve peoples daily problem. For developing location aware application in android, it needs location providers. There are two types of location providers,
  1. GPS Location Provider
  2. Network Location Provider

    
  



Network Location Provider vs GPS Location Provider

  • Network Location provider is comparatively faster than the GPS provider in providing the location co-ordinates.
  • GPS provider may be very very slow in in-door locations and will drain the mobile battery.
  • Network location provider depends on the cell tower and will return our nearest tower location.
  • GPS location provider, will give our location accurately.
 
   

Create LocationManager instance as reference to the location service

For any background Android Service, we need to get reference for using it. Similarly, location service reference will be created using getSystemService() method. This reference will be added with the newly created LocationManager instance as follows.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);



Request current location from LocationManager

After creating the location service reference, location updates are requested using requestLocationUpdates() method of LocationManager. For this function, we need to send the type of location provider, number of seconds, distance and the LocationListener object over which the location to be updated.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);



Receive location update from LocationListener on change of location

LocationListener will be notified based on the distance interval specified or the number seconds.






package com.shir60bhushan.gpsLocation;
 
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
 
import android.util.Log;
 
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude; 
protected boolean gps_enabled,network_enabled;
 
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
 
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
 
@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
 
@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
 
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
Xml layout will be As follows

 
    
 




It is very common that you have seen some simple animations in most of the applications in Android. Animations can give better user experience for your applications. In this example, I’ll try to introduce you doing simple animations with Android. It is simple enough that on clicking a button, an images starts rotating from 0 degree to 360 degree in N seconds. Lets begin with the animation XML. Once you have created a new Android project, create a folder named anim in res and a file named rotator.xml inside res/anim.

android:duration="”4000”" 
android:fromdegrees="”0”" 
android:pivotx="”50%”" 
android:pivoty="”50%”"
android:todegrees="”360”" 
android:toyscale="”0.0”" 

Hope the code is pretty self explanatory. Here one complete rotation will be completed in 4000ms (4 seconds). Now add a PNG image that you want to rotate into your drawable folder. Then open res/main.xml, after removing the default textView in the layout, add an ImageView and Button into the layout. Set the src property of the ImageView as your filename of the added image, for example android:src=”@drawable/myimg” Ok, lets edit the main class. In the onClick() for the button, add the necessary code for running the animation. Check the following code.
public class AnimationActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener()    {
            @Override
            public void onClick(View arg0) {
                final ImageView myImage = (ImageView)findViewById(R.id.imageView1);
                final Animation myRotation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotator);
                myImage.startAnimation(myRotation);
            }
        });
    }
}



Blazin Battery Saver



Blazin battery saver Application launched recently which is a battery optimisation tool having sleek look and feel and making plenty of downloads on the google play


https://play.google.com/store/apps/details?id=com.shir60bhushan.blazinbattery&hl=en

have a look on it ,.











Google provides the api for drawing the 3d piechart by just providing simple parameters of the chart one can very easily draw the piechart ,bargraph etc the chart will be displayed in the webview the code is shown bellow








package com.shir60bhushan.piechart;
 
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
 
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
 
public class Android3dPieChartActivity extends Activity {
  
 final static String urlGoogleChart 
  = "http://chart.apis.google.com/chart";
 final static String urlp3Api 
  = "?cht=p3&chs=400x150&chl=A|B|C&chd=t:";
  
 EditText inputA, inputB, inputC;
 Button generate;
 ImageView pieChart;
  
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        inputA = (EditText)findViewById(R.id.adata);
        inputB = (EditText)findViewById(R.id.bdata);
        inputC = (EditText)findViewById(R.id.cdata);
        generate = (Button)findViewById(R.id.generate);
        pieChart = (ImageView)findViewById(R.id.pie);
        generate.setOnClickListener(generateOnClickListener);
    }
     
    Button.OnClickListener generateOnClickListener
    = new Button.OnClickListener(){
 
  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   String A = inputA.getText().toString();
   String B = inputB.getText().toString();
   String C = inputC.getText().toString();
   String urlRqs3DPie = urlGoogleChart 
     + urlp3Api 
     + A + "," + B + "," + C;
    
   Bitmap bm3DPie = loadChart(urlRqs3DPie);
   if(bm3DPie == null){
    Toast.makeText(Android3dPieChartActivity.this,
      "Problem in loading 3D Pie Chart",
      Toast.LENGTH_LONG).show(); 
   }else{
    pieChart.setImageBitmap(bm3DPie); 
   }
  }};
   
 private Bitmap loadChart(String urlRqs){
  Bitmap bm = null;
  InputStream inputStream = null;
   
  try {
   inputStream = OpenHttpConnection(urlRqs);
   bm = BitmapFactory.decodeStream(inputStream);
   inputStream.close(); 
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace(); 
  }
   
  return bm; 
 }
      
 private InputStream OpenHttpConnection(String strURL) throws IOException{
  InputStream is = null;
  URL url = new URL(strURL);
  URLConnection urlConnection = url.openConnection();
        
  try{
   HttpURLConnection httpConn = (HttpURLConnection)urlConnection;
   httpConn.setRequestMethod("GET");
   httpConn.connect();
    
   if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
    is = httpConn.getInputStream();  
   } 
  }catch (Exception ex){
  }
   
  return is;  
 }
}
and the Xml file for this is as follows:


    

        

            

                
            
        

        

            

                
            
        

        

            

                
            
        

        
    




Do you know an android Apk can be completley reverse enginnered to get all source code from it


As the use of the mobile is getting more day by day so security is one of the important concern for mobile software an android application apk can be reverse engineered and we can retrieve whole code from the .apk which is harmful from security point of view so what is the solution for this?
how developer can assure the security of the software,for thisandroid has provided one tool called "progaurd"it is the tool which secures your code in .apk it becomes very very complex to reverse engineer the code


How to implement progaurd ?


Add the following line in that file
proguard.config=proguard.cfg (its default location of file)

If you have moved the location of file then give absolute path as,

proguard.config=/path/to/proguard.cfg

This is how your cfg file will look like.

-injars lib
-libraryjars ../../..//Android/android_sdk_mac_x86/add-ons/addon-google_apis-google-16

-optimizationpasses 5

-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-dontpreverify
-dontnote
-verbose
-optimizations 

!code/simplification/arithmetic,!field/*,!class/merging/*


-dontwarn sun.misc.Unsafe, java.lang.management.ManagementFactory, org.codehaus.jackson.JsonParser, org.json.JSONObject, org.codehaus.jackson.JsonGenerator, org.codehaus.jackson.JsonFactory, com.google.common.collect.MinMaxPriorityQueue



-keep public class * extends android.app.Application

-keep public class com.android.vending.licensing.ILicensingService
-keepclasseswithmembernames class * {
    native;
}

-keepclasseswithmembers class * {


    public(android.content.Context, android.util.AttributeSet);

}

 -keepclasseswithmembers class * {

    public(android.content.Context, android.util.AttributeSet, int);
}

 -keepclassmembers class * extends android.app.Activity {

   public void *(android.view.View);
}

 -keepclassmembers enum * {

    public static **[] values();
    public static ** valueOf(java.lang.String);
}
 -keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;

}



package com.shir60bhushan.excelContacts.About_N_Help;
import com.shir60bhushan.excelContacts.R;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AppRater
{
 private final static String APP_TITLE    = "Battery Saver Widget";
 private final static String APP_PNAME    = "com.batterysaverwidget";
 static Typeface    tf;
 private final static int DAYS_UNTIL_PROMPT  = 3;
 private final static int LAUNCHES_UNTIL_PROMPT = 7;


 public static void app_launched(Context mContext)
 {
  tf = Typeface.createFromAsset(mContext.getAssets(), "Merienda-Regular.ttf");
  SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);

  if(prefs.getBoolean("dontshowagain", false))
  {
   return;
  }

  SharedPreferences.Editor editor = prefs.edit();

  // Increment launch counter
  long launch_count = prefs.getLong("launch_count", 0) + 1;
  editor.putLong("launch_count", launch_count);


 // Get date of first launch

  Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
  if(date_firstLaunch == 0)
  {
   date_firstLaunch = System.currentTimeMillis();
   editor.putLong("date_firstlaunch", date_firstLaunch);
  }


 // Wait at least n days before opening

  if(launch_count >= LAUNCHES_UNTIL_PROMPT)
  {
   if(System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000))
   {
    showRateDialog(mContext, editor);
  }
 editor.commit();
 }

 public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor)
 {
  final Dialog dialog = new Dialog(mContext);

 TextView tvTitle = new TextView(mContext);
  dialog.setTitle(" Rate " + APP_TITLE + "  ");

  LinearLayout ll = new LinearLayout(mContext);
  ll.setOrientation(LinearLayout.VERTICAL);

  TextView tv = new TextView(mContext);
  tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
  tv.setWidth(240);
  tv.setTextColor(Color.WHITE);
  tv.setPadding(4, 0, 4, 10);
  tv.setTypeface(tf);
  ll.addView(tv);


  Button b1 = new Button(mContext);

  //b1.setBackgroundResource(R.drawable.selector_buttons);
  b1.setText("Rate " + APP_TITLE);
  b1.setTypeface(tf, Typeface.BOLD);
 b1.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
    dialog.dismiss();
   }
  });
  ll.addView(b1);

  Button b2 = new Button(mContext);
  b2.setText("Remind me later");
  // b2.setBackgroundResource(R.drawable.selector_buttons);
  b2.setTypeface(tf, Typeface.BOLD);

  b2.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    dialog.dismiss();
   }
  });
  ll.addView(b2);


  Button b3 = new Button(mContext);
  b3.setText("No, thanks");
  //b3.setBackgroundResource(R.drawable.selector_buttons);
  b3.setTypeface(tf, Typeface.BOLD);
  b3.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    if(editor != null)
    {
     editor.putBoolean("dontshowagain", true);
     editor.commit();
    }
    dialog.dismiss();
   }
  });

  ll.addView(b3);
 dialog.setContentView(ll);
  dialog.show();
 }
}package com.shir60bhushan.excelContacts.About_N_Help;
import com.shir60bhushan.excelContacts.R;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class AppRater
{
 private final static String APP_TITLE    = "Battery Saver Widget";
 private final static String APP_PNAME    = "com.batterysaverwidget";
 static Typeface    tf;
 private final static int DAYS_UNTIL_PROMPT  = 3;
 private final static int LAUNCHES_UNTIL_PROMPT = 7;


 public static void app_launched(Context mContext)
 {
  tf = Typeface.createFromAsset(mContext.getAssets(), "Merienda-Regular.ttf");
  SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);

  if(prefs.getBoolean("dontshowagain", false))
  {
   return;
  }

  SharedPreferences.Editor editor = prefs.edit();

  // Increment launch counter
  long launch_count = prefs.getLong("launch_count", 0) + 1;
  editor.putLong("launch_count", launch_count);


 // Get date of first launch

  Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
  if(date_firstLaunch == 0)
  {
   date_firstLaunch = System.currentTimeMillis();
   editor.putLong("date_firstlaunch", date_firstLaunch);
  }


 // Wait at least n days before opening

  if(launch_count >= LAUNCHES_UNTIL_PROMPT)
  {
   if(System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000))
   {
    showRateDialog(mContext, editor);
  }
 editor.commit();
 }

 public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor)
 {
  final Dialog dialog = new Dialog(mContext);

 TextView tvTitle = new TextView(mContext);
  dialog.setTitle(" Rate " + APP_TITLE + "  ");

  LinearLayout ll = new LinearLayout(mContext);
  ll.setOrientation(LinearLayout.VERTICAL);

  TextView tv = new TextView(mContext);
  tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
  tv.setWidth(240);
  tv.setTextColor(Color.WHITE);
  tv.setPadding(4, 0, 4, 10);
  tv.setTypeface(tf);
  ll.addView(tv);


  Button b1 = new Button(mContext);

  //b1.setBackgroundResource(R.drawable.selector_buttons);
  b1.setText("Rate " + APP_TITLE);
  b1.setTypeface(tf, Typeface.BOLD);
 b1.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
    dialog.dismiss();
   }
  });
  ll.addView(b1);

  Button b2 = new Button(mContext);
  b2.setText("Remind me later");
  // b2.setBackgroundResource(R.drawable.selector_buttons);
  b2.setTypeface(tf, Typeface.BOLD);

  b2.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    dialog.dismiss();
   }
  });
  ll.addView(b2);


  Button b3 = new Button(mContext);
  b3.setText("No, thanks");
  //b3.setBackgroundResource(R.drawable.selector_buttons);
  b3.setTypeface(tf, Typeface.BOLD);
  b3.setOnClickListener(new View.OnClickListener()
  {
   public void onClick(View v)
   {
    if(editor != null)
    {
     editor.putBoolean("dontshowagain", true);
     editor.commit();
    }
    dialog.dismiss();
   }
  });

  ll.addView(b3);
 dialog.setContentView(ll);
  dialog.show();
 }
}

RUN COMMAND PROMPT AS ADMINISTRATOR.

1.Locate your debug.keystore file
"C:\Users\bhushan\.android\debug.keystore"

2.Locate keytool.exe in Java\bin folder


C:\Program Files\Java\jre7\bin>keytool -v -list -alias androiddebugkey -keystore C:\Users\bshirsath\.android\debug.keystore -storepass android -keypass android Alias name: androiddebugkey Creation date: Mar 8, 2012 Entry type: PrivateKeyEntry Certificate chain length: 1 Certificate[1]: Owner: CN=Android Debug, O=Android, C=US Issuer: CN=Android Debug, O=Android, C=US Serial number: 1f5b8c95 Valid from: Thu Mar 08 17:51:52 IST 2012 until: Sat Mar 01 17:51:52 IST 2042 Certificate fingerprints: MD5: 6E:E7:47:2E:A7:07:8A:42:77:89:A8:83:C7:A6:53:87 SHA1: 1D:99:2B:0E:D3:2F:DE:12:92:CE:86:EE:5A:D2:99:80:28:F7:B6:22 SHA256: 30:0B:FC:40:7F:57:9F:51:FF:60:94:B9:CE:27:C1:7A:9D:EF:F7:14:C8: 36:B0:E8:F4:11:13:23:B1:67:17:08 Signature algorithm name: SHA256withRSA Version: 3 Extensions: #1: ObjectId: 2.5.29.14 Criticality=false SubjectKeyIdentifier [ KeyIdentifier [ 0000: DF 53 60 E5 59 3A 8C 07 EA E1 A2 3F 00 57 45 DD .S`.Y:.....?.WE. 0010: DF 29 08 BA .).. ] ] C:\Program Files\Java\jre7\bin>



4.Get a key for the Google Maps Android API v1:
https://developers.google.com/maps/documentation/android/v1/maps-api-signup

5.To register for a Google Maps Android API v1 Key, follow these steps:
-->If you don't have a Google account, use the link on the page to set one up.
-->Paste the MD5 key
-->Click "Generate API Key"


Generated key:0kVayCORItzMtF85IkONrJY0ECuVYdTcAuUE4HQ


6.Add API KEY to your application's MapView objects:

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:enabled="true"
android:clickable="true"
android:apiKey="EXAMPLE_MAPS_API_KEY_STRING" />

 7.Add

package="com.example.package.name">
...


...


8.Sign your application with the certificate that corresponds to the Maps API Key referenced in your MapView elements.

Hello Friends
These are some of the interesting Android phone's secret codes which gives you system ,firmware,hardware,network etc related information




Android Phone Information Secret Code: *#*#4636#*#*

To get the information of your phone and battery. including Phone information, Battery information, Battery history, and Usage statistics.



Android Phone WLAN, GPS and Bluetooth Test Secret Codes:

*#*#232339#*#* OR *#*#526#*#* OR *#*#528#*#* ¨C WLAN test (Use "Menu" button to start various tests)

*#*#232338#*#* ¨C Shows WiFi MAC address

*#*#1472365#*#* ¨C GPS test

*#*#1575#*#* ¨C Another GPS test

*#*#232331#*#* ¨C Bluetooth test

*#*#232337#*# ¨C Shows Bluetooth device address

Android Phone GTalk Secret Codes: *#*#8255#*#*

It can be used to launch GTalk Service Monitor.


Android Phone Camera Information Secret Code: *#*#34971539#*#*

It is used to get information about the camera. It includes following 4 menus: Update camera firmware in image, Update camera firmware in SD card, Get camera firmware version, and Get firmware update count. You should never use the first option otherwise your phone camera may stop working, and there is really no reason to update the camera firmware anyway.





Android Phone Reset Secret Code: *#*#7780#*#*

To reset your Android phone back to factory data. It will delete the things including Google account settings stored in your phone, System and application data and settings, and Downloaded applications too. I wont delete, including current system software, bundled applications, SD card files e.g. photos, music files.

Android Phone Factory Format Secret Code: *2767*3855#

It is used for factory format, which will delete all files and settings, including the internal memory storage. It will also reinstall the firmware.


Android Phone Firmware version information Secret Codes:

*#*#4986*2650468#*#* ¨C PDA, Phone, H/W, RFCallDate

*#*#1234#*#* ¨C PDA and Phone

*#*#1111#*#* ¨C FTA SW Version

*#*#2222#*#* ¨C FTA HW Version

*#*#44336#*#* - PDA, Phone, CSC, Build Time, Changelist number

Android Phone Factory Tests Secret Codes:

*#*#0283#*#* ¨C Packet Loopback

*#*#0*#*#* ¨C LCD test

*#*#0673#*#* OR *#*#0289#*#* ¨C Melody test

*#*#0842#*#* ¨C Device test (Vibration test and BackLight test)

*#*#2663#*#* ¨C Touch screen version

*#*#2664#*#* ¨C Touch screen test

*#*#0588#*#* ¨C Proximity sensor test

*#*#3264#*#* ¨C RAM version


Android Phone Secret Code: *#*#7594#*#*

It will change the "End Call / Power" button action on your phone. By default, if you long press the button, it shows a screen asking you to select any option from Silent mode, Airplane mode and Power off. You can change this action using this code. You can enable direct power off on this button so you don't need to waste your time in selecting the option.

Android Phone Backup Secret Code: *#*#273283*255*663282*#*#*

It opens a File copy screen where you can backup your media files e.g. Images, Sound, Video and Voice memo.

Android Phone Service mode Secret Code: *#*#197328640#*#*

It can be used to enter into Service mode. You can run various tests and change settings in the service mode.




Step 1: Create an XML in the drawable folder and name it selected_item.xml (or any another name you want but to be suggestive). The code in this xml will be:

<shape android="http://schemas.android.com/apk/res/android" shape="rectangle"><br /> <solid color="#80000000"><br /> </solid></shape>



The color="#80000000" is transparent black.
Step 2: Create an XML again, in the drawable folder an name it not_selected.xml. The code in this xml will be:


<shape android="http://schemas.android.com/apk/res/android" shape="rectangle">
<solid color="#80ffffff">
</solid></shape>


The color="#80ffffff" is transparent white.

Step 3 Create an XML again :) in the drawable folder and name it button_selector.xml. The code in this xml will be:

<selector android="http://schemas.android.com/apk/res/android">
<item drawable="@drawable/selected" state_focused="false" state_pressed="true">
<item drawable="@drawable/not_selected">
</item></item></selector>


Step 4 In the xml file where you make the button put this:

android:background="@drawable/button_selector"


AlarmManager class provides access to the system alarm services. These allow you to schedule your application to be run at some point in the future. When an alarm goes off, the Intent that had been registered for it is broadcast by the system, automatically starting the target application if it is not already running. 

In this exercise, a scheduled alarm of 10 seconds will start a service, MyAlarmService. 



 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="@string/hello"

/>

<Button

android:id="@+id/startalarm"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Start"

/>

<Button

android:id="@+id/cancelalarm"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Cancel"

/>
</LinearLayout>
AndroidAlarmService.java, the main activity

package com.shir60bhushan.AndroidAlarmService;



import java.util.Calendar;



import android.app.Activity;

import android.app.AlarmManager;

import android.app.PendingIntent;

import android.content.Intent;

import android.os.Bundle;

import android.os.SystemClock;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;



public class AndroidAlarmService extends Activity {



private PendingIntent pendingIntent;





/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Button buttonStart = (Button)findViewById(R.id.startalarm);

    Button buttonCancel = (Button)findViewById(R.id.cancelalarm);



    buttonStart.setOnClickListener(new Button.OnClickListener(){



 @Override

 public void onClick(View arg0) {

  // TODO Auto-generated method stub



  Intent myIntent = new Intent(AndroidAlarmService.this, MyAlarmService.class);

  pendingIntent = PendingIntent.getService(AndroidAlarmService.this, 0, myIntent, 0);



           AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);



           Calendar calendar = Calendar.getInstance();

           calendar.setTimeInMillis(System.currentTimeMillis());

           calendar.add(Calendar.SECOND, 10);

           alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

       

  Toast.makeText(AndroidAlarmService.this, "Start Alarm", Toast.LENGTH_LONG).show();

 }});



    buttonCancel.setOnClickListener(new Button.OnClickListener(){



 @Override

 public void onClick(View arg0) {

  // TODO Auto-generated method stub

  AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

  alarmManager.cancel(pendingIntent);



           // Tell the user about what we did.

           Toast.makeText(AndroidAlarmService.this, "Cancel!", Toast.LENGTH_LONG).show();

 }});
}
}




this the MyAlarmService.java service for managing and  triggering the alarm


package com.Shir60bhushan.AndroidAlarmService;



import android.app.Service;

import android.content.Intent;

import android.os.IBinder;

import android.widget.Toast;



public class MyAlarmService extends Service {



@Override

public void onCreate() {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();

}



@Override

public IBinder onBind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();

return null;

}



@Override

public void onDestroy() {

// TODO Auto-generated method stub

super.onDestroy();

Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG).show();

}



@Override

public void onStart(Intent intent, int startId) {

// TODO Auto-generated method stub

super.onStart(intent, startId);

Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();

}



@Override

public boolean onUnbind(Intent intent) {

// TODO Auto-generated method stub

Toast.makeText(this, "MyAlarmService.onUnbind()", Toast.LENGTH_LONG).show();

return super.onUnbind(intent);

}
}



Finally Add the service declaration in the manifest file of the application

<service android:name=".MyAlarmService" />



package com.shir60bhushan.excelContacts.About_N_Help; import com.shir60bhushan.excelContacts.R; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.Typeface; import android.net.Uri; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class AppRater { private final static String APP_TITLE = "Battery Saver Widget"; private final static String APP_PNAME = "com.batterysaverwidget"; static Typeface tf; private final static int DAYS_UNTIL_PROMPT = 3; private final static int LAUNCHES_UNTIL_PROMPT = 7;
public static void app_launched(Context mContext) { tf = Typeface.createFromAsset(mContext.getAssets(), "Merienda-Regular.ttf"); SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0); if(prefs.getBoolean("dontshowagain", false)) { return; } SharedPreferences.Editor editor = prefs.edit(); // Increment launch counter long launch_count = prefs.getLong("launch_count", 0) + 1; editor.putLong("launch_count", launch_count); // Get date of first launch Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0); if(date_firstLaunch == 0) { date_firstLaunch = System.currentTimeMillis(); editor.putLong("date_firstlaunch", date_firstLaunch); } // Wait at least n days before opening if(launch_count >= LAUNCHES_UNTIL_PROMPT) { if(System.currentTimeMillis() >= date_firstLaunch + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) { showRateDialog(mContext, editor); } editor.commit(); } public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) { final Dialog dialog = new Dialog(mContext); TextView tvTitle = new TextView(mContext); dialog.setTitle(" Rate " + APP_TITLE + "  "); LinearLayout ll = new LinearLayout(mContext); ll.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(mContext); tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!"); tv.setWidth(240); tv.setTextColor(Color.WHITE); tv.setPadding(4, 0, 4, 10); tv.setTypeface(tf); ll.addView(tv); Button b1 = new Button(mContext); //b1.setBackgroundResource(R.drawable.selector_buttons); b1.setText("Rate " + APP_TITLE); b1.setTypeface(tf, Typeface.BOLD); b1.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME))); dialog.dismiss(); } }); ll.addView(b1); Button b2 = new Button(mContext); b2.setText("Remind me later"); // b2.setBackgroundResource(R.drawable.selector_buttons); b2.setTypeface(tf, Typeface.BOLD); b2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); ll.addView(b2); Button b3 = new Button(mContext); b3.setText("No, thanks"); //b3.setBackgroundResource(R.drawable.selector_buttons); b3.setTypeface(tf, Typeface.BOLD); b3.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if(editor != null) { editor.putBoolean("dontshowagain", true); editor.commit(); } dialog.dismiss(); } }); ll.addView(b3); dialog.setContentView(ll); dialog.show(); } }








1. Make the SQLite database file.

If you don't have a sqlite manager I recommend you to download the opensource SQLite Database Browser available for Win/Linux/Mac. Make database file.

2. Use this database in your Android application.

Now put your database file in the "assets" folder of your project and create a Database Helper class by extending the SQLiteOpenHelper class
public class Databasehelper extends SQLiteOpenHelper
{
      private SQLiteDatabase myDataBase;
      private final Context myContext;
      private static final String DATABASE_NAME = "db.sqlite";
      public final static String DATABASE_PATH ="/data/data/com.shir60bhushan/databases/";
      public static final int DATABASE_VERSION = 1;
      //public static final int DATABASE_VERSION_old = 1;

      //Constructor
      public Databasehelper(Context context)
      {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            this.myContext = context;
      }

      //Create a empty database on the system
      public void createDatabase() throws IOException
      {
            boolean dbExist = checkDataBase();

            if(dbExist)
            {
                  Log.v("DB Exists", "db exists");
                  // By calling this method here onUpgrade will be called on a
                  // writeable database, but only if the version number has been
                  // bumped
                  //onUpgrade(myDataBase, DATABASE_VERSION_old, DATABASE_VERSION);
            }
           
            boolean dbExist1 = checkDataBase();
            if(!dbExist1)
            {
                  this.getReadableDatabase();
                  try
                  {
                        this.close();    
                        copyDataBase();
                  }
                  catch (IOException e)
                  {
                        throw new Error("Error copying database");
               }
            }
      }

      //Check database already exist or not
      private boolean checkDataBase()
      {
            boolean checkDB = false;
            try
            {
                  String myPath = DATABASE_PATH + DATABASE_NAME;
                  File dbfile = new File(myPath);
                  checkDB = dbfile.exists();
            }
            catch(SQLiteException e)
            {
            }
            return checkDB;
      }

      //Copies your database from your local assets-folder to the just created empty database in the system folder
      private void copyDataBase() throws IOException
      {
            String outFileName = DATABASE_PATH + DATABASE_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            InputStream myInput = myContext.getAssets().open(DATABASE_NAME);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0)
            {
                  myOutput.write(buffer, 0, length);
            }
            myInput.close();
            myOutput.flush();
            myOutput.close();
      }

      //delete database
      public void db_delete()
      {
            File file = new File(DATABASE_PATH + DATABASE_NAME);
            if(file.exists())
            {
                  file.delete();
                  System.out.println("delete database file.");
            }
      }

      //Open database
      public void openDatabase() throws SQLException
      {
            String myPath = DATABASE_PATH + DATABASE_NAME;
            myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
      }

      public synchronized void closeDataBase()throws SQLException
      {
            if(myDataBase != null)
                  myDataBase.close();
            super.close();
      }

      public void onCreate(SQLiteDatabase db)
      {
      }

      public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
      {    
            if (newVersion > oldVersion)
            {
                  Log.v("Database Upgrade", "Database version higher than old.");
                  db_delete();
            }
      }

 //add your public methods for insert, get, delete and update data in database.
}


Now you can create a new instance of this DataBaseHelper class and call the createDataBase() and openDataBase() methods. Remember to change the "YOUR_PACKAGE" to your application package namespace (i.e: com.examplename.myapp) in the DB_PATH string.


DataBaseHelper myDbHelper = new DataBaseHelper();
      myDbHelper = new DataBaseHelper(this);
      try {
            myDbHelper.createDataBase();

      } catch (IOException ioe) {

            throw new Error("Unable to create database");
      }
     
      try {      
            myDbHelper.openDataBase();

      }catch(SQLException sqle){

            throw sqle;
      }