How to call method in java from c# code? - c#

I have written a method in android(java) i.e. is used to upload image to the server. I want this method to be called from c# code. How to go about i have no idea, the java code follows below?
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("imageName", imageName );
request.addProperty("base64String", compressedImageString);
//request.addProperty("compressedImageBitmap", compressedImageBitmap);
SoapSerializationEnvelope envelope = new
SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
try {
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject result = (SoapObject)envelope.bodyIn;
if(result != null)
{
Toast.makeText(getApplicationContext(), result.getProperty(0).toString(), Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
buttonBrowse = (Button) findViewById(R.id.buttonBrowse);
buttonBrowse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(position!= null){
showPopup(MainActivity.this, position);
}
}
#SuppressWarnings("deprecation")
private void showPopup(final Activity activity, Point position) {
int popupWidth = 120;
int popupHeight = 130;
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = layoutInflater.inflate(R.layout.activity_popup, linearLayout);
popupWindow = new PopupWindow(activity);
popupWindow.setContentView(popupView);
popupWindow.setWidth(popupWidth);
popupWindow.setHeight(popupHeight);
int offset_X = 85;
int offset_Y = 5;
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAtLocation(popupView, Gravity.NO_GRAVITY, position.x + offset_X, position.y + offset_Y);
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus){
int[] location = new int[2];
buttonBrowse.getLocationOnScreen(location);
position = new Point();
position.x = location[0];
position.y = location[1];
}
public void buttonGallery_Click(View v){
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
}
public void buttonTakePhoto_Click(View v){
TakePhoto();
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent){
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
selectedImageUri = intent.getData();
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
String path = selectedImageRealPath;
imageName = path.substring(path.lastIndexOf("/")+1, path.length());
imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
compressedImageString = imageCompression(selectedImageRealPath);
}
break;
case CAMERA_REQUEST:
try
{
if(resultCode == RESULT_OK){
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
compressedImageString = imageCompression(selectedImageRealPath);
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
break;
}
popupWindow.dismiss();
}
private void TakePhoto() {
ContentValues values = new ContentValues();
imageName = String.valueOf(System.currentTimeMillis());
values.put(MediaStore.Images.Media.TITLE, imageName);
selectedImageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, selectedImageUri);
startActivityForResult(intent, CAMERA_REQUEST);
}
private String imageCompression(String filePath) {
File imageFile = new File(filePath);
FileInputStream fis = null;
try
{
fis = new FileInputStream(imageFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 600, 300, false);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 90, baos );
byte[] b = baos.toByteArray();
String imageString = Base64.encodeToString(b, Base64.DEFAULT);
//byte[] imageByte = imageString.getBytes();
return imageString;
}
public String getRealPathFromURI(Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
}
I want to call the method on buttonBrowse from c#

You cannot call java code directly from C# code.
You can wrap java classes as COM
See the link below
http://www.rgagnon.com/javadetails/java-0045.html

Related

class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback result is always null

I have converted my old StartActivityForResult code to the new RegisterForActivityResult as StartActivityForResult is depreciated in the android API 29 and higher. My new code works perfectly, except that result in class ActivityResultCallback is always null. I need to be able to know when the user cancels the taking of the picture when they hit the back button, otherwise the app crashes (if a previous picture doesn't already exist) or a previously taken picture is processed again. My code (showing only the relevant code):
public class Photo : AppCompatActivity
{
public ImageView MyImageView;
public ImageButton camerabutton;
public bool PictureTaken = false;
private CurrentSubjectInfo MySubjectInfo;
private ActivityResultCallback _activityResultCallback;
private ActivityResultLauncher _activityResultLauncher;
private Uri uri;
protected override void OnCreate(Bundle bundle)
{
try
{
_activityResultCallback = new ActivityResultCallback();
_activityResultCallback.OnActivityResultCalled += ActivityResultCallback_ActivityResultCalled;
_activityResultLauncher = RegisterForActivityResult(new ActivityResultContracts.TakePicture(), _activityResultCallback);
RequestedOrientation = Android.Content.PM.ScreenOrientation.Portrait;
base.OnCreate(bundle);
SetContentView(Resource.Layout.Photo);
PictureTaken = false;
MySubjectInfo = new CurrentSubjectInfo("", "", "", "", "");
// retrieve subject information from previous activity
MySubjectInfo = Mybundle.GetParcelable("MySubjectInfo", Java.Lang.Class.FromType(typeof(CurrentSubjectInfo))) as CurrentSubjectInfo;
ImageButton camerabutton = FindViewById<ImageButton>(Resource.Id.button1);
MyImageView = FindViewById<ImageView>(Resource.Id.imageView1);
camerabutton.Click += (sender, evt) =>
{
var cameraispresent = CheckCameraHardware();
if (cameraispresent)
{
try
{
// get directory where pictures are stored
App._dir = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
// build file name
MySubjectInfo.Name = MySubjectInfo.Name.Replace(",", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(" ", "");
MySubjectInfo.Name = MySubjectInfo.Name.Replace(".", "");
var filename = MySubjectInfo.Name + ".jpg";
App._file = new File(App._dir, String.Format(filename, Guid.NewGuid()));
uri = FileProvider.GetUriForFile(this, this.ApplicationContext.PackageName + ".provider",App._file);
// launch camera activity
_activityResultLauncher.Launch(uri);
}
catch (Exception e)
{
// trap error and log it
};
}
};
}
}
Boolean CheckCameraHardware()
{
Android.Content.PM.PackageManager pm = PackageManager;
if (pm.HasSystemFeature(Android.Content.PM.PackageManager.FeatureCamera))
{
// this device has a camera
return true;
}
else
{
// no camera on this device
return false;
}
}
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
// result is always null, so I don't check it
try
{
// Because the resulting bitmap is rotated and too large, I set original orientation and resize
// suffice it to say it works perfectly so I won't post the code here
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
// save the resized bitmap, overwriting original file
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
// set the imageview to the resulting bitmap
MyImageView.SetImageBitmap (App.bitmap);
// cleanup
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
catch (Exception ex)
{
PictureTaken = false;
// trap and log error
}
}
}
This is the ActivityResultCallback class:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult = result as ActivityResult;
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
As stated all this code executes perfectly with no errors except that Java.Lang.Object result is always null. I need to know when the user cancels the camera activity, I would assume that Java.Lang.Object result would indicate cancelled but I get nothing. What am I missing?
Ok, after some playing around I noticed that the parameter Java.Lang.Object result in the ActivityResultCallback class was either true or false depending on what the user did with the camera. So I changed the class to:
public class ActivityResultCallback : Java.Lang.Object, IActivityResultCallback
{
public EventHandler<ActivityResult> OnActivityResultCalled;
public void OnActivityResult(Java.Lang.Object result)
{
ActivityResult activityResult;
if ((bool)result)
{
activityResult = new ActivityResult((int)Result.Ok, null);
} else
{
activityResult = new ActivityResult((int)Result.Canceled, null);
}
OnActivityResultCalled?.Invoke(this, activityResult);
}
}
In the ActivityResultCallback_ActivityResultCalled function, I modified it to this:
private void ActivityResultCallback_ActivityResultCalled(object sender, ActivityResult result)
{
try
{
if (result.ResultCode == (int)Result.Ok)
{
int height = 260;
int width = 200;
App.bitmap = App._file.Path.LoadAndResizeBitmap(width, height);
Bitmap bitmap = App.bitmap;
var filePath = App._file.AbsolutePath;
var stream = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
bitmap.Compress(Bitmap.CompressFormat.Jpeg, 100, stream);
stream.Close();
MyImageView.SetImageBitmap(App.bitmap);
bitmap = null;
App.bitmap = null;
PictureTaken = true;
}
}
catch (Exception ex)
{
// trap and log error
}
}
activityResult apparently has, at a minimum, two parameters, the result and data. I already had what I needed for data so I set that to null and cast Result.Ok or Result.Cancelled to int depending on whether result was true or false. I still don't totally understand how to use the new ActivityForResult API, but this works for me and I'm running with it.

Streaming SharpDX Bitmap from one device to another by converting to byte array

I'm trying to capture a bitmap from desktop and then stream that to another device on the local network via socket connection.
I have a working example of this using gdi that sends a bitmap via socket to the client device and renders it to a picture box, but this solution is pretty inefficient as I'm sending unchanged bitmaps and it requires a lot of cpu processing on the client.
I'll include this example as a reference point
public class Serial
public static byte[] BitmapToBytes(Bitmap bitmap) {
using(MemoryStream ms = new MemoryStream()) {
using(BinaryWriter bw = new BinaryWriter(ms)) {
using(MemoryStream msb = new MemoryStream()) {
bitmap.Save(msb, ImageFormat.Jpeg);
byte[] bitmapBytes = msb.ToArray();
bw.Write(bitmapBytes.Length);
bw.Write(bitmapBytes);
return ms.ToArray();
}
}
}
}
public static Bitmap BytesToBitmap(byte[] bytes) {
using(MemoryStream ms = new MemoryStream(bytes)) {
using(BinaryReader br = new BinaryReader(ms)) {
int len = br.ReadInt32();
byte[] bitmapBytes = br.ReadBytes(len);
if(len == bitmapBytes.Length) {
using(MemoryStream msb = new MemoryStream(bitmapBytes)) {
return new Bitmap(msb);
}
} else {
return null;
}
}
}
}
}
public class Send {
private ClientInfo Instance;
public Send(ClientInfo instance) {
Instance = instance;
}
public void Bitmap(Bitmap bitmap) {
if(!Instanced) { return; }
Instance.SendMessage((uint)Code.Bitmap, Serial.BitmapToBytes(bitmap));
}
}
public class Server { //Same code for Client
public event EventHandler<BitmapEventArgs> BitmapReceived = delegate { };
//Socket connection setup code stripped as it's not relevant
private void Data_Received(ClientInfo c, uint code, byte[] bytes, int len) {
switch((Code)code) {
case Code.BitmapReceived:
BitmapReceived(this, new BitmapEventArgs(Serial.BytesToBitmap(bytes)));
break;
}
}
}
public partial class Form1 : Form {
private Client Client;
private Server Server;
private Send Send;
private void StartSocket() {
new Thread(() => {
StopSocket();
Client = new Client();
Client.ClientConnected += Client_Connected;
Client.ClientDisconnected += Client_Disconnected;
Client.BitmapReceived += Bitmap_Received;
if(!Client.Start(Config.Connection.IP, Config.Connection.Port)) {
Client = null;
Server = new Server();
Server.ClientConnected += Client_Connected;
Server.ClientDisconnected += Client_Disconnected;
Server.BitmapReceived += Bitmap_Received;
Server.Start(Config.Connection.Port);
}
}).Start();
}
private void Client_Connected(object sender, EventArgs e) {
if(sender is Server) {
Send = new Send(Server.Instance);
} else {
Send = new Send(Client.Instance);
}
}
private void SendBitmap() {
if(Send == null) { return; }
new Thread(() => {
while(Send != null) {
Bitmap b = CaptureBitmap();
if(b != null) {
Send.Bitmap(b);
Thread.Sleep(16); //around 60 times a second
}
}
}).Start();
}
private void Bitmap_Received(object sender, BitmapEventArgs e) {
if(Send != null && e.Bitmap != null) {
BitmapPicBox.Image = e.Bitmap;
}
}
private Bitmap CaptureBitmap() {
IntPtr deskHandle = WinApi.GetDesktopWindow();
IntPtr dc = WinApi.GetWindowDC(deskHandle);
if(dc != IntPtr.Zero) {
if(WinApi.GetWindowRect(deskHandle, out WinApi.RECT winRect)) {
IntPtr hdcDest = WinApi.CreateCompatibleDC(dc);
IntPtr hBitmap = WinApi.CreateCompatibleBitmap(dc, winRect.Width, winRect.Height);
IntPtr hOld = WinApi.SelectObject(hdcDest, hBitmap);
if(WinApi.BitBlt(hdcDest, 0, 0, winRect.Width, winRect.Height, dc, winRect.Left, winRect.Top, WinApi.TernaryRasterOperations.SRCCOPY)) {
WinApi.SelectObject(hdcDest, hOld);
WinApi.DeleteDC(hdcDest);
WinApi.ReleaseDC(deskHandle, dc);
Bitmap b = Image.FromHbitmap(hBitmap);
WinApi.DeleteObject(hBitmap);
return b;
} else {
WinApi.DeleteDC(hdcDest);
WinApi.ReleaseDC(deskHandle, dc);
WinApi.DeleteObject(hBitmap);
}
}
}
return null;
}
}
I have since tried a SharpDX implementation. I used the example from this github project for getting desktop image by desktop duplication and feeding that to a panel on the form which renders it.
But I'm not sure how I'd integrate this into my socket connection, I'd need to pass the frame being created as a byte array, and then back into a Bitmap1 that can be rendered.
Receiving the byte array and converting to Bitmap1 would be here:
private void RenderDuplicatedFrame(byte[] bitmapBytes) {
//Convert bitmapBytes to SharpDX.Direct2D1.Bitmap1
SharpDX.Direct2D1.Bitmap1 bitmap = //???
_backBufferDc.Value.BeginDraw();
_backBufferDc.Value.Clear(new RawColor4(0, 0, 0, 1));
using(bitmap) {
var renderX = (Size.Width - RenderSize.Width) / 2;
var renderY = (Size.Height - RenderSize.Height) / 2;
_backBufferDc.Value.DrawBitmap(bitmap, new RawRectangleF(renderX, renderY, renderX + RenderSize.Width, renderY + RenderSize.Height), 1, BitmapInterpolationMode.Linear);
}
_backBufferDc.Value.EndDraw();
_swapChain.Value.Present(1, 0);
}
Sending the Bitmap1 would be here:
private void AcquireFrame() {
var od = _outputDuplication.Value;
SharpDX.DXGI.Resource frame;
OutputDuplicateFrameInformation frameInfo;
od.AcquireNextFrame(500, out frameInfo, out frame);
using(frame) {
if(frameInfo.LastPresentTime != 0) {
using(var frameSurface = frame.QueryInterface<Surface>()) {
using(var frameDc = new SharpDX.Direct2D1.DeviceContext(_2D1Device.Value, DeviceContextOptions.EnableMultithreadedOptimizations)) {
using(var frameBitmap = new Bitmap1(frameDc, frameSurface)) {
//Convert frameBitmap to byte array here to send over socket
}
}
}
}
od.ReleaseFrame();
}
}
So how do I go about converting to and from a byte array?

Screen capturing in C#/UWP

i am working with UWP desktop window app and I am trying to implement the functionality of taking the screenshots with saving it to a local file, but i got the error message :
System.NullReferenceException: 'Object reference not set to an instance of an object.
on await frame.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f); in the method SaveImageAsync.
Could you tell me what is going wrong?
namespace App5
{
public sealed partial class MainPage : Page
{
private SizeInt32 _lastSize;
private GraphicsCaptureItem _item;
private Direct3D11CaptureFramePool _framePool;
private GraphicsCaptureSession _session;
private CanvasDevice _canvasDevice;
private CompositionGraphicsDevice _compositionGraphicsDevice;
private Compositor _compositor;
private CompositionDrawingSurface _surface;
private CanvasBitmap _currentFrame;
private string _screenshotFilename = "test.png";
public MainPage()
{
this.InitializeComponent();
Setup();
}
private void Setup()
{
_canvasDevice = new CanvasDevice();
_compositionGraphicsDevice = CanvasComposition.CreateCompositionGraphicsDevice(
Window.Current.Compositor,
_canvasDevice);
_compositor = Window.Current.Compositor;
_surface = _compositionGraphicsDevice.CreateDrawingSurface(
new Size(400, 400),
DirectXPixelFormat.B8G8R8A8UIntNormalized,
DirectXAlphaMode.Premultiplied);
var visual = _compositor.CreateSpriteVisual();
visual.RelativeSizeAdjustment = Vector2.One;
var brush = _compositor.CreateSurfaceBrush(_surface);
brush.HorizontalAlignmentRatio = 0.5f;
brush.VerticalAlignmentRatio = 0.5f;
brush.Stretch = CompositionStretch.Uniform;
visual.Brush = brush;
ElementCompositionPreview.SetElementChildVisual(this, visual);
}
public async Task StartCaptureAsync()
{
var picker = new GraphicsCapturePicker();
GraphicsCaptureItem item = await picker.PickSingleItemAsync();
if (item != null)
{
StartCaptureInternal(item);
}
}
private void StartCaptureInternal(GraphicsCaptureItem item)
{
// Stop the previous capture if we had one.
StopCapture();
_item = item;
_lastSize = _item.Size;
_framePool = Direct3D11CaptureFramePool.Create(
_canvasDevice, // D3D device
DirectXPixelFormat.B8G8R8A8UIntNormalized, // Pixel format
2, // Number of frames
_item.Size); // Size of the buffers
_framePool.FrameArrived += (s, a) =>
{
using (var frame = _framePool.TryGetNextFrame())
{
ProcessFrame(frame);
}
};
_item.Closed += (s, a) =>
{
StopCapture();
};
_session = _framePool.CreateCaptureSession(_item);
_session.StartCapture();
}
public void StopCapture()
{
_session?.Dispose();
_framePool?.Dispose();
_item = null;
_session = null;
_framePool = null;
}
private void ProcessFrame(Direct3D11CaptureFrame frame)
{
bool needsReset = false;
bool recreateDevice = false;
if ((frame.ContentSize.Width != _lastSize.Width) ||
(frame.ContentSize.Height != _lastSize.Height))
{
needsReset = true;
_lastSize = frame.ContentSize;
}
try
{
CanvasBitmap canvasBitmap = CanvasBitmap.CreateFromDirect3D11Surface(
_canvasDevice,
frame.Surface);
_currentFrame = canvasBitmap;
FillSurfaceWithBitmap(canvasBitmap);
}
catch (Exception e) when (_canvasDevice.IsDeviceLost(e.HResult))
{
needsReset = true;
recreateDevice = true;
}
if (needsReset)
{
ResetFramePool(frame.ContentSize, recreateDevice);
}
}
private void FillSurfaceWithBitmap(CanvasBitmap canvasBitmap)
{
CanvasComposition.Resize(_surface, canvasBitmap.Size);
using (var session = CanvasComposition.CreateDrawingSession(_surface))
{
session.Clear(Colors.Transparent);
session.DrawImage(canvasBitmap);
}
}
private void ResetFramePool(SizeInt32 size, bool recreateDevice)
{
do
{
try
{
if (recreateDevice)
{
_canvasDevice = new CanvasDevice();
}
_framePool.Recreate(
_canvasDevice,
DirectXPixelFormat.B8G8R8A8UIntNormalized,
2,
size);
}
catch (Exception e) when (_canvasDevice.IsDeviceLost(e.HResult))
{
_canvasDevice = null;
recreateDevice = true;
}
} while (_canvasDevice == null);
}
private async void Button_ClickAsync(object sender, RoutedEventArgs e)
{
await StartCaptureAsync();
await SaveImageAsync(_screenshotFilename, _currentFrame);
}
private async Task SaveImageAsync(string filename, CanvasBitmap frame)
{
StorageFolder pictureFolder = KnownFolders.SavedPictures;
StorageFile file = await pictureFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await frame.SaveAsync(fileStream, CanvasBitmapFileFormat.Png, 1f);
}
}
}
}
This code is from a Windows Forms .Net Core project, but I just pasted in a WPF project and it works.
In WPF you have to add Nuget package System.Drawing.Common:
You also have to add references to:
using System.Windows.Forms;
using WindowsFormsIntegration;
using System.Drawing;
// take a screenshot
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
Graphics graphics = Graphics.FromImage(bitmap);
graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);
// to save:
bitmap.Save(fileName);
The above code came from this project. I helped someone create sub images and search for sub images in a larger image. They had the screenshot code.
https://github.com/DataJuggler/SubImageCreator
This project is used to create sub images from a larger image and search for sub images in a larger image.

