Image Review not shown after camera.takePicture - camera

On all the handsets I've tried, including the Galaxy Nexus with both API 2.3.7 and 4.0 after the takePicture method is called the surface view changes to the image that was taken, the "Image Review".
I've tested on these tablet devices and the image review didn't show up:
XOOM API 3.1
Galaxy Tab 10.1 API 3.1
Galaxy Tab 10.1 API 3.2
surfaceView = (SurfaceView)findViewById(R.id.surfaceView);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
...
public void takePicture() {
cam.takePicture(this, null, this); //Shuttercallback, RawCallback, JpegCallback
}
...
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// Stop preview before changing camera parameters
if(isPreviewRunning) {
this.cam.stopPreview();
}
Camera.Parameters p = this.cam.getParameters();
LogUtils.info("CheckCapture", "Preview Size: " + String.valueOf(width) +"x" + String.valueOf(height));
p.setPreviewSize(width, height);
//Set picture size to a multiple of previewSize to maintain aspect ratio AND minimum capture width
//LogUtils.info("CheckCapture", "Picture Size: " + String.valueOf(width*factor) +"x" + String.valueOf(height*factor));
p.setPictureSize(width, height);
p.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
//Set picture format (we can check device capabilities, but all devices at API level 8 should support JPEG)
p.setPictureFormat(PixelFormat.JPEG);
//Set new camera parameters
try {
this.cam.setParameters(p);
}catch (Exception e) {
e.printStackTrace();
}
//Setup preview display on our surfaceViewHolder
try {
this.cam.setPreviewDisplay(surfaceHolder);
} catch (IOException e) {
e.printStackTrace();
}
//Start preview
this.cam.startPreview();
this.isPreviewRunning = true;
}

on btn_click.onclickListener use callback method as follow
_btn_click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ShutterCallback shutterCallBack = new ShutterCallback() {
#Override
public void onShutter() {}
};
PictureCallback pictureCallBack = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {}
};
PictureCallback pictureCallBackJPG = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap capturedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
};
setFlashMode();
camera.takePicture(shutterCallBack, pictureCallBack,
pictureCallBackJPG);
showProgressDialog("Bitte warten", CameraCaptureActivity.this);
}
});
in this code main line is
Bitmap capturedBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
use capturedBitmap in imageview.setImageBitmap(capturedBitmap); to show the image.
Happy Coding

Related

Screenshot does not take the latest, current or updated view (Android)

I'm trying to switch a banner adView to imageView just before I take a screenshot so that users can share this screenshot through share intent.
However, when I take the screenshot, it does not include the imageView.
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
adView1 = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID1);
LinearLayout.LayoutParams childParam2 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0.10f);
adView1.setLayoutParams(childParam2);
adView1.loadAd(new AdRequest());
ll.addView(adView1);
setContentView(ll);
myAdView = new ImageView(this);
LinearLayout.LayoutParams childParam1 = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0, 0.10f);
myAdView.setLayoutParams(childParam1);
....
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
...
case R.id.menu3:
share();
break;
...
}
}
Here's share() function.
private void share(){
List<Intent> targetedShareIntents = new ArrayList<Intent>();
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("*/*");
List<ResolveInfo> resInfo =
this.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
........
if (packageName.toLowerCase().contains("twitter")){
targetedShareIntent.setType("*/*");
String location = "file://" + takeScreen(ll);
...
}
...
}
This is takeScreen(View v) function.
public String takeScreen(View c_view){
ll.removeView(adView1);
ll.addView(myAdView);
// create bitmap screen capture
Bitmap bitmap;
View v1 = c_view.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = v1.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File imageFile = new File(extr, "screen_" + System.currentTimeMillis() + ".jpg");
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
boolean saved = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
//Log.e("bitmap saved ?", saved + "!");
fout.flush();
fout.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ll.removeView(myAdView);
ll.addView(adView1);
return imageFile.getPath();
}
As you can see, I'm removing adView and adding myAdView(imageView) just before the screenshot is taken in takeScreen() function. adView IS removed but imageVies is NOT added to the screenshot.
The imageView DOES appear on the screen just before chooserIntent(share intent) pop-up screen is displayed.
I have tried many other options like
added both views and just switched visibility. setVisibility(View.Gone, View.Visible)
tried creating bitmap with canvas instead of getDrawingCache (thinking that it could be a cache related problem)
Is taking screenshot or 'share intent' too much of work for the UI thread to be blocked?
Can anyone shed a light here? I am completely at a loss.
I found a way to get around this. I created a composite bitmap out of the background bitmap and the overlay(my ad image) bitmap. In case anyone is interested, here's the code.
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
Bitmap overlay = BitmapFactory.decodeResource(this.getResources() , R.drawable.my_ad);
canvas.drawBitmap(overlay, 100, 100, null);
return bitmap;
}

