Tuesday, 11 September 2012

Sim info android source code


package com.umer.cellid;



import java.util.Locale;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.CellLocation;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class OpencellidActivity extends Activity {


String latitude;
 String longitude;

 public class OpenCellID {
  String mcc;  //Mobile Country Code
  String mnc;  //mobile network code
  String cellid; //Cell ID
  String lac;  //Location Area Code
  Boolean error;
  String strURLSent;
  String GetOpenCellID_fullresult;

  public Boolean isError(){
   return error;
  }
 
  public void setMcc(String value){
   mcc = value;
  }
 
  public void setMnc(String value){
   mnc = value;
  }
 
  public void setCallID(int value){
   cellid = String.valueOf(value);
  }
 
  public void setCallLac(int value){
   lac = String.valueOf(value);
  }
 
  public String getLocation(){
   return("latitude: "+latitude + " longitude: " + longitude);
  }
 
  public void groupURLSent(){
   strURLSent =
    "http://www.opencellid.org/cell/get?mcc=" + mcc
    +"&mnc=" + mnc
    +"&cellid=" + cellid
    +"&lac=" + lac
    +"&fmt=txt";
  }
 
  public String getstrURLSent(){
   return strURLSent;
  }
 
  public String getGetOpenCellID_fullresult(){
   return GetOpenCellID_fullresult;
  }
 
  public void GetOpenCellID() throws Exception {
   groupURLSent();
   HttpClient client = new DefaultHttpClient();
   HttpGet request = new HttpGet(strURLSent);
   HttpResponse response = client.execute(request);
   GetOpenCellID_fullresult = EntityUtils.toString(response.getEntity());
   spliteResult();
  }
 
  private void spliteResult(){
   if(GetOpenCellID_fullresult.equalsIgnoreCase("err")){
    error = true;
   }else{
    error = false;
    String[] tResult = GetOpenCellID_fullresult.split(",");
    latitude = tResult[0];
    longitude = tResult[1];
   }
  }
 }

 int myLatitude, myLongitude;
 OpenCellID openCellID;


 TextView textSignal,batteryLevel;
   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
     
       SignalStrengthListener signalStrengthListener;
     
       TextView textGsmCellLocation = (TextView)findViewById(R.id.gsmcelllocation);
       TextView textMCC = (TextView)findViewById(R.id.mcc);
       TextView textMNC = (TextView)findViewById(R.id.mnc);
       TextView textCID = (TextView)findViewById(R.id.cid);
       TextView textLAC = (TextView)findViewById(R.id.lac);
       TextView textGeo = (TextView)findViewById(R.id.geo);
       TextView textRemark = (TextView)findViewById(R.id.remark);
       TextView textImei = (TextView)findViewById(R.id.imei);
       TextView textImsi = (TextView)findViewById(R.id.imsi);
       TextView textGps = (TextView)findViewById(R.id.gps_langlat);
      textSignal = (TextView)findViewById(R.id.signal);
      batteryLevel=(TextView) findViewById(R.id.betry);
     
      Button mapButton=(Button) findViewById(R.id.button1);
 
       //retrieve a reference to an instance of TelephonyManager
       TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
       GsmCellLocation cellLocation = (GsmCellLocation)telephonyManager.getCellLocation();

       String networkOperator = telephonyManager.getNetworkOperator();
       String mcc = networkOperator.substring(0, 3);
       String mnc = networkOperator.substring(3);
       textMCC.setText("mcc: " + mcc);
       textMNC.setText("mnc: " + mnc);
 
       textImei.setText("Imei:  " + getimeinum().toString());
       textImsi.setText("imsi:  " + getimsinum().toString());
     
       int cid = cellLocation.getCid();
       int lac = cellLocation.getLac();
       textGsmCellLocation.setText(cellLocation.toString());
       textCID.setText("gsm cell id: " + String.valueOf(cid));
     textLAC.setText("gsm location area code: " + String.valueOf(lac));
     
       signalStrengthListener = new SignalStrengthListener();        
       ((TelephonyManager)getSystemService(TELEPHONY_SERVICE)).listen(signalStrengthListener,SignalStrengthListener.LISTEN_SIGNAL_STRENGTHS);
     
     
       LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    criteria.setAccuracy(Criteria.ACCURACY_COARSE);
    String bestprovider = locationManager.getBestProvider(criteria, false);
    Location lastknownlocation = locationManager.getLastKnownLocation(bestprovider);
    if(lastknownlocation!=null)
    {
textGps.setText("GPSLocation: Latitude: " + lastknownlocation.getLatitude()+", Longitude: "+ lastknownlocation.getLongitude());
     
    }
   
   
   
    textGeo.setText("APN: " + getapn().toString());
   
   
    this.registerReceiver(this.myBatteryReceiver,
            new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

       openCellID = new OpenCellID();
     
       openCellID.setMcc(mcc);
       openCellID.setMnc(mnc);
       openCellID.setCallID(cid);
       openCellID.setCallLac(lac);
       try {
   openCellID.GetOpenCellID();
 
   if(!openCellID.isError()){
  //  textGeo.setText(openCellID.getLocation());
    textRemark.setText( "\n\n"
      + "URL sent: \n" + openCellID.getstrURLSent() + "\n\n"
      + "response: \n" + openCellID.getLocation()+ "\n\n");
   }else{
    textGeo.setText("Error");
   }
  } catch (Exception e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   textGeo.setText("Exception: " + e.toString());
  }

  mapButton.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

Intent in=new Intent(OpencellidActivity.this, Map.class);

Bundle b=new Bundle();
b.putString("latitude", latitude);
b.putString("longitude", longitude);

in.putExtras(b);
startActivity(in);

}
});

   }

   private BroadcastReceiver myBatteryReceiver
   = new BroadcastReceiver(){
 @Override
 public void onReceive(Context arg0, Intent arg1) {
  // TODO Auto-generated method stub

  if (arg1.getAction().equals(Intent.ACTION_BATTERY_CHANGED)){
   batteryLevel.setText("Battery Level: "
     + String.valueOf(arg1.getIntExtra("level", 0)) + "%");
 
  }

 
   }
   };
 
 
 
 
 
 
 
   public String getimeinum() {
  String deviceID = null;
       String serviceName = Context.TELEPHONY_SERVICE;
       TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);    
      CellLocation re= m_telephonyManager.getCellLocation();    
      GsmCellLocation loc = (GsmCellLocation)m_telephonyManager.getCellLocation();
      String Cell_ID = String.format("%08x ", loc.getCid());
      int deviceType = m_telephonyManager.getPhoneType();
      switch (deviceType) {
            case (TelephonyManager.PHONE_TYPE_GSM):
            break;
            case (TelephonyManager.PHONE_TYPE_CDMA):
            break;
            case (TelephonyManager.PHONE_TYPE_NONE):
            break;
           default:
          break;
      }    
    //  String imsi = m_telephonyManager.getSubscriberId();
      deviceID = m_telephonyManager.getDeviceId();
      return deviceID  ;
   
    }
 
 

   public String getimsinum()
   {
   
       String serviceName = Context.TELEPHONY_SERVICE;
       TelephonyManager m_telephonyManager = (TelephonyManager) getSystemService(serviceName);
       String imsi = m_telephonyManager.getSubscriberId();
return imsi;

}
 
   private class SignalStrengthListener extends PhoneStateListener
   {
    @Override
    public void onSignalStrengthsChanged(android.telephony.SignalStrength signalStrength) {
   
       // get the signal strength (a value between 0 and 31)
       int strengthAmplitude = signalStrength.getGsmSignalStrength();
   
      //do something with it (in this case we update a text view)
       textSignal.setText(" signal strength: "+String.valueOf(strengthAmplitude));
     
    //   signal=String.valueOf(strengthAmplitude);
     
      super.onSignalStrengthsChanged(signalStrength);
    }
 
   }
 
   public String getLocation()
   {
String name = null;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestprovider = locationManager.getBestProvider(criteria, false);
Location lastknownlocation = locationManager.getLastKnownLocation(bestprovider);
Geocoder geocoder = new Geocoder(OpencellidActivity.this, Locale.getDefault());
   if(lastknownlocation!=null)
  {
lastknownlocation.getLatitude();
lastknownlocation.getLongitude();      

  }
    return name;    
   }
 
 
   public String getapn()
   {
  final Uri APN_TABLE_URI = Uri.parse("content://telephony/carriers");


final Uri PREFERRED_APN_URI = Uri.parse("content://telephony/carriers/preferapn");

//receiving cursor to preffered APN table
Cursor c = getContentResolver().query(PREFERRED_APN_URI, null, null, null, null);

//moving the cursor to beggining of the table
c.moveToFirst();

//now the cursor points to the first preffered APN and we can get some
//information about it
//for example first preffered APN id  
int index = c.getColumnIndex("_id");    //getting index of required column
Short id = c.getShort(index);           //getting APN's id from

//we can get APN name by the same way
index = c.getColumnIndex("name");
String name = c.getString(index);

return name;
   }
 
}

