Thursday, 6 March 2014

how to capture video in andriod with dynamic video QUALITY and get base64


Java CODE.....


package com.example.capturevideo_own;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

@TargetApi(Build.VERSION_CODES.FROYO)
public class MainActivity extends Activity {

private Camera myCamera;
private MyCameraSurfaceView myCameraSurfaceView;
private MediaRecorder mediaRecorder;
Thread thread;
Button myButton;
SurfaceHolder surfaceHolder;
boolean recording;
private Handler progressBarHandler = new Handler();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

recording = false;

setContentView(R.layout.activity_main);

// Get Camera for preview
myCamera = getCameraInstance();
if (myCamera == null) {
Toast.makeText(MainActivity.this, "Fail to get Camera",
Toast.LENGTH_LONG).show();
}

myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
FrameLayout myCameraPreview = (FrameLayout) findViewById(R.id.videoview);
myCameraPreview.addView(myCameraSurfaceView);

myButton = (Button) findViewById(R.id.mybutton);
myButton.setOnClickListener(myButtonOnClickListener);
}

Button.OnClickListener myButtonOnClickListener = new Button.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (recording) {
// stop recording and release camera
mediaRecorder.stop(); // stop the recording
releaseMediaRecorder(); // release the MediaRecorder object


Intent in = new Intent(MainActivity.this, Start_video.class);
startActivity(in);
finish();
} else {

// Release Camera before MediaRecorder start
releaseCamera();









if (!prepareMediaRecorder()) {
Toast.makeText(MainActivity.this,
"Fail in prepareMediaRecorder()!\n - Ended -",
Toast.LENGTH_LONG).show();

}

mediaRecorder.start();
recording = true;
myButton.setText("STOP");




thread = new Thread() {
@Override
public void run() {
try {
while (true) {
sleep(1000);
progressBarHandler.post(new Runnable() {
@SuppressWarnings("deprecation")
public void run() {

if(recording )
{
convert_base64("/sdcard/myvideo.mp4");
}

}
});

}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();


}
}
};

private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}

@SuppressLint("NewApi")
private boolean prepareMediaRecorder() {
myCamera = getCameraInstance();
mediaRecorder = new MediaRecorder();

myCamera.unlock();
mediaRecorder.setCamera(myCamera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

// mediaRecorder.setProfile(CamcorderProfile
// .get(CamcorderProfile.QUALITY_480P));
mediaRecorder.setProfile(CamcorderProfile
.get(CamcorderProfile.QUALITY_LOW));

mediaRecorder.setOutputFile("/sdcard/myvideo.mp4");
mediaRecorder.setMaxDuration(6000000); // Set max duration 60 sec.
mediaRecorder.setMaxFileSize(500000000); // Set max file size 5M

mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder()
.getSurface());

try {
mediaRecorder.prepare();
} catch (IllegalStateException e) {
releaseMediaRecorder();
return false;
} catch (IOException e) {
releaseMediaRecorder();
return false;
}
return true;

}

@Override
protected void onPause() {
super.onPause();
releaseMediaRecorder(); // if you are using MediaRecorder, release it
// first
releaseCamera(); // release the camera immediately on pause event
}

private void releaseMediaRecorder() {
if (mediaRecorder != null) {
mediaRecorder.reset(); // clear recorder configuration
mediaRecorder.release(); // release the recorder object
mediaRecorder = null;
myCamera.lock(); // lock camera for later use
}
}

private void releaseCamera() {
if (myCamera != null) {
myCamera.release(); // release the camera for other applications
myCamera = null;
}
}

public class MyCameraSurfaceView extends SurfaceView implements
SurfaceHolder.Callback {

private SurfaceHolder mHolder;
private Camera mCamera;

public MyCameraSurfaceView(Context context, Camera camera) {
super(context);
mCamera = camera;

// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format,
int weight, int height) {
// If your preview can change or rotate, take care of those events
// here.
// Make sure to stop the preview before resizing or reformatting it.

if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}

// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}

// make any resize, rotate or reformatting changes here

// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();

} catch (Exception e) {
}
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
// The Surface has been created, now tell the camera where to draw
// the preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub

}
}
public void convert_base64(String uri)
{



InputStream inputStream = null;
try {
inputStream = new FileInputStream(uri);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
   while ((bytesRead = inputStream.read(buffer)) != -1) {
   output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
long Size_of_image = (long) ((bytes.length));
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

formatFileSize(Size_of_image);



    //  Toast.makeText(getApplicationContext(), encodedString ,Toast.LENGTH_LONG).show();  
    }
public static String formatFileSize(long size) {
String hrSize = null;

double b = size;
double k = size / 1024.0;
double m = ((size / 1024.0) / 1024.0);
double g = (((size / 1024.0) / 1024.0) / 1024.0);
double t = ((((size / 1024.0) / 1024.0) / 1024.0) / 1024.0);

DecimalFormat dec = new DecimalFormat("0.00");

if (t > 1) {
hrSize = dec.format(t).concat(" TB");
} else if (g > 1) {
hrSize = dec.format(g).concat(" GB");
} else if (m > 1) {
hrSize = dec.format(m).concat(" MB");
} else {
hrSize = dec.format(k).concat(" KB");
}
Log.e("sizeeeee", ""+hrSize);
return hrSize;
}
}


..............................
Start_video.java



package com.example.capturevideo_own;

import android.app.Activity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class Start_video extends Activity {



VideoView videoView;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_video);

videoView = (VideoView) findViewById(R.id.videoView1);

videoView.setVideoPath("/sdcard/myvideo.mp4");
videoView.setMediaController(new MediaController(this));
videoView.start();
}

}