Client cannot connect to Wcf Service

I would like to upload file to wcf service from android. The service already open but every time connect to the service it fail, stuck at .connect().
After few minutes it throw Exception:
failed to connect to /10.16.2.56 (port 80): connect failed: ETIMEDOUT
(Connection timed out)
I configure my wcf side almost same as this, please help!
Here my code of android :
try
{
Bitmap bm = BitmapFactory.decodeFile(imgPath);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
HttpParams httpParameters = new BasicHttpParams();
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost postRequest = new HttpPost("http://10.16.2.37/wcf3/service1.svc/GetStream");
ByteArrayBody bab =new ByteArrayBody(data,"001.jpg");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addPart("uploaded", bab);
HttpEntity entity = builder.build();
postRequest.setEntity(entity);
System.out.println("2");
HttpResponse response = httpClient.execute(postRequest);
System.out.println("response");
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
System.out.println("Response: " + s);
}
}
catch (Exception e)
{
System.out.println(e.getClass().getName() + ": " + e.getMessage());
}
Its worked for me.
package databaseconnect.databaseconnect;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class MainActivity extends Activity {
private static String SOAP_ACTION = "http://example.com/IService1/InsertData";
private static String NAMESPACE = "http://example.com/";
private static String METHOD_NAME = "InsertData";
private static String URL = "http://example.com/Service1.svc?wsdl";
Button Save,Clear;
EditText name,mobile,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.editText);
mobile = (EditText) findViewById(R.id.editText2);
email = (EditText) findViewById(R.id.editText3);
Save=(Button)findViewById(R.id.button);
Clear=(Button)findViewById((R.id.clear));
Save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AsyncCallWS task = new AsyncCallWS();
task.execute();
}
});
Clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name.setText("");
mobile.setText("");
email.setText("");
}
});
}
private class AsyncCallWS extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params)
{
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("name", name.getText().toString());
request.addProperty("mobile", mobile.getText().toString());
request.addProperty("email", email.getText().toString());
//request.addProperty("name", "testuser");
// request.addProperty("mobile", "123456789");
//request.addProperty("email", "sample#google.com");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
envelope.setOutputSoapObject(request);
String res=null;
try
{
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL,180000);
androidHttpTransport.debug=true;
androidHttpTransport.call(SOAP_ACTION, envelope);
} catch (Exception e)
{
name.setText(e.toString());
}
return null;
}
}
#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_main, 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);
}
}