Manifest

 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
   <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
   <uses-permission android:name="android.permission.INTERNET"/>


Monday, 3 September 2012

how to extract code of apk file.


step 1:
Download dex2jar here. Create a new java project and paste (dex2jar-0.0.7.11-SNAPSHOT/lib ) jar files .
Copy apk file into  newly created java project
Run it and after refresh the project ,you get jar file .Using java decompiler you can view all java class files
step 2: Download java decompiler here

 One more way


  1. Download Dex2Jar zip from this link :http://code.google.com/p/dex2jar/
  2. Unzip the downloaded zip file.
  3. Open command prompt & write the following command on reaching to directry where dex2jar exe is there and also copy the apk in same directory.
    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)
  4. http://java.decompiler.free.fr/?q=jdgui download decompiler from this link.
  5. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Thursday, 19 July 2012

adroid mapview display multiple locations and on tap change activity

package com.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class NearMapSearch extends MapActivity {
private MapView mapView;
private MapController mc;
String latJson = "", lngJson = "";
String SelectedItem = "";
String path = "";
Spinner selCategary;
String selectedcategary="";
private LocationManager locationManager;
private String provider;
Location location;
double lat,lng;
GeoPoint point;
public ArrayList<HashMap<String, String>> mylist;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.near);
mapView = (MapView) findViewById(R.id.near_mapview);
selCategary=(Spinner) findViewById(R.id.near_selcategary_categary);
mc = mapView.getController();
mapView.setBuiltInZoomControls(true);
ArrayAdapter<CharSequence> selcategaryadapter = ArrayAdapter.createFromResource(this, R.array.sel_categary, android.R.layout.simple_spinner_item);
selcategaryadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
selCategary.setAdapter(selcategaryadapter);
selCategary.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(selCategary.getSelectedItemPosition()!=0)
{
selectedcategary=selCategary.getSelectedItem().toString();
mylist = new ArrayList<HashMap<String, String>>();

path = "ajax.googleapis.com/ajax/services/search/local?v=1.0&q="+ selectedcategary+ "&sll=31.418083,73.077575&rsz=large&start=0";

//** service start and data store in mylist ***
JSONObject json = JSONFunction.getJSONCategaryRes(path);
if (json != null) {
JSONObject Jindex = null;
try { JSONObject responseData = json.getJSONObject("responseData");
JSONArray results = responseData.getJSONArray("results");
for (int i = 0; i < results.length(); i++) {
HashMap<String, String> data = new HashMap<String, String>();
Jindex = results.getJSONObject(i);
data.put("latJson", Jindex.getString("lat").toString());
data.put("lngJson", Jindex.getString("lng").toString());
data.put("city", Jindex.getString("city").toString());
data.put("title", Jindex.getString("title").toString());
data.put("url", Jindex.getString("staticMapUrl").toString());
data.put("streetAddress", Jindex.getString("streetAddress").toString());
mylist.add(data);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//** service end ***
Drawable makerDefault = NearMapSearch.this.getResources().getDrawable(
R.drawable.red_dot);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
point =new GeoPoint((int) ( (31.418083) * 1E6),(int) ((73.077575) * 1E6));
OverlayItem overlayItem = new OverlayItem(point, "fsd", null);
for(int i=0;i<mylist.size();i++)
Double lng=0.0;
Double lat=0.0;
HashMap<String, String> data1=(HashMap<String, String>) mylist.get(i);
lat=Double.parseDouble(data1.get("latJson") );
lng=Double.parseDouble(data1.get("lngJson"));
int lat1=(int)((lat) * 1E6);
int lng1=(int)((lng) * 1E6);
itemizedOverlay.addOverlayItem(lat1,lng1,"abc");
}
mapView.getOverlays().add(itemizedOverlay);
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int)(31.418083 * 1E6), (int)(73.077575 * 1E6)));
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(),
itemizedOverlay.getLonSpanE6());
}
else
{
AlertDialog alertDialog = new AlertDialog.Builder(NearMapSearch.this).create();
alertDialog.setTitle("");
alertDialog.setMessage("Result not found.");
alertDialog.setButton("OK", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
alertDialog.show();
}
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
 
if (location != null)
{
lat = (double) (location.getLatitude());
lng = (double) (location.getLongitude());
}
mapView.setBuiltInZoomControls(true);
point = new GeoPoint( (int) ( (31.418083) * 1E6),(int) ((73.077575) * 1E6));
OverlayItem overlayitem = new OverlayItem(point, "Hello!", "I am here");
final List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.circle);
MItemizedOverlay itemizedoverlay = new MItemizedOverlay(drawable, this);
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
NearMapSearch.this.runOnUiThread(new Runnable() {
public void run() {
mapView.getController().animateTo(point);
}
});
 
}
@Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private class MirItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
@Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
@Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
System.out.println("item index::" + index);
HashMap<String, String> data1=(HashMap<String, String>) mylist.get(index);;
Intent i=new Intent(NearMapSearch.this,BusinessDetail.class);
Bundle b=new Bundle();
b.putString("title", data1.get("title"));
b.putString("city", data1.get("city"));
b.putString("url", data1.get("url"));
b.putString("streetAddress", data1.get("streetAddress"));
i.putExtras(b);
startActivity(i);
return true;
}
}
}

