How can play sound with service in android? - java

In a special app for android i need to make a service that play a sound for hours and control it by my service ... but sound player`s code does not work in any method of my service class :((
my player class that extend from Service class :
package org.tooj;
import org.qtproject.example.Book.R;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
public class Player extends Service {
MediaPlayer Player;
#Override
public void onCreate() {
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
//my player
public int onStartCommand(Intent intent, int flags, int startId) {
Player = MediaPlayer.create(ToojActivity.getInstance(),R.ra w.alfa);
Player.setLooping(true);
Player.setVolume(1,1);
Player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
Player.stop();
Player.release();
}
#Override
public void onLowMemory() {
}
}
my main activity :
package org.tooj;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import org.qtproject.qt5.android.bindings.QtActivity;
public class ToojActivity extends QtActivity{
private static ToojActivity instance;
private boolean _transparentStatusBar = false;
private boolean _transparentNavigationBar = false;
public ToojActivity(){
instance = this;
Log.i("ToojActivity", "ctor");
}
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent svc=new Intent(this, Player.class); // call service
startService(svc);
public static ToojActivity getInstance() {
return ToojActivity.instance;
}
public void SetStatusBarIsTransparent(boolean value) {
_transparentStatusBar = value;
}
public void GetNavigationBarIsTransparent(boolean value) {
_transparentNavigationBar = value;
}
public boolean GetStatusBarIsTransparent() {
return _transparentStatusBar;
}
public boolean GetNavigationBarIsTransparent() {
return _transparentNavigationBar;
}
}
and manifest ...
<?xml version='1.0' encoding='utf-8'?>
<manifest package="org.qtproject.example.Book" xmlns:android="http://schemas.android.com/apk/res/android" android:versionName="1.0" android:versionCode="1" android:installLocation="auto">
<application android:hardwareAccelerated="true" android:name="org.qtproject.qt5.android.bindings.QtApplication" android:label="Book">
<activity android:configChanges="orientation|uiMode|screenLayout|screenSize|smallestScreenSize|layoutDirection|locale|fontScale|keyboard|keyboardHidden|navigation"
android:name="org.tooj.ToojActivity"
android:label="Book"
android:screenOrientation="unspecified"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<meta-data android:name="android.app.lib_name" android:value="Book"/>
<meta-data android:name="android.app.qt_sources_resource_id" android:resource="#array/qt_sources"/>
<meta-data android:name="android.app.repository" android:value="default"/>
<meta-data android:name="android.app.qt_libs_resource_id" android:resource="#array/qt_libs"/>
<meta-data android:name="android.app.bundled_libs_resource_id" android:resource="#array/bundled_libs"/>
<!-- Deploy Qt libs as part of package -->
<meta-data android:name="android.app.bundle_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.bundled_in_lib_resource_id" android:resource="#array/bundled_in_lib"/>
<meta-data android:name="android.app.bundled_in_assets_resource_id" android:resource="#array/bundled_in_assets"/>
<!-- Run with local libs -->
<meta-data android:name="android.app.use_local_qt_libs" android:value="1"/>
<meta-data android:name="android.app.libs_prefix" android:value="/data/local/tmp/qt/"/>
<meta-data android:name="android.app.load_local_libs" android:value="plugins/platforms/android/libqtforandroid.so:plugins/bearer/libqandroidbearer.so:lib/libQt5QuickParticles.so:plugins/mediaservice/libqtmedia_android.so:lib/libQt5MultimediaQuick_p.so"/>
<meta-data android:name="android.app.load_local_jars" android:value="jar/QtAndroid.jar:jar/QtAndroidAccessibility.jar:jar/QtAndroid-bundled.jar:jar/QtAndroidAccessibility-bundled.jar:jar/QtAndroidBearer.jar:jar/QtAndroidBearer-bundled.jar:jar/QtMultimedia.jar:jar/QtMultimedia-bundled.jar"/>
<meta-data android:name="android.app.static_init_classes" android:value="org.qtproject.qt5.android.multimedia.QtMultimediaUtils:org.qtproject.qt5.android.multimedia.QtMultimediaUtils"/>
<!-- Messages maps -->
<meta-data android:value="#string/ministro_not_found_msg" android:name="android.app.ministro_not_found_msg"/>
<meta-data android:value="#string/ministro_needed_msg" android:name="android.app.ministro_needed_msg"/>
<meta-data android:value="#string/fatal_error_msg" android:name="android.app.fatal_error_msg"/>
<!-- Messages maps -->
<!-- Splash screen -->
<!--
<meta-data android:name="android.app.splash_screen_drawable" android:resource="#drawable/logo"/>
-->
<!-- Splash screen -->
<!-- Background running -->
<!-- Warning: changing this value to true may cause unexpected crashes if the
application still try to draw after
"applicationStateChanged(Qt::ApplicationSuspended)"
signal is sent! -->
<meta-data android:name="android.app.background_running" android:value="false"/>
<!-- Background running -->
</activity>
<service android:enabled="true" android:name=".Player" />
</application>
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="14"/>
<supports-screens android:largeScreens="true" android:normalScreens="true" android:anyDensity="true" android:smallScreens="true"/>
<!-- The following comment will be replaced upon deployment with default permissions based on the dependencies of the application.
Remove the comment if you do not require these default permissions. -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<!-- The following comment will be replaced upon deployment with default features based on the dependencies of the application.
Remove the comment if you do not require these default features. -->
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<uses-feature android:name="android.hardware.microphone" android:required="false" />
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
</manifest>

Related

WatchFaces are not configuring

I have created watchface for android wear and my code is as follows:
ComapnionConfigActivity (in mobile module):
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.wearable.Wearable;
public class CompanionConfigActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_companion_config);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Wearable.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_watch_config, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
Manifest for mobile module:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.agile.mywatchface" >
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/square"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".CompanionConfigActivity"
android:label="#string/title_activity_watch_config" >
<intent-filter>
<action android:name="com.example.agile.mywatchface.MAIN" />
<category android:name= "com.google.android.wearable.watchface.category.COMPANION_CONFIGURATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MyWatchfaceService: (service in wear module for drawing watchface)
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.wearable.watchface.CanvasWatchFaceService;
import android.view.SurfaceHolder;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
/**
*
* Created by agile on 3/5/2015.
*/
public class MyWatchfaceService extends CanvasWatchFaceService{
Calendar c;
int hrs,min,sec,width,height;
Timer timer;
TimerTask timerTask;
Paint paint;
#Override
public Engine onCreateEngine() {
return new MyEngine();
}
class MyEngine extends CanvasWatchFaceService.Engine {
#Override
public void onCreate(SurfaceHolder holder) {
super.onCreate(holder);
timer = new Timer();
timerTask = new MyTimerTask();
c = Calendar.getInstance();
paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(18);
}
#Override
public void onPropertiesChanged(Bundle properties) {
super.onPropertiesChanged(properties);
}
#Override
public void onTimeTick() {
super.onTimeTick();
}
#Override
public void onDraw(Canvas canvas, Rect bounds) {
updateTimeOnEachSecond();
width = bounds.width();
height = bounds.height();
canvas.drawText(String.valueOf(hrs)+":"+String.valueOf(min)+":"+String.valueOf(sec),width/2,height/2,paint);
}
#Override
public void onVisibilityChanged(boolean visible) {
super.onVisibilityChanged(visible);
}
}
public void updateTimeOnEachSecond() {
timer.scheduleAtFixedRate(timerTask, 0, 1000);
}
class MyTimerTask extends TimerTask {
public void run(){
hrs = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
sec = c.get(Calendar.SECOND);
}
}
}
Manifest for wear module:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.agile.mywatchface" >
<uses-feature android:name="android.hardware.type.watch" />
<uses-permission android:name="com.google.android.permission.PROVIDE_BACKGROUND" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#drawable/square"
android:label="#string/app_name"
>
<service
android:name=".MyWatchfaceService"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER"
android:allowEmbedded="true"
>
<!-- companion configuration activity -->
<meta-data
android:name="android.service.wallpaper"
android:resource="#xml/watch_face" />
<meta-data
android:name="com.example.agile.mywatchface.preview"
android:resource="#drawable/square" />
<meta-data
android:name="com.example.agile.mywatchface.preview_circular"
android:resource="#drawable/square" />
<meta-data
android:name="com.google.android.wearable.watchface.companionConfigurationAction"
android:value="com.example.agile.mywatchface.MAIN" />
<!-- wearable configuration activity -->
<meta-data
android:name="com.google.android.wearable.watchface.wearableConfigurationAction"
android:value="com.example.agile.mywatchface.MAIN" />
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
<category android:name="com.example.agile.mywatchface.category.WATCH_FACE" />
</intent-filter>
</service>
<activity
android:name=".WearConfigActivity"
android:label="#string/title_activity_wear_config"
android:allowEmbedded="true">
<intent-filter>
<action android:name="com.example.agile.mywatchface.CONFIG_DIGITAL" />
<category android:name=
"com.google.android.wearable.watchface.category.WEARABLE_CONFIGURATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="com.google.android.wearable.watchface.wearableConfigurationAction"
android:value="com.example.agile.mywatchface.MAIN" />
</activity>
</application>
</manifest>
I have followed official guide for creating watchface. But, when I install the app, it isn't showing in companion app. It seems like the problem is in manifest or companionconfigactivity. I tried for more than a day but couldn't identify it. Can anyone help me out?
In your Wearable Manifest you have following line:
<category android:name="com.example.agile.mywatchface.category.WATCH_FACE" />
This is incorrect, you need to use
<category android:name="com.google.android.wearable.watchface.category.WATCH_FACE" />
Android Wear looks for services with this category in the filter, it will ignore yours if you use custom category.

Android, Background service is not starting

I am implementing a simple application executing a background service, I am not able to start the service, following is my Manifest & Code, the service class is properly resolved ( reading resources ), inheriting from IntentService ( and implementing the req methods ) doesn't resolve the problem as-well...
Why does the Background service doesn't start?
any help will be appreciated.
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.newcomp.vagent"
android:versionCode="1"
android:versionName="1.0"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="20" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.newcomp.Infrastructure.BootStarter" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".CaptureService"
android:exported="true"
android:process=":captureService" >
</service>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.USE_CREDENTIALS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>
Service code:
package com.newcomp.vagent;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.R.*;
import android.os.IBinder;
import java.io.IOException;
import fi.iki.elonen.NanoHTTPD;
public class CaptureService extends Service {
public CaptureService() {
//super("Capture Service");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
}
Activity code:
package com.newcomp.vagent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final String strSvcName = getResources().getString(R.string.startup_service);
//setContentView(R.layout.main);
Toast.makeText(getBaseContext(), String.format("Hello from '%s'", strSvcName), Toast.LENGTH_LONG).show();
Class cls = null;
try {
cls = getClassLoader().loadClass(strSvcName);
startService(new Intent(this, cls));// Starts the service
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//finish();
}
}
The problem was simple, the service was actually starting but since android:process=":captureService" was specified it was starting on a separate process, one that is not connected by the debugger, either specifcally connecting to the service process, OR, omitting android:process=":captureService" resolve the problem.

terminate service android does not work correctly

I am currently trying to implement an app that has a service running until the user explicitly ends it via the app.
The service runs even when I exit the app(which is ok)
But when I enter the app again and try to stop the service, the app stops running.
What am I doing wrong?
This is the service code
package com.mac.service;
import android.app.Service;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
private Handler handler = new Handler();
private long timeAndSpace = 5000;
Thread t;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacksAndMessages(null);
Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}
#Override
public void onStart(Intent intent, int startid) {
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT)
.show();
final Runnable r = new Runnable() {
public void run() {
Location l = getMine();
Toast.makeText(
getApplicationContext(),
String.valueOf(l.getLatitude()) + " "
+ String.valueOf(l.getLongitude()),
Toast.LENGTH_SHORT).show();
handler.postDelayed(this, timeAndSpace);
}
};
handler.postDelayed(r, timeAndSpace);
return START_STICKY;
}
private Location getMine() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
return myLocation;
}
}
and this the manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mac.service"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="19" />
<uses-permission android:name="com.mac.maps2demo.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Required to show current location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- Required OpenGL ES 2.0. for Maps V2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<!-- Requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.mac.service.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<service
android:name="com.mac.service.MyService"
android:enabled="true"
android:exported="true" />
</application>
</manifest>

Why it can run in my device but it didn't display the map?I am beginner of SDK please explain clearly

This is my MainActivity
it is wrong about level of API ??
i am using Google API
API level 18
package com.example.map;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MapView myMap = (MapView) findViewById(R.id.mapView);
final MapController controller = myMap.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
controller.setCenter(new GeoPoint((int)location.getLatitude(),(int)location.getLongitude()));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
}
This is my Manifest
The uses_permission is necessary ??
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="11" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-library
android:name="com.google.android.maps" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY"/>
<activity
android:name="com.example.map.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
This is my activity_main
My layout is it correct??
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
If you're seeing a grayed tile background where a map should be, you are likely using the wrong api key. You need a production key for a device that is different from the debug key for the map api.

android - exception when trying to open the front camera

i am unable to get the the front facing camera (camera id 1). open cam #1 failed appears on screen when i try to run the following code.
enclosed a snippet. any help will be appreciated (i am trying it on nexus 4).
Tester.java
package com.example.cam;
import java.util.HashMap;
import java.util.Iterator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
public class Tester extends Activity {
private static final int[] camIds = { Camera.CameraInfo.CAMERA_FACING_BACK, Camera.CameraInfo.CAMERA_FACING_FRONT };
#SuppressLint("UseSparseArrays")
private final HashMap<Integer, Camera> camMap = new HashMap<Integer, Camera>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
protected void onResume() {
super.onResume();
if (!checkCameraHardware())
finish();
getCameras();
releaseCamera();
}
#Override
protected void onPause() {
super.onPause();
releaseCamera();
}
#Override
protected void onStop() {
super.onStop();
releaseCamera();
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseCamera();
}
private final void doToast(final String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private final void getCameras() {
for (int camId : camIds)
try {
camMap.put(camId, Camera.open(camId));
doToast("open cam #" + camId + " succeeded");
} catch (Exception e) {
doToast("open cam #" + camId + " failed");
}
}
private final void releaseCamera() {
final Iterator<Integer> iter = camMap.keySet().iterator();
while (iter.hasNext())
camMap.remove(iter.next()).release();
}
private final boolean checkCameraHardware() {
if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA))
return camIds.length <= Camera.getNumberOfCameras();
else
return false;
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cam"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CAPTURE_AUDIO_OUTPUT" />
<uses-permission android:name="android.permission.CAPTURE_SECURE_VIDEO_OUTPUT" />
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-feature
android:name="android.hardware.camera"
android:required="true" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.cam.Tester"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Categories