Android : How to check if device has camera
In this tutorial we are going to use PackageManager
and the hasSystemFeature
method to find out whether our device has a Camera or not. Of course there are plenty of things you can find out about the device using the same tools.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
- JDK 1.7
- Eclipse 4.2 Juno
- Android SKD 4.2
1. Create a new Android Project
Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project and click Next.
You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.
In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.
Select “BlankActivity” and click Next.
You will be asked to specify some information about the new activity. In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml
will be created. Then, click Finish.
Open res/layout/main.xml
file :
And paste the following code :
<RelativeLayout 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" tools:context=".MainActivity" > <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout>
2. Code
Go to the java file that contains the code of the activity you’ve just created:
And paste the following code:
package com.javacodegeeks.androids.androiddevicecameraexample; import android.app.Activity; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Context context = this; PackageManager pm = context.getPackageManager(); TextView text = (TextView) findViewById(R.id.text); if (pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) { text.setText("This device has a Camera"); } else { text.setText("This device doesn't have a Camera"); } } }
3. Run the application
This is the main screen of our Application:
Download Eclipse Project
This was an Android Example on how to find out if your device has a Camera. Download the Eclipse Project of this tutorial: AndroidDeviceCameraExample.zip