[APP] Floating Camera [v1.000.00.1r][4.0.+][Tutorial][SourceCode]

Geeks Empire

Senior Member
Aug 29, 2014
1,200
1,252
153
Nashville
GeeksEmpire.net

Free to Take Quick Picture Over other Apps

/*
* This is Camera Application in Overlay Window (Floating View)
* that Allow users to move app around screen & also use another apps in background

*/

Current Feature;
+ Switch (Switch Camera Back/Front)
(There is 3 options in menu)
+ Focus (Apply Auto Focus to Clear View)
+ Torch (Turn On the flash)
+ Close
+ More Feature Coming Soon...

NOTE: There is auto mode bind in capture process; Auto-Focus, Auto-Flash, Auto-Scene
So just need to launch the app and capture...
NOTE: I will release it on Geeks Empire account on Google Play Store asap.


### Let Start Coding ###
What you need is ability to create Hello World! project ;)
& By Reading this Tutorial & Use SourceCode you will learn How to Make;
Camera + Services + Overlay Windows + File I/O + Popup Menu & etc.

- from Bottom to Top
* First of All you need to set Permissions & declare classes in Manifest.xml

Code:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.FLASHLIGHT"/>
<uses-feature android:name="android.hardware.camera"
 	      android:required="true" />
<!-- This permission is for Overlay Window -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
* Now you need to declare 2 Services & 2 Classes (Check Source Code)
Services are for Back/Front Camera View
Classes are for controlling as helper

* Then you need to add required components into layouts
To Add Camera View you need to define FrameLayout in layout & some Buttons as Shutter, Switch & Menu. (Check Source Code)
to have more control I made two layouts for Back/Front Camera View.
Code:
...
<FrameLayout
	android:id="@+id/previewFrame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true" />
<Button 
        android:id="@+id/menumode"
        android:layout_width="15dp"
	    android:layout_height="40dp"
	    android:paddingLeft="3dp"
	    android:paddingRight="3dp"
	    android:layout_marginTop="2dp"
	    android:layout_marginRight="8dp"
	    android:layout_alignParentRight="true"
	    android:layout_alignParentTop="true"
        android:background="@drawable/ic_menu_more" />
	
	<Button 
	    android:id="@+id/capture"
	    android:layout_width="55dp"
	    android:layout_height="55dp"
	    android:layout_centerHorizontal="true"
	    android:layout_alignParentBottom="true"
	    android:background="@drawable/capturing" />
	
	<Button 
	    android:id="@+id/sw"
	    android:layout_width="45dp"
	    android:layout_height="45dp"
	    android:layout_alignParentTop="true"
	    android:layout_centerHorizontal="true"
	    android:background="@drawable/ic_switch" />
...
* After that you should work on classes.
In Main.Class Activity there just few line to perform startService(INTENT);
(I just Set this for future developments.)
Code:
Intent s = new Intent(Main.this, FloatingCamera_Back.class);
s.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startService(s);
* So we should work on Service Class.
NOTE: Also you need to create class to handle Preview of Camera. (Check Source Code)

Code:
public class FloatingCamera_Back extends Service{

	WindowManager windowManager;   //WindowManager for adding View to SYSTEM_ALERT_WINDOW
	ViewGroup vG;                               //ViewGroup of layout
	Context context;

	Camera mCamera;
        Preview mPreview;
        Button capture, flash, menu, sw;
    
        byte[] pictureBytes;  //for captured data from camera lens
    
        String mCurrentPhotoPath;
        private static final String TAG = "Floating_Camera";
    
	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
           [COLOR="Red"]// I set Everything I need for Camera & Capturing process here[/COLOR]
     }
}
All these Codes should place in onStartCommand()
Now you need to setup Overlay Window
Code:
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

//Change int Value of size to dp		
int H = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 320, this.getResources().getDisplayMetrics());
int w = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 220, this.getResources().getDisplayMetrics());
		
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
	w,
	H,
	WindowManager.LayoutParams.TYPE_PHONE,
	WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
	PixelFormat.TRANSLUCENT);

	params.gravity = Gravity.TOP | Gravity.LEFT;
	params.x = 10;
	params.y = 100;
& after this you should add view to WindowManager, So define & find remote ViewGroup

Code:
//Define View
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vG = (ViewGroup)layoutInflater.inflate(R.layout.full_back, null, false);
windowManager.addView(vG, params);
here you can find component inside layout like buttons
Code:
capture = (Button)vG.findViewById(R.id.capture);
menu = (Button)vG.findViewById(R.id.menumode);
sw = (Button)vG.findViewById(R.id.sw);
after setting up the GUI components it s time to work on Camera & add Preview to FrameLayout
Code:
mCamera = getCameraInstance(); //It is function that check & open camera
mPreview = new Preview(this, mCamera);
FrameLayout preview = (FrameLayout) vG.findViewById(R.id.previewFrame);
preview.addView(mPreview);
Up to here Floating Window popped up & showing Camera view
so you need to capture that view