..................................
activity_main.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" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="horizontal" >

        <FrameLayout
            android:id="@+id/videoview"
            android:layout_width="720px"
            android:layout_height="480px" />

        <Button
            android:id="@+id/mybutton"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="REC"
            android:textSize="12dp" />
    </LinearLayout>

</LinearLayout>




............................
start_video.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

 

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" />

</LinearLayout>




..................................
AndroidManifest.xml


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

    <uses-sdk android:minSdkVersion="7" />

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

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name="com.example.capturevideo_own.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
          <activity
            android:name="com.example.capturevideo_own.Start_video"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.NoTitleBar.Fullscreen" >
            </activity>
     
    </application>


</manifest>

Monday, 13 January 2014

MaTlab

HI Friends Matlab software is use for image proceesing, using matlab sofware we create a project using java and createa jar file and that jar file is use in our andriod code, this this the best way for image processing 

Monday, 14 January 2013

Push notification with GCM

Include the library of GCM.jar file in your project

public class GCMIntentService extends GCMBaseIntentService {

    @SuppressWarnings("hiding")
    private static final String TAG = "GCMIntentService";

    public GCMIntentService() {
        super("123456");
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
     private static void generateNotification(Context context, String message)
     {
     int icon = R.drawable.icon;
     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.app_name);
     Intent notificationIntent = new Intent(context, ABCCCC.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, 0);
     notification.setLatestEventInfo(context, title, message, intent);
     notification.flags |= Notification.FLAG_AUTO_CANCEL;
     notificationManager.notify(0, notification);
     }

    @Override
    protected void onError(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }



    @Override
    protected void onMessage(Context arg0, Intent arg1) {
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
        Log.e("GCM", "RECIEVED A MESSAGE");
       
        generateNotification(getApplicationContext(),arg1.getStringExtra("message"));
    }

    @Override
    protected void onRegistered(Context arg0, String regId) {
        // TODO Auto-generated method stub
       
        ConstantData.DEVICETOKEN=regId;
       
        Log.e("MY_APP_TAG", "Registered: " + regId);

    }

    @Override
    protected void onUnregistered(Context arg0, String arg1) {
        // TODO Auto-generated method stub

    }

}







SamplePushActivity extends Application {
    /** Called when the activity is first created. */
public void onCreate() {
            super.onCreate();
            //setContentView(R.layout.main);
           
             try{

                 //User device id...
                TelephonyManager tManager = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
                ConstantData.DEVICEID = tManager.getDeviceId();

                //        Log.e("Device id is:-", uid);
               
                }catch (Exception e) {
                    // TODO: handle exception
                }
           
            try {
                       
            Log.e("IN GCM_SAMPLE_PUSH","aa gaya");
            GCMRegistrar.checkDevice(this);
            GCMRegistrar.unregister(this);
            Log.e("info","unregistereddd....." + GCMRegistrar.getRegistrationId(this));
            GCMRegistrar.checkManifest(this);
            if (GCMRegistrar.isRegistered(this)) {
                Log.e("info", GCMRegistrar.getRegistrationId(this));
               
            }
            final String regId = GCMRegistrar.getRegistrationId(this);
   
            Log.e("REG_ID", regId);
   
            if (regId.equals("")) {
                GCMRegistrar.register(this, "CLENT SIDE ID");
                Log.e("info", GCMRegistrar.getRegistrationId(this));
               
            } else {
                Log.e("info", "already registered as" + regId);
            }
   
           
            } catch (Exception e) {
                // TODO: handle exception
            }
        }

}


make reciver in your manifest file

receiver
android:name="com.google.android.gcm.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />

<category android:name="your project name" />
</intent-filter>
</receiver>

permission in manifest file
internet permission

make service in manifest file
<service android:name=".GCMIntentService" />







Tuesday, 8 January 2013

how to get accurate speed in android



static float[] dist1 = new float[1];

Location location = null;
static LocationManager locationmanager;

static double  avg_distance = 0.0;

locationmanager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

location = locationmanager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null) {
location = locationmanager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location == null) {
location = locationmanager
.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
}
if (location != null) {
pre_Latitude = location.getLatitude();
pre_Lognitude = location.getLongitude();

}

try {
if (pre_lat_long == 2) {
String pre_lat = getSharedPreferences("TEXT", 0)
.getString("prelat", null);
String pre_long = getSharedPreferences("TEXT", 0)
.getString("prelog", null);
pre_Latitude = Double.valueOf(pre_lat);
pre_Lognitude = Double.valueOf(pre_long);
Log.e("locationpp", "" + pre_Latitude + ".."
+ pre_Lognitude);
}
} catch (Exception e) {
// TODO: handle exception
Log.e("error", e.getMessage().toString());
}

Double lat = 0.00, log = 0.00;
if (location != null) {
lat = location.getLatitude();
log = location.getLongitude();
Log.e("loca", "" + lat + ".." + log);
}

if (pre_lat_long == 0) {

pre_Latitude = lat;
pre_Lognitude = log;
pre_lat_long = 2;
}

present_Longitude = log;
present_Latitude = lat;
SharedPreferences shp = getSharedPreferences("TEXT", 0);
final Editor editor = shp.edit();
editor.putString("prelat", "" + lat);
editor.putString("prelog", "" + log);
editor.commit();


Location.distanceBetween(present_Latitude, present_Longitude,
pre_Latitude, pre_Lognitude, dist1);
double miles = dist1[0] * 0.00062137119;
total_times = location.getTime();
distance = distance + miles;
                               String Distance_string_1 = "" + distance;

         avg_distance = ((distance_cover_*3600)/totaltime_in_sec)*0.621371;




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"
    />