Vibrate during play a ringtone in netcf C#

i need to vibrate the phone while playing a ringtone.
This is my code:
public static bool PlaySound(string soundName)
{
try
{
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
string MediaFile = Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(0, Assembly.GetExecutingAssembly().GetName().CodeBase.LastIndexOf("\\")) + "\\Resources\\" + soundName;
player.URL = MediaFile;
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
player.settings.volume = 100;
player.controls.play();
SetVibrate(true);
System.Threading.Thread.Sleep((int)wmp.newMedia(MediaFile).duration*1000 + 100);
SetVibrate(false);
return true;
}
catch
{
return false;
}
}
My problem is that the phone FIRST vibrate, then Play sound.. is not possibile to vibrate for the duration of the sound?
thanks.
#x86shadow: I tried with thread but not working :(
public static bool PlaySound(string soundName)
{
try
{
// 29/11/2010 Luca - Aggiungo vibrazione durante il suono del messaggio.
WMPLib.WindowsMediaPlayer player = new WMPLib.WindowsMediaPlayer();
string MediaFile = Assembly.GetExecutingAssembly().GetName().CodeBase.Substring(0, Assembly.GetExecutingAssembly().GetName().CodeBase.LastIndexOf("\\")) + "\\Resources\\" + soundName;
player.URL = MediaFile;
WindowsMediaPlayerClass wmp = new WindowsMediaPlayerClass();
player.settings.volume = 100;
RingDuration = (int) wmp.newMedia(MediaFile).duration*1000 + 100;
VibrateWhilePlayingThread = new Thread(VibrateWhilePlaying);
VibrateWhilePlayingThread.Start();
player.controls.play();
VibrateWhilePlayingThread.Join();
return true;
}
catch
{
return false;
}
}
private static int RingDuration;
public static Thread VibrateWhilePlayingThread;
public static void VibrateWhilePlaying()
{
SetVibrate(true);
System.Threading.Thread.Sleep(RingDuration);
SetVibrate(false);
}
Adding an EventHandler:
Player.PlayStateChanged += new AxWMPLib._WMPOCXEvents_PlayChangeEventHandler(player_PlayStateChange);
Try to create an Event:
private void player_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if (Player.playState == WMPLib.WMPPlayState.wmppsPlaying)
{
SetVibrate(true);
}
else
{
SetVibrate(false);
}
}

Categories

Resources