Tuesday 9 October 2012

Check Sms status in android

 
 
 
public void sendSMS(String phoneNumber, String message)

{

String SENT =
"SMS_SENT";

String DELIVERED =
"SMS_DELIVERED";

 

PendingIntent sentPI = PendingIntent.getBroadcast(
this, 0,

new Intent(SENT), 0);

 

PendingIntent deliveredPI = PendingIntent.getBroadcast(
this, 0,

new Intent(DELIVERED), 0);

 

//---when the SMS has been sent---

registerReceiver(
new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch (getResultCode())

{

case Activity.RESULT_OK:

Toast.makeText(getBaseContext(),
"SMS sent",

Toast.
LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_GENERIC_FAILURE:

Toast.makeText(getBaseContext(),
"Your No. is not Register",

Toast.
LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NO_SERVICE:

Toast.makeText(getBaseContext(),
"No service",

Toast.
LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_NULL_PDU:

Toast.makeText(getBaseContext(),
"Null PDU",

Toast.
LENGTH_SHORT).show();

break;

case SmsManager.RESULT_ERROR_RADIO_OFF:

Toast.makeText(getBaseContext(),
"Radio off",

Toast.
LENGTH_SHORT).show();

break;

}

}

},
new IntentFilter(SENT));

 

//---when the SMS has been delivered---

registerReceiver(
new BroadcastReceiver(){

@Override

public void onReceive(Context arg0, Intent arg1) {

switch (getResultCode())

{

case Activity.RESULT_OK:

Toast.makeText(getBaseContext(),
"SMS delivered",

Toast.
LENGTH_SHORT).show();

break;

case Activity.RESULT_CANCELED:

Toast.makeText(getBaseContext(),
"SMS not delivered",

Toast.
LENGTH_SHORT).show();

break;

}

}

},
new IntentFilter(DELIVERED));

 

SmsManager sms = SmsManager.getDefault();

sms.sendTextMessage(phoneNumber,
null, message, sentPI, deliveredPI);

}

Media player


String file = Environment.getExternalStorageDirectory().getAbsolutePath();

String sound = file+"/loop.mp3";

"/loop.mp3";

Log.e(

"12", ""+sound);



//System.out.println("Before Allocation file is: "+file);



//rePlay.setText("Stop");



mPlayer = new MediaPlayer();



try


{


mPlayer.setDataSource(sound);




mPlayer.prepare();




mPlayer.start();


}


catch (Exception e)


{

Log.e(

"c", "prepare() failed");

}

Get json array by using get or post Request


 


 


public static void CopyStream(InputStream is, OutputStream os)



throws Exception {



final int buffer_size = 1024;



byte[] bytes = new byte[buffer_size];



for (;;) {



int count = is.read(bytes, 0, buffer_size);



if (count == -1)



break;


os.write(bytes, 0, count);

}

}



 


public static String makePostRequest(String url,


List<NameValuePair> nvp) {

Log.e(url,

"");


String result =

"";



try {


HttpClient client =

new DefaultHttpClient();


HttpPost post =

new HttpPost(url);


post.setEntity(

new UrlEncodedFormEntity(nvp));


HttpResponse httpResponse = client.execute(post);

HttpEntity httpEntity = httpResponse.getEntity();




if (httpEntity != null) {


InputStream inputStream = httpEntity.getContent();

result = convertStreamToString(inputStream);

inputStream.close();

client =

null;


post.abort();

}

}

catch (Exception e) {


Log.e(

"ee", ""+e.getMessage());


e.printStackTrace();

}


return result;


}



 


public static String makePostRequest1(String url,


List<NameValuePair> nameValuePair) {

String result =

null;



try {


HttpClient httpclient =

new DefaultHttpClient();


HttpPost httppost =

new HttpPost(url);


httppost.setEntity(

new UrlEncodedFormEntity(nameValuePair));



//Log.e("httppost", ""+httppost);



if (httppost != null) {


HttpResponse response = httpclient.execute(httppost);

Log.e(

"response", ""+response);



if (response != null) {


InputStream is = response.getEntity().getContent();

result = convertStreamToString(is);

is.close();

}

httpclient =

null;


httppost.abort();

}


}

catch (SocketException e) {


}

catch (UnknownHostException e) {


}

catch (Exception e) {



//Log.e("ee111", ""+e.getMessage());


}

catch (Error e) {



//Log.e("ee", ""+e.getMessage());



// TODO: handle exception


}


return result;


}




public static String getJSONData(String url) throws Exception {


Log.d(

"url ", ""+url);


String result =

"";


{

HttpClient httpClient =

new DefaultHttpClient();


HttpGet httpGet =

new HttpGet(url);


HttpResponse httpResponse = httpClient.execute(httpGet);

HttpEntity httpEntity = httpResponse.getEntity();


if (httpEntity != null) {


InputStream inputStream = httpEntity.getContent();

result = convertStreamToString(inputStream);

inputStream.close();

httpClient =

null;


httpGet.abort();

}


return result;


}

}




private static String convertStreamToString(InputStream is)



throws Exception {


BufferedReader reader =

new BufferedReader(new InputStreamReader(is));


StringBuilder sb =

new StringBuilder();


String line =

null;



while ((line = reader.readLine()) != null) {


sb.append(line +

"\n");


}

is.close();

reader.close();


//Log.e("sb",""+sb.toString());



return sb.toString();

}

Thursday 5 July 2012

How to make Widget

ButtonWidget.java          class


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class ButtonWidget extends AppWidgetProvider {

public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Toast.makeText(context, "onUpdate", Toast.LENGTH_SHORT).show();

RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent configIntent = new Intent(context, ClickOneActivity.class);
configIntent.setAction(ACTION_WIDGET_CONFIGURE);

Intent active = new Intent(context, ButtonWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("msg", "Message for Button 1");

//PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, configIntent, 0);

//remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.button_two, configPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}

@Override
public void onReceive(Context context, Intent intent) {
   
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noty = new Notification(R.drawable.icon, "Button 1 clicked", System.currentTimeMillis());

noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
notificationManager.notify(1, noty);

} else {
// do nothing
}

super.onReceive(context, intent);
}
}
}



