Using Camera and include an image of a layout - android-layout

I have the next code, actually I have a main layer that shows the camera preview, and 2 layouts called R.layout.overlay and R.layout.controls, the layout of controls only show a button that take a picture, and the overlay have an image, what I try to do is that at the moment I take the picture the image that is in R.layout.overlay appear on the capture of the photo.
At the moment of preview before taking the photo it displays controls an image fine.
I don't know how to do this cause when I take the picture it takes it but without the image on R.layout.overlay.
Or is there a way to take an screenshot with some code? thats other option I have been thinking, but the problem of this is that the photo will be of the size of the resolution of the screen.
This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().setFormat(PixelFormat.UNKNOWN);
surfaceView = (SurfaceView)findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
drawingView = new DrawingView(this);
LayoutParams layoutParamsDrawing
= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(drawingView, layoutParamsDrawing);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.control, null);
LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(viewControl, layoutParamsControl);
inflater = LayoutInflater.from(getBaseContext());
View view = inflater.inflate(R.layout.overlay, null);
LayoutParams layoutParamsControl2= new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT);
this.addContentView(view, layoutParamsControl2);
buttonTakePicture = (Button)findViewById(R.id.takepicture);
buttonTakePicture.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.takePicture(myShutterCallback, myPictureCallback_RAW, myPictureCallback_JPG);
}});
LinearLayout layoutBackground = (LinearLayout)findViewById(R.id.background);
layoutBackground.setOnClickListener(new LinearLayout.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(false);
camera.autoFocus(myAutoFocusCallback);
}});
prompt = (TextView)findViewById(R.id.prompt);
}
//Termina onCreate
FaceDetectionListener faceDetectionListener
= new FaceDetectionListener(){
#Override
public void onFaceDetection(Face[] faces, Camera camera) {
if (faces.length == 0){
prompt.setText(" No Face Detected! ");
drawingView.setHaveFace(false);
}else{
prompt.setText(String.valueOf(faces.length) + " Face Detected :) ");
drawingView.setHaveFace(true);
detectedFaces = faces;
}
drawingView.invalidate();
}};
AutoFocusCallback myAutoFocusCallback = new AutoFocusCallback(){
#Override
public void onAutoFocus(boolean arg0, Camera arg1) {
// TODO Auto-generated method stub
buttonTakePicture.setEnabled(true);
}};
ShutterCallback myShutterCallback = new ShutterCallback(){
#Override
public void onShutter() {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_RAW = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
}};
PictureCallback myPictureCallback_JPG = new PictureCallback(){
#Override
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriTarget);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
prompt.setText("Image saved: " + uriTarget.toString());
Toast.makeText(AndroidCamera.this, "Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
camera.startFaceDetection();
}};
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if(previewing){
camera.stopFaceDetection();
camera.stopPreview();
previewing = false;
}
if (camera != null){
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
prompt.setText(String.valueOf(
"Max Face: " + camera.getParameters().getMaxNumDetectedFaces()));
camera.startFaceDetection();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
camera.setFaceDetectionListener(faceDetectionListener);
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopFaceDetection();
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
private class DrawingView extends View{
boolean haveFace;
Paint drawingPaint;
public DrawingView(Context context) {
super(context);
haveFace = false;
drawingPaint = new Paint();
drawingPaint.setColor(Color.GREEN);
drawingPaint.setStyle(Paint.Style.STROKE);
drawingPaint.setStrokeWidth(2);
}
public void setHaveFace(boolean h){
haveFace = h;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
if(haveFace){
// Camera driver coordinates range from (-1000, -1000) to (1000, 1000).
// UI coordinates range from (0, 0) to (width, height).
int vWidth = getWidth();
int vHeight = getHeight();
for(int i=0; i<detectedFaces.length; i++){
int l = detectedFaces[i].rect.left;
int t = detectedFaces[i].rect.top;
int r = detectedFaces[i].rect.right;
int b = detectedFaces[i].rect.bottom;
int left = (l+1000) * vWidth/2000;
int top = (t+1000) * vHeight/2000;
int right = (r+1000) * vWidth/2000;
int bottom = (b+1000) * vHeight/2000;
canvas.drawRect(
left, top, right, bottom,
drawingPaint);
}
}else{
canvas.drawColor(Color.TRANSPARENT);
}
}
}

You can take a screenshot of your phone by physically pressing a combination of buttons. Thus, I guess there should be a way to do this programmatically, probably by overriding a callback somewhere. Check here: How to programmatically take a screenshot in Android?
But remember that when you are taking the screenshot, the image will have the same resolution of the phone display, and on old devices it may be very low. A picture taken with the camera will have a far better resolution. You can still add your image on the picture taken by simply merging the two images together.

Related

Hide first item in the spinner

I working on the spinner , there are 5 items in the spinner , i just want to hide the first item in the spinner , not to remove ,just hide.Problem is that when i click on the spinner ,without selecting an item the api get hit by using first item_id , i just added the blank feild in the spinner at first position(0). it is working properly .Only issue is that the visibility of the first blank item.I want to hide that item. My code is as follows :
JSONArray staff_array;
List<String> owner_list =new ArrayList<String>();
final List<String> owner_id_list = new ArrayList<String>();
try
{
isEnabled(0); //To disable First Item
owner_list.add("");
owner_id_list.add("");
for (int i = 0; i <staff_array.length(); i++)
{
JSONObject staff_obj=staff_array.getJSONObject(i);
String fname=staff_obj.getString(FIRST_NAME);
String lname=staff_obj.getString(LAST_NAME);
owner_id_list.add(staff_obj.getString(STAFF_ID));
String staff_name=fname.concat(" "+lname);
owner_list.add(staff_name);
}
owner_list.add((String) getText(R.string.unassigned));
owner_id_list.add("0");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayAdapter<String> owner_Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,owner_list);
owner_Adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(owner_Adapter);
int owner_Position = owner_Adapter.getPosition(tv_owner.getText().toString());
spin.setSelection(owner_Position);
spin.performClick();
spin.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// TODO Auto-generated method stub
String selected_owner = parent.getItemAtPosition(pos).toString();
String staff_id=owner_id_list.get(pos);
//*************************
Toast.makeText(getApplicationContext(),selected_owner+" "+staff_id , Toast.LENGTH_SHORT).show();
Log.d("selected owner : ",selected_owner);
Log.d("staff id is blank : ",staff_id);
if(staff_id!="")
{
String owner_filter="&vis_ticket_id="+Ticket_id+"&vis_action=staff&vis_update_id="+staff_id;
UPDATE_OWNER_URL=op.getUrl(getApplicationContext(),"ticket","update_properties",owner_filter);
JSONArray owner_array ;
}
//*************************
try
{
owner_array = new editProperties(UPDATE_OWNER_URL).execute().get();
String result=owner_array.toString();
if(result.equals("[\"success\"]"))
{
new ticketDetails().execute(); // parse other ticket details using AsyncTask
//tv_owner.setText(selected_owner);
}
else {Operation.showToast(getApplicationContext(), R.string.error);}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Try this, the overridden getCount method will reduce the number of spinner items by 1. But overriding this method only will hide only the last item in the spinner. So we will override the getDropDownView method to offset (push up) all items by 1. The end result will be only item 0 (the first item) is hidden.
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.your_spinner_layout, spinnerArray) {
public View getDropDownView(int position, View convertView, ViewGroup parent) {
return super.getDropDownView(position + 1, convertView, parent);
}
public int getCount() {
return spinnerArray.size - 1;
}
};

Adding button(Imageview) to viewpager within sliding image activity

I am relatively new to Android development, my background being more php, html5 and the likes. I've studied, continue to take tutorials and am working on my first application which I've practically got the way I want it to be, save one particular item. I hope that you can help me, and to some, it is likely a simple response. But, I've tried and tried and cannot get things to work out without errors.
Basically, the application uses ViewPager, and has SlidingImageActivity as a class, so when images are loaded in full size (clicked from thumbnail) the images can be swiped from screen to screen.
I have action bar items, which rather than show in the overflow bar, I've created Image Button and placed in the xml below for the viewpager. It is the file - fullimageslider.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/grid_back_color"
tools:ignore="RtlHardcoded" >
<android.support.v4.view.ViewPager
android:id="#+id/image_slider"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/menu_zoom"
android:background="#color/grid_back_color" >
</android.support.v4.view.ViewPager>
<ImageButton
android:id="#+id/menu_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/save"
android:title="#string/menu_save" />
<ImageButton
android:id="#+id/menu_setaswallpaper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/set"
android:title="#string/menu_setaswallpaper" />
<ImageButton
android:id="#+id/menu_zoom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="43dp"
android:layout_toRightOf="#+id/menu_share"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/zoom"
android:title="#string/menu_zoom" />
<ImageButton
android:id="#+id/menu_share"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#+id/menu_setaswallpaper"
android:background="#color/grid_back_color"
android:padding="10dp"
android:src="#drawable/share"
android:title="#string/menu_share" />
</RelativeLayout>
I've added the buttons as you can see, below the viewpager. So that they remain on the bottom of the layout as the screen swipes.
My problem is, getting the buttons to function in the SlideImageActivity class. I'm not sure where to change the overflow menu tasks to the button tasks. I have removed the items I've created buttons for from the menu. And changed them into the above.
The following is the current SlideImageActivity class.
public class SlideImageActivity extends SherlockActivity
implements sensorEventListener {
int position;
String[] mAllImages,mAllImageCatName;
public DatabaseHandler db;
ImageView vp_imageview;
ViewPager viewpager;
int TOTAL_IMAGE;
private SensorManager sensorManager;
private boolean checkImage = false;
private long lastUpdate;
Handler handler;
Runnable Update;
boolean Play_Flag=false;
private Menu menu;
private DatabaseManager dbManager;
String Image_catName,Image_Url;
Bitmap bgr;
DisplayImageOptions options;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.fullimageslider);
db = new DatabaseHandler(this);
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
setTitle(Constant.CATEGORY_TITLE);
// Look up the AdView as a resource and load a request.
Intent i=getIntent();
position=i.getIntExtra("POSITION_ID", 0);
mAllImages=i.getStringArrayExtra("IMAGE_ARRAY");
mAllImageCatName=i.getStringArrayExtra("IMAGE_CATNAME");
TOTAL_IMAGE=mAllImages.length-1;
viewpager=(ViewPager)findViewById(R.id.image_slider);
handler=new Handler();
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(position);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int position) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int position) {
// TODO Auto-generated method stub
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.photo_menu, menu);
this.menu = menu;
//for when 1st item of view pager is favorite mode
FirstFav();
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem)
{
switch (menuItem.getItemId())
{
case android.R.id.home:
onBackPressed();
return true;
case R.id.menu_back:
position=viewpager.getCurrentItem();
position--;
if (position < 0) {
position = 0;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_next:
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
return true;
case R.id.menu_play:
if(Play_Flag)
{
handler.removeCallbacks(Update);
menuItem.setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
ShowMenu();
}
else
{
/*
* when Play_Flag false then Play
* but when image is last not start auto play
* now hide all menu when auto play start
*/
if(viewpager.getCurrentItem()==TOTAL_IMAGE)
{
Toast.LENGTH_SHORT).show();
}
else
{
AutoPlay();
menuItem.setIcon(getResources().getDrawable(R.drawable.stop));
Play_Flag=true;
HideMenu();
}
}
return true;
case R.id.menu_fav:
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
AddtoFav(position);//if size is zero i.e means that record not in database show
add to favorite
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
RemoveFav(position);
}
}
return true;
case R.id.menu_overflow:
//just override click
return true;
case R.id.menu_share:
position=viewpager.getCurrentItem();
(new ShareTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_save:
position=viewpager.getCurrentItem();
(new SaveTask(SlideImageActivity.this)).execute
(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY+mAllImageCatName[position]
+"/"+mAllImages[position]);
return true;
case R.id.menu_setaswallaper:
position=viewpager.getCurrentItem();
Intent intwall=new intent(getApplicationContext(), SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
case R.id.menu_zoom:
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;
default:
return super.onOptionsItemSelected(menuItem);
}
}
//add to favorite
public void AddtoFav(int position)
{
Image_catName=mAllImageCatName[position];
Image_Url=mAllImages[position];
db.AddtoFavorite(new Pojo(Image_catName, Image_Url));
Toast.makeText(getApplicationContext(),
"Added to Favorite", Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
//remove from favorite
public void RemoveFav(int position)
{
Image_Url=mAllImages[position];
db.RemoveFav(new Pojo(Image_Url));
Toast.makeText(getApplicationContext(), "Removed from
Favorite",Toast.LENGTH_SHORT).show();
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
//auto play slide show
public void AutoPlay()
{
Update=new Runnable() {
#Override
public void run() {
AutoPlay();
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
handler.removeCallbacks(Update);//when last image play mode goes to Stop
Toast.makeText(getApplicationContext(), "Last Image Auto Play Stoped",
Toast.LENGTH_SHORT).show();
menu.getItem(1).setIcon(getResources().getDrawable(R.drawable.play));
Play_Flag=false;
//Show All Menu when Auto Play Stop
ShowMenu();
}
viewpager.setCurrentItem(position);
}
};
handler.postDelayed(Update, 1500);
}
public void ShowMenu()
{
menu.getItem(0).setVisible(true);
menu.getItem(2).setVisible(true);
menu.getItem(3).setVisible(true);
menu.getItem(4).setVisible(true);
}
public void HideMenu()
{
menu.getItem(0).setVisible(false);
menu.getItem(2).setVisible(false);
menu.getItem(3).setVisible(false);
menu.getItem(4).setVisible(false);
}
public void FirstFav()
{
int first=viewpager.getCurrentItem();
String Image_id=mAllImages[first];
List<Pojo> pojolist=db.getFavRow(Image_id);
if(pojolist.size()==0)
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_id))
{
menu.getItem(3).setIcon(getResources().getDrawable(R.drawable.fav_hover));
}
}
}
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = getLayoutInflater();
}
#Override
public int getCount() {
return mAllImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_item, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner =(ProgressBar)imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault
(getApplicationContext()));
ImageLoader.getInstance().displayImage(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position], imageView, options, new
SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason
failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(SlideImageActivity.this, message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
getAccelerometer(event);
}
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
if (accelationSquareRoot >= 2) //
{
if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;
// Toast.makeText(this, "Device was shuffed", Toast.LENGTH_SHORT)
// .show();
if (checkImage) {
position=viewpager.getCurrentItem();
viewpager.setCurrentItem(position);
} else {
position=viewpager.getCurrentItem();
position++;
if (position == TOTAL_IMAGE) {
position = TOTAL_IMAGE;
}
viewpager.setCurrentItem(position);
}
checkImage = !checkImage;
}
}
#Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
if(dbManager == null){
dbManager = DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
}else if(dbManager.isDatabaseClosed()){
dbManager.init(getApplicationContext());
}
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
// unregister listener
super.onPause();
if(!dbManager.isDatabaseClosed())
dbManager.closeDatabase();
sensorManager.unregisterListener(this);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(Update);
sensorManager.unregisterListener(this);
if(dbManager != null)dbManager.closeDatabase();
}
public class SaveTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public SaveTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Downloading Image ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection)
myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/EC Images/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Toast.makeText(SlideImageActivity.this, "Image Saved Succesfully /",
Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
}
public class ShareTask extends AsyncTask<String , String , String>
{
private Context context;
private ProgressDialog pDialog;
String image_url;
URL myFileUrl;
String myFileUrl1;
Bitmap bmImg = null;
File file ;
public ShareTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Please Wait ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
try {
myFileUrl = new URL(args[0]);
//myFileUrl1 = args[0];
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
}
catch (IOException e)
{
e.printStackTrace();
}
try {
String path = myFileUrl.getPath();
String idStr = path.substring(path.lastIndexOf('/') + 1);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File (filepath.getAbsolutePath() + "/HD Wallpaper/");
dir.mkdirs();
String fileName = idStr;
file = new File(dir, fileName);
FileOutputStream fos = new FileOutputStream(file);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String args) {
// TODO Auto-generated method stub
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + file.getAbsolutePath()));
startActivity(Intent.createChooser(share, "Share Image"));
pDialog.dismiss();
}
}
}
As you can see the code implements the menu items, Share, Set as Wallpaper, Save and Zoom. These are the Imagebuttons I -want- to use and have set up on the above xml layout.
This is what I have for the buttons. But I have no idea where or how to add this, implement it into the ImageSliderActivity class.
Button clickButton = (Button) findViewById(R.id.menu_share);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
(new shareTask(SlideImageActivity.this)).execute(Constant.
SERVER_IMAGE_UPFOLDER_CATEGORY+
mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_save);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {position=viewpager.getCurrentItem();
newSaveTask(SlideImageActivity.this)).execute(Constant.SERVER_IMAGE_UPFOLDER_CATEGORY
+mAllImageCatName[position]+"/"+mAllImages[position]);
return true;
Button clickButton = (Button) findViewById(R.id.menu_setaswallpaper);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {position=viewpager.getCurrentItem();
Intent intwall=new Intent(getApplicationContext(),SetAsWallpaperActivity.class);
intwall.putExtra("WALLPAPER_IMAGE_URL", mAllImages);
intwall.putExtra("WALLPAPER_IMAGE_CATEGORY", mAllImageCatName);
intwall.putExtra("POSITION_ID", position);
startActivity(intwall);
return true;
Button clickButton = (Button) findViewById(R.id.menu_zoom);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
position=viewpager.getCurrentItem();
Intent intzoom=new Intent(getApplicationContext(),PinchZoom.class);
intzoom.putExtra("ZOOM_IMAGE_URL", mAllImages);
intzoom.putExtra("ZOOM_IMAGE_CATEGORY", mAllImageCatName);
intzoom.putExtra("POSITION_ID", position);
startActivity(intzoom);
return true;`
I hope I've made sense.If some one could please guide me in the right direction, I would greatly appreciate the help. Basically, I want to remove the overflow menu during the slidingimage activity, and use buttons at the bottom of the layout instead to implement those items. The layout works in the emulator and causes no error, but obviously when the buttons are clicked, nothing happens because I don't know where to add the button portion to the sliding activity class, without causing multiple errors.
Thanks so much for your time in advance!

Moving ball with accelerometer inside a view on camera preview in android

I have been searching and coding for 3 days now on this problem, no result :(
I made a camera overlay which the code is here + the Accelerometer
public class CameraActivity extends Activity implements SurfaceHolder.Callback, SensorEventListener {
Camera camera;
SurfaceView surfaceView;
SurfaceHolder surfaceHolder;
boolean previewing = false;
LayoutInflater controlInflater = null;
static String TAG = CameraActivity.class.getSimpleName();
// Accelerometer
private SensorManager mSensorManager;
private Sensor mAccelerometer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surface_view);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.camera_control,
null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
this.addContentView(viewControl, layoutParamsControl);
// Accelerometer
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager
.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Then in the camera_control.xml I have this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout_holder"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#android:color/transparent"
android:gravity="bottom" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/camera_red_button"
android:layout_alignLeft="#+id/camera_back_button"
android:layout_marginBottom="27dp"
android:src="#drawable/camera_accelerometer_red" />
</RelativeLayout>
and in the surface_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/camerapreview_holder"
>
<SurfaceView
android:id="#+id/camerapreview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
The Image View is a image for spirit level.
The idea is user needs to level the camera before she takes a photo. I have cleared all the un-nessessery code. The above code are working code.
Question:
I need to make a ball for the spirit level. it doesnt need to be the smoothest spirit level. If I can find the way to confine the ball within the spirit level and move it based on the Accelerometer results I will be as happy as Larry :)/
If someone please put me in the right direction regarding these 3 things:
confining the animation within an area
confinement area to be Circle, how to make it
Thanks in advance.
H.
Ok I have got the answer. Hope it can help someone. You need to use calculate the distance from the middle to the corner (radius) the offset the corners.
Also I have change the Accelerometor to Orientation Sensor which then I can get the 3d rotation of the phone in the X and Y Axis.
The following code is working code and I tested them. I am using the Android 2.3.3+
The ball movement is not very smooth as this is not the purpose of the application.
I think in order to smooth the movement you might need to add the timer and collision detection to it too. Please check the android sample.
I haven't refactor the code too yet. So this is not a production level code :)
Codes:
public class CameraActivity extends Activity implements SurfaceHolder.Callback,
SensorEventListener {
// Accelerometer
private SensorManager mSensorManager;
private Sensor mAccelerometer;
/** Called when the activity is first created. */
public static float x;
public static float y;
FrameLayout layout_holder;
FrameLayout ball_holder;
// private float hOriginSize;
float halfOfWidth;
int centerYOnImage;
private Sensor mOrientation;
// float viewInset = 14.0f; // I remove this simply to make the code cleaner. I used this to calculate the radius and the offset later on
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.surface_view);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
surfaceView = (SurfaceView) findViewById(R.id.camerapreview);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
controlInflater = LayoutInflater.from(getBaseContext());
View viewControl = controlInflater.inflate(R.layout.camera_control,
null);
LayoutParams layoutParamsControl = new LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
this.addContentView(viewControl, layoutParamsControl);
// Accelerometer
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mOrientation = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
mSensorManager.registerListener(this, mAccelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.ball);
CustomDrawableView mCustomDrawableView = new CustomDrawableView(this,
bitmap);
ball_holder = (FrameLayout) findViewById(R.id.ball_holder);
ball_holder.addView(mCustomDrawableView);
halfOfWidth = 40; // You can calculate this, I just put this so I can test it. This is the half of the width of target image - attached in the question
centerYOnImage = 40; // Not important :)
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// This method will update the UI on new sensor events
public void onSensorChanged(SensorEvent event) {
// float azimuth_angle = event.values[0];
x = event.values[1];
y = event.values[2];
// FIXME: Fine tune this for the image taking part
float ratio = 70.0f / 25.0f;
x = x * ratio;
y = y * ratio;
Log.d(TAG, "x and y: " + x + " " + y);
float maxDistance = 35; // To calculate this halfOfWidth - viewInset;
// to calculate between 2 distances
float distance = (float) Math.sqrt(((x) * (x)) + ((y) * (y)));
if (distance > maxDistance) {
float angle = (float) Math.atan2(x, y);
/ Get new point on the edge of the circle
y = (float) (Math.cos(angle) * maxDistance);
x = (float) (Math.sin(angle) * maxDistance);
}
x = x + 40; // 40 is the half od the distance of the full width
y = (y * -1.0f) + 40; // -1.0f is so orientation works like the actual spirit level
canUserTakePhoto(distance);
}
// Change the background
public void canUserTakePhoto(float treshold) {
if (treshold > 10) {
// Not Yet
} else {
// take it
}
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mOrientation,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public class CustomDrawableView extends ImageView {
Bitmap b;
public CustomDrawableView(Context context, Bitmap bitmap) {
super(context);
this.b = bitmap;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawBitmap(this.b, x, y, null);
invalidate();
}
}
#Override
public void onDestroy() // main thread stopped
{
super.onDestroy();
// wait for threads to exit before clearing app
System.runFinalizersOnExit(true);
// remove app from memory
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
if (previewing) {
camera.stopPreview();
previewing = false;
}
if (camera != null) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
previewing = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera.stopPreview();
camera.release();
camera = null;
previewing = false;
}
}
Cheers.

Android MediaPlayer seek bar current position thread issues

Hi I am new to android and I am learning by example. I am trying to make an activity that has a list view of all songs in my raw folder with media player controls at the bottom. I have everything working so far but I can't seem to get the SeekBar to stop force closing.
Here is the code:
public class music extends ListActivity implements Runnable {
private ArrayList<sound> mSounds = null;
private soundadapter mAdapter = null;
private ImageButton playbtn;
private SeekBar seekbar;
private int total;
private MediaPlayer mp = null;
private TextView selelctedFile = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.music);
selelctedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
seekbar.setProgress(0);
// create a simple list
mSounds = new ArrayList<sound>();
sound s = new sound();
s.setDescription("Rudolph The Red Nosed Reindeer");
s.setSoundResourceId(R.raw.rudolphtherednosereindeer);
mSounds.add(s);
s = new sound();
s.setDescription("Battery");
s.setSoundResourceId(R.raw.battery);
mSounds.add(s);
mAdapter = new soundadapter(this, R.layout.listitem, mSounds);
setListAdapter(mAdapter);
playbtn = (ImageButton) findViewById(R.id.play);
playbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
try {
if (mp.isPlaying()) {
mp.pause();
playbtn.setImageResource(android.R.drawable.ic_media_play);
} else {
mp.start();
playbtn.setImageResource(android.R.drawable.ic_media_pause);
}
} catch (Exception e) {
e.printStackTrace();
// TODO: handle exception
}
}
});
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id) {
sound s = (sound) mSounds.get(position);
if (mp != null) {
mp.reset();
mp.release();
}
mp = MediaPlayer.create(this, s.getSoundResourceId());
selelctedFile.setText(s.getDescription());
playbtn.setImageResource(android.R.drawable.ic_media_pause);
mp.start();
total = mp.getDuration();
seekbar.setMax(total);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
mp.seekTo(progress);
seekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
Thread.sleep(100);
}
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private Handler threadHandler = new Handler() {
public void handleMessage(Message msg) {
// super.handleMessage(msg);
// txt.setText(Integer.toString(msg.what));
seekbar.setProgress(msg.what);
}
};
#Override
protected void onPause() {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
if(mp != null) {
mp.stop();
mp.release();
mp = null;
}
}
}
and here is the error i keep getting when i click several times on different songs:
04-14 02:53:00.452: W/dalvikvm(27452): threadid=19: thread exiting with uncaught exception (group=0x40018560)
04-14 02:53:00.466: E/AndroidRuntime(27452): FATAL EXCEPTION: Thread-22
04-14 02:53:00.466: E/AndroidRuntime(27452): java.lang.IllegalStateException
04-14 02:53:00.466: E/AndroidRuntime(27452): at android.media.MediaPlayer.getCurrentPosition(Native Method)
04-14 02:53:00.466: E/AndroidRuntime(27452): at net.cybercore.collapsingfromwithin.music.run(music.java:145)
04-14 02:53:00.466: E/AndroidRuntime(27452): at java.lang.Thread.run(Thread.java:1019)
Line error 145 is :
int currentPosition = mp.getCurrentPosition();
I cannot for the life of me figure out why it works for 3 or 4 times playing and then it kills the app.
Any help is appreciated. I have already looked at several other sites for examples including http://www.androidhive.info/2012/03/android-building-audio-player-tutorial/ and http://www.androiddevblog.net/android/playing-audio-in-android
**
UPDATE
**
I think I fixed it. thanks for your help I found Thread using for seekbar on android mediaplayer so i changed it to
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (mp != null) {
int currentPosition = mp.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("My exeption" + e);
}
}
I still get the errors but they are not killing my app. I don't think this is right way to do it but its working.
You should prepare your media player when instanciating it.
A MediaPlayer object must first enter the Prepared state before playback can be started.
There are two ways (synchronous vs. asynchronous) that the Prepared state can be reached: either a call to prepare() (synchronous) which transfers the object to the Prepared state once the method call returns, or a call to prepareAsync() (asynchronous) which first transfers the object to the Preparing state after the call returns (which occurs almost right way) while the internal player engine continues working on the rest of preparation work until the preparation work completes. When the preparation completes or when prepare() call returns, the internal player engine then calls a user supplied callback method, onPrepared() of the OnPreparedListener interface, if an OnPreparedListener is registered beforehand via setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener).
Read it here
so you should call mp.prepare() after instanciating the player.
also you should make sure the media player in playing to run the run method. I'd start by adding
mp.isPlaying() to the while line.
while (mp != null && mp.isPlaying()) {
...
}
IllegalStateException means that you are on an illegal state to call that method, like for instance, if the player is stopped.
I'm not sure, but I think this will stop the run method when you pause the music. So you should try to avoid this. I create a boolean to identify that the player is playing or paused and use it on the while.

How can I repaint part of screen on blackberry while connections run?

I have two questions.
The first is about updating the UI, the second is when I try to connect to the camera to get a mjpeg stream and run getResponseCode(), the app locks there. The MDS shows a lot of data transferring.
I have some classes like ....:
Http extends Thread {
public abstract String getUrl();
public abstract String getBase64Encode();
public abstract void onReturn(int responseCode, InputStream is,int lenght);
protected abstract void onError(Exception e);
}
CameraHttp extends Http and MjpegHttp extends CameraHttp.
http connects to a URL which is the jpeg or mjpeg camera adresses.
I have a Camera Class. It starts a connection with the overridden method mjpegconnection.go();
I also have a static bitmap on ViewCam screen which extends MainScreen.
After it starts:
url = getUrl();
queryString = encodeURL(queryString);
byte postmsg[] = queryString.getBytes("UTF-8");
httpConnection = (HttpConnection) Connector.open(url
+ ";deviceside=false", Connector.READ_WRITE);
httpConnection.setRequestMethod(HttpConnection.GET);
httpConnection.setRequestProperty("Authorization", getBase64Encode());
os = httpConnection.openDataOutputStream();
for (int i = 0; i < postmsg.length; i++) {
os.write(postmsg[i]);
}
{
if (!cancel) {
System.out.println(httpConnection.getURL()+
" *****"+httpConnection.getPort());
System.out.println("onreturn oncesi"
+ httpConnection.getResponseCode());
onReturn(httpConnection.getResponseCode(), httpConnection
.openInputStream(),(int) httpConnection.getLength());
System.out.println("onreturn sornrası");
}
os.close();
httpConnection.close();
}
} catch (Exception e) {
System.out.println("hata " + e.getMessage());
try {
httpConnection.close();
Thread.sleep(60);
} catch (Exception ie) {
}
onError(e);
}
After dosomething
// decides mjpeg-jpeg stream
// if it is mjpeg, direct to parser,
// else it sets image with setImage() and return to connection with go();
public void parse(InputStream is, int lenght) {
try {
if (!type.isMjpegStream()) {
setImage(is, lenght);
System.gc();
StaticVar.ActiveCam.setConnected(true);
} else {
if (parser == null) {
parser = new JpegParser(is, this);
} else {
parser.setInputSteam(is, this);
}
parser.parse();
is.close();
}
} catch (Exception e) {
}
}
and
public void setImage(InputStream is, int lenght) {
byte[] raw = new byte[lenght];
try {
is.read(raw);
currentImage = Bitmap.createBitmapFromBytes(raw, 0, raw.length, 1);
ViewCam.ViewCam=currentImage; //static var.
} catch (IOException e) {
System.out.println("catche***********");
// TODO Auto-generated catch block
e.printStackTrace();
}
}
How can I repaint the screen to show the bitmap?
And my ViewCam
public class ViewCam extends MainScreen {
Header header;
String headerString;
public static Bitmap ViewCam;// cam image shows
private static Thread My;// runs connection
void OnStart() {
My = new Thread() {
public void run() {
System.out.println("ONSTART");
StaticVar.ActiveCam.go();
};
};
My.start();
Bitmap bitmap = Bitmap.getBitmapResource("res/main.png");
Bitmap bmp2 = ResizeImage.resizeBitmap(bitmap, Display.getWidth(),
Display.getHeight());
Background bg = BackgroundFactory.createBitmapBackground(bmp2);
this.setBackground(bg);
this.getMainManager().setBackground(bg);
}
public ViewCam() {
StaticVar.ActiveCam.getIp();
OnStart();
headerString ="Cam View";
header = new Header("res/bartop.png", headerString, 0);
add(header);
ViewCam = Bitmap.getBitmapResource("res/spexco_splash.png");
ViewCam = ResizeImage.bestFit(ViewCam, Display.getWidth(), Display
.getHeight());
BitmapField bf = new BitmapField(ViewCam);
add(bf);
}
}
Try Screen.invalidate()
public void invalidate(int x, int y, int width, int height)
Invalidates a region of this screen.
This method marks a region of this screen as needing a repaint. The repainting is handled later by the main event dispatch thread.
Note: Any thread can safely invoke this method, and does not require to synchronize on the event lock.
Overrides:
invalidate in class Manager
Parameters:
x - Left edge of the region in ContentRect coordinates.
y - Top edge of the region in ContentRect coordinates.
width - Width (in pixels) of the region.
height - Height (in pixels) of the region.

Resources