Using LocationListener (with google play service) as service consume too much battery (Android 4.4.2)

I have a service that returns the current position every 30 seconds, my problem is that the service consumes about 40% of the battery. The GPS icon is always active, even if I increase the time interval. I see this problem with my Nexus 4 android 4.4.2. Once the callback OnLocationChanged is called, the GPS is awake all the time and this consumes the entire battery. With my other Phone Nexus One android 2.2.3 , I do not see this problem, the GPS turns on every 30 seconds and turns off. And I have no battery consommation. The service use Location Request, with .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY), excepted to use GPS and Network and is not the case. I thinks there is a problem with android 4.4.2 or is Google play service
Here my service code:
public class MyServiceGpsDebug extends Service implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener,LocationListener
{
IBinder mBinder = new LocalBinder();
private LocationClient mLocationClient;
private LocationRequest mLocationRequest;
// Flag that indicates if a request is underway.
private boolean mInProgress;
private Boolean servicesAvailable = false;
public class LocalBinder extends Binder
{
public MyServiceGpsDebug getServerInstance()
{
return MyServiceGpsDebug.this;
}
}
#Override
public void onCreate()
{
super.onCreate();
mInProgress = false;
// Create the LocationRequest object
mLocationRequest = LocationRequest.create();
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the update interval to 5 seconds
mLocationRequest.setInterval(Constants.UPDATE_INTERVAL);
// Set the fastest update interval to 1 second
mLocationRequest.setFastestInterval(Constants.FASTEST_INTERVAL);
servicesAvailable = servicesConnected();
mLocationClient = new LocationClient(this, this, this);
}
private boolean servicesConnected()
{
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode)
{
return true;
}
else
{
return false;
}
}
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
if(!servicesAvailable || mLocationClient.isConnected() || mInProgress)
return START_STICKY;
setUpLocationClientIfNeeded();
if(!mLocationClient.isConnected() || !mLocationClient.isConnecting() && !mInProgress)
{
appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Started", Constants.LOG_FILE);
mInProgress = true;
mLocationClient.connect();
}
return START_STICKY;
}
private void setUpLocationClientIfNeeded()
{
if(mLocationClient == null)
mLocationClient = new LocationClient(this, this, this);
}
#Override
public void onLocationChanged(Location location)
{
// Report to the UI that the location was updated
String msg = Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude());
Log.d("debug", msg);
// Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
appendLog(msg, Constants.LOCATION_FILE);
}
#Override
public IBinder onBind(Intent intent)
{
return mBinder;
}
public String getTime()
{
SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return mDateFormat.format(new Date());
}
public void appendLog(String text, String filename)
{
File logFile = new File(filename);
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onDestroy()
{
// Turn off the request flag
mInProgress = false;
if(servicesAvailable && mLocationClient != null)
{
mLocationClient.removeLocationUpdates(this);
// Destroy the current location client
mLocationClient = null;
}
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Stopped", Constants.LOG_FILE);
super.onDestroy();
}
#Override
public void onConnected(Bundle bundle)
{
// Request location updates using static settings
mLocationClient.requestLocationUpdates(mLocationRequest, this);
appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Connected", Constants.LOG_FILE);
}
#Override
public void onDisconnected()
{
// Turn off the request flag
mInProgress = false;
// Destroy the current location client
mLocationClient = null;
// Display the connection status
// Toast.makeText(this, DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
appendLog(DateFormat.getDateTimeInstance().format(new Date()) + ": Disconnected", Constants.LOG_FILE);
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult)
{
mInProgress = false;
if (connectionResult.hasResolution())
{
// If no resolution is available, display an error dialog
} else {
}
}
public final class Constants
{
// Milliseconds per second
private static final int MILLISECONDS_PER_SECOND = 1000;
// Update frequency in seconds
private static final int UPDATE_INTERVAL_IN_SECONDS = 60;
// Update frequency in milliseconds
public static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
// The fastest update frequency, in seconds
private static final int FASTEST_INTERVAL_IN_SECONDS = 60;
// A fast frequency ceiling in milliseconds
public static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;
// Stores the lat / long pairs in a text file
public static final String LOCATION_FILE = "sdcard/location.txt";
// Stores the connect / disconnect data in a text file
public static final String LOG_FILE = "sdcard/log.txt";
/**
* Suppress default constructor for noninstantiability
*/
private Constants() {
throw new AssertionError();
}
}
}
I have similar problem with Nexus 4. My app has a service which uses location updates (fusion location or android providers, not both). Everything works OK for all android phones but in Nexus4 after some time the phone gets hot and slow even if i kill the app (through DDMS, 100% stopped). The only solution is to kill Google play services .
I think that there is a bug in play services for nexus 4. There is a dirty solution to kill Google Play Services every 30mins for example if phone=nexus4, but i do not know if it is possible