Code:
capture.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {			
			mCamera.takePicture(null, null, mPicture);
                       //Highly Recommend to [FONT="Impact"](Check Source Code)[/FONT]
		}
});
mPicture is PictureCallBack that handle captured data and write it to file. Check out following codes & comments;
Code:
public static final int MEDIA_TYPE_IMAGE = 1;

    private File getOutputMediaFile(int type){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Floating_Camera");
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                Log.d("CameraW", "failed to create directory");
                return null;
            }
        }
        
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String timeStampshort = new SimpleDateFormat("_HHmmss").format(new Date());
        File mediaFile = null;
        if (type == MEDIA_TYPE_IMAGE){
        	mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp);
        } 
        else {
            return null;
        }
        
        mCurrentPhotoPath = mediaFile.getAbsolutePath();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            	galleryAddPic();
            }
        }, 300);	        
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
            	galleryAddPicPort();
            }
        }, 300);
        
        return mediaFile;
    }
	
	private PictureCallback mPicture = new PictureCallback() {
	    @Override
	    public void onPictureTaken(byte[] data, Camera camera) {

	        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
	        if (pictureFile == null){
	            //
	        	
	            return;
	        }
	        
/***/  // NOTE: Handle the image rotation after saving the file. 
///////////////////////////////////Portrait	        
             if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            //	 	BitmapFactory.Options options = new BitmapFactory.Options();
            //	 	options.inSampleSize = 2;
                 
            		 Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                     int w = bm.getWidth();
                     int h = bm.getHeight();
                     
                     Matrix mtx = new Matrix();
                     mtx.setRotate(90);
                     bm = Bitmap.createBitmap(bm, 0, 0, w, h, mtx, true);

                     //byte[] pictureBytes;
                     ByteArrayOutputStream bos = new ByteArrayOutputStream();
                     bm.compress(CompressFormat.JPEG, 100, bos);
                     pictureBytes = bos.toByteArray();
                     
                     try {
         	            FileOutputStream fos = new FileOutputStream(pictureFile);
         	            fos.write(pictureBytes);
         	            fos.close();
         	        } catch (FileNotFoundException e) {
         	            Log.d(TAG, "File not found: " + e.getMessage());
         	        } catch (IOException e) {
         	            Log.d(TAG, "Error accessing file: " + e.getMessage());
         	        } finally {
         	        	mCamera.startPreview();
         	        }
             }
/////////////////////////////////////Landscape
        else{
	        try {
	            FileOutputStream fos = new FileOutputStream(pictureFile);
	            fos.write(data);
	            fos.close();
	        } catch (FileNotFoundException e) {
	            Log.d(TAG, "File not found: " + e.getMessage());
	        } catch (IOException e) {
	            Log.d(TAG, "Error accessing file: " + e.getMessage());
	        }finally {
	        	mCamera.startPreview();
	        }
	    }
	 }
};
That's it. ;)
The Captured Data from Camera View in Floating Windows saved into files

Also there is some additional functions that are handling Flash_Torch_Mode, Auto_Focus & etc.

* Also to have real meaning floating window user should be able to move it around screen. so u set touchListener for ViewGroup (to move whole view together)
Code:
vG.setOnTouchListener(new View.OnTouchListener() {
private WindowManager.LayoutParams paramsF = params;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;

@Override 
public boolean onTouch(View v, MotionEvent event) {
										
switch (event.getAction()) {
	case MotionEvent.ACTION_DOWN:
	System.out.println("Touch ACTION_DOWN");
			    		
	initialX = paramsF.x;
	initialY = paramsF.y;
	initialTouchX = event.getRawX();
	initialTouchY = event.getRawY();
	break;
	case MotionEvent.ACTION_UP:
	System.out.println("Touch ACTION_UP");

	break;
	case MotionEvent.ACTION_MOVE:
	System.out.println("Touch ACTION_MOVE");

	paramsF.x = initialX + (int) (event.getRawX() - initialTouchX);
	paramsF.y = initialY + (int) (event.getRawY() - initialTouchY);
	windowManager.updateViewLayout(vG, paramsF);
	break;
	}
	return false;
	}
});

NOTE: onDestroy >> Do NOT forget to release camera & stop the service

Code:
@Override
	public void onDestroy() {
		super.onDestroy();
		if (vG != null) {
			windowManager.removeView(vG);
			stopService(new Intent(getApplicationContext(), FloatingCamera_Back.class));
			releaseCamera();  //[FONT="Impact"](Check Source Code)[/FONT]
		}
	}
Download SourceCode & APK & Enjoy

If you find any mistake Or issue in my codes Please inform me.
Don't forget to Hit Thanks

XDA:DevDB Information
Floating Camera, App for all devices (see above for details)

Contributors
Geeks Empire
Source Code: http://forum.xda-developers.com/attachment.php?attachmentid=3327564&stc=1&d=1432386596


Version Information
Status: Stable
Current Stable Version: 1.000.00.1r
Stable Release Date: 2015-05-20

Created 2015-05-23
Last Updated 2017-03-16
 

Geeks Empire

Senior Member
Aug 29, 2014
1,200
1,252
153
Nashville
GeeksEmpire.net
Info

Source Code Download
APK file Download

Check out CameraW+ (Voice Command & Floating View)





Thanks for Supporting GeeksEmpire projects

:cowboy:
 

Attachments

Last edited:

Geeks Empire

Senior Member
Aug 29, 2014
1,200
1,252
153
Nashville
GeeksEmpire.net
Info

HOW TO Create Floating Widget

To Add Floating Widget all part should configure as a normal shortcut or better to say a view.
First you define View & Add to WindowManager. But an extra Step for Widgets is defining AppWidgetManager to get WidgetID & WidgetView for attaching.

Check Out the SourceCode of Floating Shortcuts Application.


Thanks for Supporting GeeksEmpire projects

Don't Forget To Hit Thanks