ClickOneActivity.java         Our activity(main Activity)



public class ClickOneActivity  extends Activity {

//flag to detect flash is on or off
private boolean isLighOn = false;

private Camera camera;

private Button button;
RelativeLayout Rv;
ImageView im;




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

}


main.xml(Layout)



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="150dip"
    android:layout_height="40dip"
    android:layout_gravity="center"
    android:orientation="horizontal" >





    <Button
        android:id="@+id/button_two"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_gravity="center_horizontal|center"
        android:background="@drawable/appicon" />


</LinearLayout>




main1.xml(Layout)



<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/background" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:background="@drawable/bottom_glow_red" />


    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/imageView1"
        android:layout_centerHorizontal="true"
        android:background="@drawable/button_off" />


</RelativeLayout>










manifest file



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


    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    
    <application android:icon="@drawable/appicon" android:label="@string/app_name">


<!-- Broadcast Receiver that will process AppWidget updates -->
        <receiver android:name="com.karan.torch.ButtonWidget" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <!-- Broadcast Receiver that will also process our self created action -->
<action android:name="com.karan.torch.ButtonWidget.ACTION_WIDGET_RECEIVER"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/button_widget_provider" />
        </receiver>


<!-- this activity will be called, when we fire our self created ACTION_WIDGET_CONFIGURE -->
<activity android:name="com.karan.torch.ClickOneActivity">
   
   
    <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
<intent-filter>
<action android:name="com.karan.torch.ButtonWidget.ACTION_WIDGET_CONFIGURE"/>
</intent-filter>
</activity>


    </application>
    <uses-sdk android:minSdkVersion="3" />
    

</manifest>









button_widget_provider.xml (In res/xml/button_widget_provider.xml)



<?xml version="1.0" encoding="utf-8"?>
<!-- 
AppWidget default settings:
- setting width and hight
- setting update periode to 1 second
- setting the initialLayout to layout/widget_text.xml
-->


<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="146dip"
    android:minHeight="72dip"
    android:updatePeriodMillis="0"
    android:initialLayout="@layout/main1"
    />











Tuesday 3 July 2012

Torch in andriod

public class FlashLightActivity extends Activity {

    //flag to detect flash is on or off
    private boolean isLighOn = false;

    private Camera camera;

    private Button button;

    @Override
    protected void onStop() {
        super.onStop();

        if (camera != null) {
            camera.release();
        }
    }

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