<manifest>
<
uses-permission android:name="android.permission.INTERNET" />uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
</manifest>




<
<
umer;

Using GPS How to get current location Android

public getLocation()
{
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestprovider = locationManager.getBestProvider(criteria,false);
Location lastknownlocation = locationManager.getLastKnownLocation(bestprovider);
Geocoder geocoder = new Geocoder(SignUp.this, Locale.getDefault());
try{

if(lastknownlocation!=null)
{
List<Address> addresses = geocoder.getFromLocation(lastknownlocation.getLatitude(),lastknownlocation.getLongitude(),100);
showToast(addresses.get(0).getAddressLine(0)+", "+addresses.get(0).getAddressLine(1)+", "+addresses.get(0).getCountryName());
}
else{
Toast.makeText(this, "location is not available", 3000).show();
}
}
catch (IOException e)
{
e.printStackTrace();
}

}


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

Wednesday, 11 July 2012

SharedPreferences in android

SharedPreferences prefs;

public static Context context;

context =getApplicationContext();
prefs = PreferenceManager.getDefaultSharedPreferences(context);
//put data in sharedpreference
Editor editor = prefs.edit();
editor.putString(USERNAME_MEM", username11 );
editor.commit();
//get data from sharedpreference
String username= prefs.getString("username", null);
{
// do ur work
}

SplashScreen in android


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class SplashScreen extends Activity
 {
     private Thread mSplashThread;   
     public void onCreate(Bundle savedInstanceState)
      {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.splash);       
          final SplashScreen sPlashScreen = this;  
          mSplashThread =  new Thread()
           {       
               public void run()
                {
                    try
                     {
                      synchronized(this)
                       {
                        wait(1000);                    
                       }
                     }
                    catch(InterruptedException ex)
                     {                   
                     }
                    finish();
                    Intent intent = new Intent();
                    intent.setClass(sPlashScreen, OurWishingWellActivity.class);
                    startActivity(intent);                   
                }
           };       
           mSplashThread.start();       
      }       
     public boolean onTouchEvent(MotionEvent evt)
      {
          if(evt.getAction() == MotionEvent.ACTION_DOWN)
           {
               synchronized(mSplashThread)
                {
                    mSplashThread.notifyAll();
                }
           }
          return true;
      }   
 }

scrolling whole screen including ListView in android


Add this class in ur project
//**** class Utility start****
package com.umer;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
public class Utility
{
public static void setListViewHeightBasedOnChildren(ListView listView)
{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
{
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++)
{
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1))+40;
listView.setLayoutParams(params);
listView.requestLayout();
}
}
//**** class Utility end****
//Add this code where you are using ur adapter
try{
ImageAdapter imageAdapter=new ImageAdapter(MyReg1.this, R.layout.my_reg_list, mylist);
bar.setVisibility(View.INVISIBLE);
list.setAdapter(imageAdapter);
list.setScrollingCacheEnabled(false);
Utility.setListViewHeightBasedOnChildren(list);
}
 
catch(Exception exp){
Log.d("Image Adapter Exception",exp.toString());
}