how to make my flashlight not o open instantly when i open the program?

// Get the camera
private void getCamera() {
if (camera == null) {
try {
camera = Camera.open();
params = camera.getParameters();
} catch (RuntimeException e) {
Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
}
}
}
// Turning On flash
private void turnOnFlash() {
if (!isFlashOn) {
if (camera == null || params == null) {
return;
}
// play sound
playSound();
params = camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
camera.startPreview();
isFlashOn = true;
// changing button/switch image
toggleButtonImage();
}
}
My code that gets involved with flash on is above, any suggestions,how to make the flash not open the moment my app opens but only when i press the button
I would guess you are calling turnFlashOn() in onCreate() and don't have a button ClickListener. But it is possible you could be calling turnFlashOn() in onStart() or onResume().
To have it turn on with a button press you should do something like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_view);
flashlight_button = (Button) findViewById(R.id.your_button);
flashlight_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getCamera();
turnOnFlash();
}
});
}
I built an open source flashlight for Android that you can check out at Flashlight by Joe github.

android media player connecting status with audio streaming link(ie 2%,4%...100% then online radio start to play) in android

how i get buffering status while media player trying to connect audio streaming link(ie 2%,4%...100% then online radio start to play) in android.
this is my code.
but i have no idea how i solve my problem.thanks is advance to any kind of help.
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
i solve this problem. here is the link. http://coderfriend.blogspot.com/
as per request here i share blog content..
when user click play button to play radio then i want to show connecting status(buffering 1%,2%.. 99%). when status will be 100% radio start to play. i was face problem to solve this. so here i share this code for all.
//at first create this class
public class StreamingMediaPlayer {
private static final int INTIAL_KB_BUFFER = 96*10/8;//assume 96kbps*10secs/8bits per byte
private TextView textStreamed;
private ImageButton playButton;
private ProgressBar progressBar;
// Track for display by progressBar
private long mediaLengthInKb, mediaLengthInSeconds;
private int totalKbRead = 0;
// Create Handler to call View updates on the main UI thread.
private final Handler handler = new Handler();
private MediaPlayer mediaPlayer;
private File downloadingMediaFile;
private boolean isInterrupted;
private Context context;
private int counter = 0;
public StreamingMediaPlayer(Context context,TextView textStreamed, ImageButton playButton, Button streamButton,ProgressBar progressBar)
{
this.context = context;
this.textStreamed = textStreamed;
this.playButton = playButton;
this.progressBar = progressBar;
}
/**
* Progressivly download the media to a temporary location and update the MediaPlayer as new content becomes available.
*/
public void startStreaming(final String mediaUrl, long mediaLengthInKb, long mediaLengthInSeconds) throws IOException {
this.mediaLengthInKb = mediaLengthInKb;
this.mediaLengthInSeconds = mediaLengthInSeconds;
Runnable r = new Runnable() {
public void run() {
try {
downloadAudioIncrement(mediaUrl);
} catch (IOException e) {
Log.e(getClass().getName(), "Unable to initialize the MediaPlayer for fileUrl=" + mediaUrl, e);
return;
}
}
};
new Thread(r).start();
}
/**
* Download the url stream to a temporary location and then call the setDataSource
* for that local file
*/
public void downloadAudioIncrement(String mediaUrl) throws IOException {
URLConnection cn = new URL(mediaUrl).openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
if (stream == null) {
Log.e(getClass().getName(), "Unable to create InputStream for mediaUrl:" + mediaUrl);
}
downloadingMediaFile = new File(context.getCacheDir(),"downloadingMedia.dat");
if (downloadingMediaFile.exists()) {
downloadingMediaFile.delete();
}
FileOutputStream out = new FileOutputStream(downloadingMediaFile);
byte buf[] = new byte[16384];
int totalBytesRead = 0, incrementalBytesRead = 0;
do {
int numread = stream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
totalBytesRead += numread;
incrementalBytesRead += numread;
totalKbRead = totalBytesRead/1000;
testMediaBuffer();
fireDataLoadUpdate();
} while (validateNotInterrupted());
stream.close();
if (validateNotInterrupted()) {
fireDataFullyLoaded();
}
}
private boolean validateNotInterrupted() {
if (isInterrupted) {
if (mediaPlayer != null) {
mediaPlayer.pause();
//mediaPlayer.release();
}
return false;
} else {
return true;
}
}
/**
* Test whether we need to transfer buffered data to the MediaPlayer.
* Interacting with MediaPlayer on non-main UI thread can causes crashes to so perform this using a Handler.
*/
private void testMediaBuffer() {
Runnable updater = new Runnable() {
public void run() {
if (mediaPlayer == null) {
// Only create the MediaPlayer once we have the minimum buffered data
if ( totalKbRead >= INTIAL_KB_BUFFER) {
try {
startMediaPlayer();
} catch (Exception e) {
Log.e(getClass().getName(), "Error copying buffered conent.", e);
}
}
} else if ( mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000 ){
// NOTE: The media player has stopped at the end so transfer any existing buffered data
// We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
transferBufferToMediaPlayer();
}
}
};
handler.post(updater);
}
private void startMediaPlayer() {
try {
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// We double buffer the data to avoid potential read/write errors that could happen if the
// download thread attempted to write at the same time the MediaPlayer was trying to read.
// For example, we can't guarantee that the MediaPlayer won't open a file for playing and leave it locked while
// the media is playing. This would permanently deadlock the file download. To avoid such a deadloack,
// we move the currently loaded data to a temporary buffer file that we start playing while the remaining
// data downloads.
moveFile(downloadingMediaFile,bufferedFile);
Log.e(getClass().getName(),"Buffered File path: " + bufferedFile.getAbsolutePath());
Log.e(getClass().getName(),"Buffered File length: " + bufferedFile.length()+"");
mediaPlayer = createMediaPlayer(bufferedFile);
// We have pre-loaded enough content and started the MediaPlayer so update the buttons & progress meters.
mediaPlayer.start();
startPlayProgressUpdater();
playButton.setEnabled(true);
} catch (IOException e) {
Log.e(getClass().getName(), "Error initializing the MediaPlayer.", e);
return;
}
}
private MediaPlayer createMediaPlayer(File mediaFile)
throws IOException {
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(
new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e(getClass().getName(), "Error in MediaPlayer: (" + what +") with extra (" +extra +")" );
return false;
}
});
// It appears that for security/permission reasons, it is better to pass a FileDescriptor rather than a direct path to the File.
// Also I have seen errors such as "PVMFErrNotSupported" and "Prepare failed.: status=0x1" if a file path String is passed to
// setDataSource(). So unless otherwise noted, we use a FileDescriptor here.
FileInputStream fis = new FileInputStream(mediaFile);
mPlayer.setDataSource(fis.getFD());
mPlayer.prepare();
return mPlayer;
}
/**
* Transfer buffered data to the MediaPlayer.
* NOTE: Interacting with a MediaPlayer on a non-main UI thread can cause thread-lock and crashes so
* this method should always be called using a Handler.
*/
private void transferBufferToMediaPlayer() {
try {
// First determine if we need to restart the player after transferring data...e.g. perhaps the user pressed pause
boolean wasPlaying = mediaPlayer.isPlaying();
int curPosition = mediaPlayer.getCurrentPosition();
// Copy the currently downloaded content to a new buffered File. Store the old File for deleting later.
File oldBufferedFile = new File(context.getCacheDir(),"playingMedia" + counter + ".dat");
File bufferedFile = new File(context.getCacheDir(),"playingMedia" + (counter++) + ".dat");
// This may be the last buffered File so ask that it be delete on exit. If it's already deleted, then this won't mean anything. If you want to
// keep and track fully downloaded files for later use, write caching code and please send me a copy.
bufferedFile.delete();
moveFile(downloadingMediaFile,bufferedFile);
// Pause the current player now as we are about to create and start a new one. So far (Android v1.5),
// this always happens so quickly that the user never realized we've stopped the player and started a new one
mediaPlayer.pause();
// Create a new MediaPlayer rather than try to re-prepare the prior one.
mediaPlayer = createMediaPlayer(bufferedFile);
mediaPlayer.seekTo(curPosition);
// Restart if at end of prior buffered content or mediaPlayer was previously playing.
// NOTE: We test for < 1second of data because the media player can stop when there is still
// a few milliseconds of data left to play
boolean atEndOfFile = mediaPlayer.getDuration() - mediaPlayer.getCurrentPosition() <= 1000;
if (wasPlaying || atEndOfFile){
mediaPlayer.start();
}
// Lastly delete the previously playing buffered File as it's no longer needed.
oldBufferedFile.delete();
}catch (Exception e) {
Log.e(getClass().getName(), "Error updating to newly loaded content.", e);
}
}
private void fireDataLoadUpdate() {
Runnable updater = new Runnable() {
public void run() {
if((totalKbRead>19)&&(totalKbRead<120))
textStreamed.setText((totalKbRead-19 + "% Buffering"));//show buffering status.. ie 1%,2%. in ui
else if(totalKbRead<19)
textStreamed.setText(("Connecting..."));
else
textStreamed.setText((""));
float loadProgress = ((float)totalKbRead/(float)mediaLengthInKb);
progressBar.setSecondaryProgress((int)(loadProgress*100));
}
};
handler.post(updater);
}
private void fireDataFullyLoaded() {
Runnable updater = new Runnable() {
public void run() {
transferBufferToMediaPlayer();
// Delete the downloaded File as it's now been transferred to the currently playing buffer file.
downloadingMediaFile.delete();
textStreamed.setText(("Audio full loaded: " + totalKbRead + " Kb read"));
}
};
handler.post(updater);
}
public MediaPlayer getMediaPlayer() {
return mediaPlayer;
}
public void startPlayProgressUpdater() {
float progress = (((float)mediaPlayer.getCurrentPosition()/1000)/mediaLengthInSeconds);
progressBar.setProgress((int)(progress*100));
if (mediaPlayer.isPlaying()) {
Runnable notification = new Runnable() {
public void run() {
startPlayProgressUpdater();
}
};
handler.postDelayed(notification,1000);
}
}
public void interrupt() {
playButton.setEnabled(false);
isInterrupted = true;
validateNotInterrupted();
}
/**
* Move the file in oldLocation to newLocation.
*/
public void moveFile(File oldLocation, File newLocation)
throws IOException {
if ( oldLocation.exists( )) {
BufferedInputStream reader = new BufferedInputStream( new FileInputStream(oldLocation) );
BufferedOutputStream writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
try {
byte[] buff = new byte[8192];
int numChars;
while ( (numChars = reader.read( buff, 0, buff.length ) ) != -1) {
writer.write( buff, 0, numChars );
}
} catch( IOException ex ) {
throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
} finally {
try {
if ( reader != null ){
writer.close();
reader.close();
}
} catch( IOException ex ){
Log.e(getClass().getName(),"Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
} else {
throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
}
}
}
//now copy the below code in activity
StreamingMediaPlayer audioStreamer =
new StreamingMediaPlayer(this,textStreamed,playButton,
streamButton,progressBar);
audioStreamer.startStreaming("your streaming station name",5208, 216);
i think this helps you :)

Waiting for camera to save photo, what is better than thread.sleep?

I have a custom OpenCV camera activity that takes a photo when the screen is tapped. The activity is started with a startActivityForResult intent, and the filepath of the photo is handed back to the MainActivity after the activity is finished. However, the camera saves the photo asynchronously and therefore the filepath shouldn't be checked until the photo is taken. I am using the filepath to set an imageView, and calling it immediately gives an empty image. I have managed to make it work by using Thread.sleep(3000); but this is a horrible option as it just stalls the UI which, as I've read countless times, is a big no no! Is there a way I can wait until the photo is saved before calling the return to MainActivity intent? I understand there is a callback from the camera but I don't understand how it works or how to use it, perhaps that is the best way to go?
Here's some code anyway.
in MainActivity extends FragmentActivity:
rootView.findViewById(R.id.button_start_camera).setOnClickListener(new View.OnClickListener() {
// Listen for Take Photo button Click, start app's openCV camera
#Override
public void onClick(View view) {
// Start Camera app
Intent intentCamera = new Intent(getActivity(), CameraActivity.class);
startActivityForResult(intentCamera, 2);
}
});
In CameraActivity extends Activity implements CvCameraViewListener2, OnTouchListener:
#Override
public boolean onTouch(View v, MotionEvent event) {
Log.i(TAG,"onTouch event");
if (takePicture) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss");
String currentDateandTime = sdf.format(new Date());
fileName = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath() +
"/MatCom_" + currentDateandTime + ".jpg";
mOpenCvCameraView.takePicture(fileName);
Toast.makeText(this, fileName + " saved", Toast.LENGTH_SHORT).show();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent returnIntent = new Intent();
returnIntent.putExtra("result", fileName);
setResult(RESULT_OK, returnIntent);
finish();
}
return false;
}
And then back to MainActivity:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
Log.i(TAG, "onActivityResult. resultCode = " + requestCode);
if (requestCode == 1) {//My other startActivityForResult...}
if (requestCode == 131074 && resultCode == RESULT_OK){
Bundle bundle = intent.getExtras();
filepath = bundle.getString("result");
Log.i(TAG, filepath);
imageView = (ImageView) findViewById(R.id.imageView);
bmp = BitmapFactory.decodeFile(filepath);
imageView.setBackgroundResource(0);
imageView.setImageBitmap(bmp);
}
}
NOTICE: As an aside, for some reason my requestCode comes back as 131074 every time despite setting it at 2 for the startActivityForResult - let me know if you know why that is.
Finally, in case it's necessary to see, here's the takePicture method from the CameraView class:
public void takePicture(final String fileName) {
Log.i(TAG, "Taking picture");
PictureCallback callback = new PictureCallback() {
private String mPictureFileName = fileName;
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.i(TAG, "Saving a bitmap to file");
Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
try {
FileOutputStream out = new FileOutputStream(mPictureFileName);
picture.compress(Bitmap.CompressFormat.JPEG, 90, out);
picture.recycle();
// Open the image for analysis
// Read in the image from the file
Mat mOriginalImage = Highgui.imread(fileName);
// Only process the image if it actually exists!
if (mOriginalImage != null) {
// Find the size of the image
org.opencv.core.Size mSizeReadImage = mOriginalImage.size();
// From the number of rows and columns get the coordinates of the largest possible centralised square
double height = mSizeReadImage.height;
double width = mSizeReadImage.width;
double minDim = Math.min(height, width);
double top = height/2.0 - 2.0*minDim/5.0;
double left = width/2.0 - 2.0*minDim/5.0;
// Create a submat of the image based on the centralised square
Mat mOriginalImageSubmat = mOriginalImage.submat((int)Math.round(top), (int)Math.round(top + 4.0*minDim/5.0), (int)Math.round(left), (int)Math.round(left + 4.0*minDim/5.0));
// Create another Mat the required size but same type as mOriginalImageSubmat and resize mOriginalImageSubmat to fit into it
Mat mDrawableSubmat = new Mat(new Size(480.0, 480.0), mOriginalImageSubmat.type());
Imgproc.resize(mOriginalImageSubmat, mDrawableSubmat, mDrawableSubmat.size());
Mat mColourSourceSubmat = mDrawableSubmat.clone();
Mat mCannyOutput = mDrawableSubmat.clone();
double minLineLength = 300.0;
ColourMatrix matrix = new ColourMatrix();
matrix.setColourMatch(colourMatch);
matrix.setColourOrder(colourOrder);
matrix.setComparison(comparison);
matrix.setDisplayHotspots(displayHotspots);
matrix.setDisplayOutline(displayOutline);
matrix.setIntensity(intensity);
matrix.setMatrixType(matrixType);
String output = matrix.decode(mColourSourceSubmat, mCannyOutput, mDrawableSubmat, minLineLength);
Log.i(TAG, "DJH - decoded: " + output);
}
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}
};
mCamera.takePicture(null, null, callback);
}
Thread.sleep isn't bad per se. You can use a loop to 30 with thread.sleep(100). Then you'll only be pausing .1 second at a time, and the CPU still won't spike.