        button = (Button) findViewById(R.id.buttonFlashlight);

        Context context = this;
        PackageManager pm = context.getPackageManager();

        // if device support camera?
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e("err", "Device has no camera!");
            return;
        }

        camera = Camera.open();
        final Parameters p = camera.getParameters();

        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if (isLighOn) {

                    Log.i("info", "torch is turn off!");
                    Toast.makeText(getApplicationContext(), "torch is turn off!", Toast.LENGTH_SHORT).show();
                    p.setFlashMode(Parameters.FLASH_MODE_OFF);
                    camera.setParameters(p);
                    camera.stopPreview();
                    isLighOn = false;

                } else {

                    Log.i("info", "torch is turn on!");
                    Toast.makeText(getApplicationContext(), "torch is turn on!", Toast.LENGTH_SHORT).show();
                    p.setFlashMode(Parameters.FLASH_MODE_TORCH);

                    camera.setParameters(p);
                    camera.startPreview();
                    isLighOn = true;

                }

            }
        });

    }
}





main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <Button
        android:id="@+id/buttonFlashlight"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
           android:layout_centerVertical="true"
           android:layout_centerHorizontal="true"
        android:text="Torch" />

</RelativeLayout>






Wednesday 27 June 2012

CountDownTimer in andriod


class timess extends CountDownTimer {
public timess(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}

@Override
public void onFinish() {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "hello", 10000).show();
}
//on Tick method is call Every time
@Override
public void onTick(long millisUntilFinished) {
delay = delay + 1;
if (delay > 3) {
second = second + 1;
}
if (second == 60) {
minute = minute + 1;
second = 0;
}

// TODO Auto-generated method stub
}
}

How to call Countdown timmer class in activity...........


"timess" is the name of that class which is extend by countdowntimer 



timess tm = new timess(1000000000, 1000);
tm.start();



Services in andriod


public class Myserviceclass extends Service {
private static final String TAG = "MyService";

double d;
public String mPhoneNumber, loc, unicode, datalatitute, datalognitute,
dataunicode, datatiming, timming, ourNumber, sDeviceID, phnno,
mint, hr, sec, Answer_id;
int Dataid, countQuestion = 1, second = 0, minute = 0, hours = 0,
delay = 0, quesno = 2;
double latitude, longitude, datalognitute1, datalatitute1;
// ParsingN pn;
Timer t;

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

@Override
public void onCreate() {

Log.d(TAG, "onCreate");
}
// Start method is call.................Every time when service is run in back ground
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy");
}

@Override
public void onStart(Intent intent, int startid) {

Log.d(TAG, "onStart");



LocationManager locationmanager = (LocationManager)                     getSystemService(Context.LOCATION_SERVICE);
Location location2 = locationmanager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.i("ccc", "" + location2);
Location location1 = locationmanager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location1 != null) {
latitude = location1.getLatitude();
longitude = location1.getLongitude();
Log.d("testing1111", "" + latitude + "kkk" + longitude);
loc = "" + longitude + "+" + "" + latitude;
} else {
Log.d("testing1111", "testing fail");
}

Toast.makeText(getApplicationContext(), "" + loc, 20000).show();
// //////// GETTING UNIQUE CODE AND PHONE NO FROM WEBSERVICE
if (Geocoder.isPresent()) {
/*Getparsing obj = new Getparsing(
"http://192.168.3.24/phpnewebservice/phonewebservice.php?user=1");*/
Getparsing obj = new Getparsing(
"http://192.168.3.24/phpnewebservice/phonewebservice.php?user=1");
Log.i("kkkk", "" + Geocoder.isPresent());
} else {
Toast.makeText(getApplicationContext(), "wait......",
Toast.LENGTH_LONG).show();
}
Log.i("karan11", "soni");
Log.i("karan222", "soni");
SitesList sitesList = new SitesList();
sitesList = MyXMLHandler.sitesList;
Log.i("size", "" + sitesList.getPhn_ID().size());
for (int i = 0; i < sitesList.getPhn_no().size(); i++) {
Log.i("getting no", "" + sitesList.getPhn_no().get(i));
}
for (int i = 0; i < sitesList.getPhn_ID().size(); i++) {
Log.i("getting id", "" + sitesList.getPhn_ID().get(i));
}
for (int i = 0; i < sitesList.getCode().size(); i++) {
Log.i("getting c", "" + sitesList.getCode().get(i));
}
TelephonyManager mTelephonyMgr = (TelephonyManager) this
.getSystemService(Context.TELEPHONY_SERVICE);
ourNumber = mTelephonyMgr.getLine1Number();
sDeviceID = mTelephonyMgr.getDeviceId();
int N = sitesList.getPhn_no().indexOf(ourNumber);
int PID = sitesList.getPhn_ID().indexOf(sDeviceID);
unicode = sitesList.getCode().get(PID);
Log.i("NN", "" + N);
Log.i("unicode", "" + unicode);
if (Geocoder.isPresent()) {

Log.i("kkkk", "" + Geocoder.isPresent());
}
if (!Geocoder.isPresent()) {

Log.i("kkkk", "" + Geocoder.isPresent());

}
}


}

Tuesday 12 June 2012

how to send message or ACTION_SENDTO


Uri uri = Uri.parse("smsto:"+mainArrayList_phno.get(position));  
   Intent it = new Intent(Intent.ACTION_SENDTO, uri);  
   it.putExtra("sms_body", ""+password);  
   startActivity(it);

how to get CONTENT no. from phone


Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
 String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
 String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
 name_array_list.add(name);
 phone_no_array_list.add(phoneNumber);
}
phones.close();

how to draw line between two latitude and two lognitute


public class Route_mapActivity extends MapActivity {

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

private List mapOverlays;
private Projection projection;
private MapController mc;
private MapView mapView;
private GeoPoint gP;

// private GeoPoint gP2;

private MyOverlay myoverlay;
double my_Latitude, friend_latitude;
double my_Longitude, friend_Longitude;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview);
mapView = (MapView) findViewById(R.id.mapview);// Creating an instance
// of MapView
mapView.setBuiltInZoomControls(true);// Enabling the built-in Zoom
// Controls
gP = new GeoPoint(33695043, 73000000);// Creating a GeoPoint
mc = mapView.getController();
mc.setCenter(gP);
mc.setZoom(9);// Initializing the MapController and setting the map to
// center at the

// defined GeoPoint
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
myoverlay = new MyOverlay();
mapOverlays.add(myoverlay);

}

@Override
protected boolean isRouteDisplayed() {

// TODO Auto-generated method stub

return false;

}

class MyOverlay extends Overlay {

public MyOverlay() {
}

public void draw(Canvas canvas, MapView mapv, boolean shadow) {
super.draw(canvas, mapv, shadow);
// Configuring the paint brush

Point screenPts = new Point();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(4);

my_Latitude = getIntent().getExtras().getDouble("my_Latitude");
my_Longitude = getIntent().getExtras().getDouble("my_Longitude");
friend_latitude = getIntent().getExtras().getDouble("friend_lati");
friend_Longitude = getIntent().getExtras().getDouble("friend_longni");

Log.e("my_Latitude1E6", "" + ((int) (my_Latitude * 1000000)));
GeoPoint gP1 = new GeoPoint((int) (my_Latitude * 1000000),
((int) my_Longitude * 1000000));// starting point Abbottabad
GeoPoint gP2 = new GeoPoint(
(int) (friend_latitude * 1000000 + 1000000),
((int) friend_Longitude * 1000000 + 1000000));// End point
// Islamabad

Point p1 = new Point();
Point p2 = new Point();
Path path1 = new Path();
Point p3 = new Point();
Point p4 = new Point();
Path path2 = new Path();
projection.toPixels(gP2, p3);
projection.toPixels(gP1, p4);
path1.moveTo(p4.x, p4.y);// Moving to Abbottabad location
path1.lineTo(p3.x, p3.y);// Path till Islamabad
/*
* projection.toPixels(gP3, p1);
*
* projection.toPixels(gP4, p2);
*/
path2.moveTo(p2.x, p2.y);// Moving to Islamabad location
path2.lineTo(p1.x, p1.y);// Path to Rawalpindi
canvas.drawPath(path1, mPaint);// Actually drawing the path from
// Abbottabad to Islamabad
canvas.drawPath(path2, mPaint);// Actually drawing the path from
// Islamabad to Rawalpindi

}

}

}