How to save current location? - xamarin.forms

I have a question. I am working on mobile app where my user can store experience from trip by loggin current location.
I am connected to SQLite fo now and I am just exploring the Geolocator nuget from James Monemagno. SO far I can get the pin on map with current location, but I am unsure how to store the location in databse. I guess it wont be"position" and it must be Latitude and Longitude but then how will i get again the picture with the pin displayed under my post? Do you guys have some experience?
Public clas NoteViewMode : BaseViewModel
{
/////
private string _location;
public string Location
{
get { return _location; }
set
{
_location = value;
OnPropertyChanged();
}
}
public double _latitude;
public double Latitude
{
get { return _latitude; }
set
{
_latitude = value;
OnPropertyChanged();
}
}
private double _longitude;
public double Longitude
{
get { return _longitude; }
set
{
_longitude = value;
OnPropertyChanged();
}
}
}
public Map()
{
InitializeComponent();
GetPremissions();
BindingContext = ViewModel = new AdLogEntryViewModel();
}
private async void GetPremissions()
{
try
{
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (status != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
{
await DisplayAlert("We need location", "", "Ok");
}
var result = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse);
if (result.ContainsKey(Plugin.Permissions.Abstractions.Permission.LocationWhenInUse))
status = result[Plugin.Permissions.Abstractions.Permission.LocationWhenInUse];
}
if (status == Plugin.Permissions.Abstractions.PermissionStatus.Granted)
{
locationsMap.IsShowingUser = true;
hasLocationPermission = true;
GetLocation();
}
else
{
await DisplayAlert("Location denied", "", "");
}
}
catch (Exception ex)
{
await DisplayAlert("erroe", ex.Message, "ok");
}
}
protected override async void OnAppearing()
{
base.OnAppearing();
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
locator.PositionChanged += Locator_PositionChanged;
await locator.StartListeningAsync(TimeSpan.Zero, 100);
}
GetLocation();
}
protected override void OnDisappearing()
{
base.OnDisappearing();
CrossGeolocator.Current.StopListeningAsync();
CrossGeolocator.Current.PositionChanged -= Locator_PositionChanged;
}
void Locator_PositionChanged(object sender, Plugin.Geolocator.Abstractions.PositionEventArgs e)
{
MoveMap(e.Position);
}
private async void GetLocation()
{
if (hasLocationPermission)
{
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync();
MoveMap(position);
}
}
private async void MoveMap(Position position)
{
var center = new Xamarin.Forms.Maps.Position(position.Latitude, position.Longitude);
var span = new Xamarin.Forms.Maps.MapSpan(center, 1, 1);
locationsMap.MoveToRegion(span);
}

you can programmatically add a Pin to a Map
Pin pin = new Pin
{
Label = "Santa Cruz",
Address = "The city with a boardwalk",
Type = PinType.Place,
Position = new Position(36.9628066, -122.0194722)
};
map.Pins.Add(pin);

Related

Circuit Breaker with gRPC

In a REST service adding a circuit breaker with hystrix, I could do the following:
#HystrixCommand(fallbackMethod = "getBackupResult")
#GetMapping(value = "/result")
public ResponseEntity<ResultDto> getResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = service.parserRequest(someRequest);
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
public ResponseEntity<ResultDto> getBackupResult(#RequestParam("request") String someRequest) {
ResultDto resultDto = new ResultDto();
return new ResponseEntity<>(resultDto, HttpStatus.OK);
}
Is there something similar I can do for the gRPC call?
public void parseRequest(ParseRequest request, StreamObserver<ParseResponse> responseObserver) {
try {
ParseResponse parseResponse = service.parseRequest(request.getSomeRequest());
responseObserver.onNext(parseResponse);
responseObserver.onCompleted();
} catch (Exception e) {
logger.error("Failed to execute parse request.", e);
responseObserver.onError(new StatusException(Status.INTERNAL));
}
}
I solved my problem by implementing the circuit-breaker on my client. I used the sentinel library
To react on exceptions ratio for example I added this rule:
private static final String KEY = "callGRPC";
private void callGRPC(List<String> userAgents) {
initDegradeRule();
ManagedChannel channel = ManagedChannelBuilder.forAddress(grpcHost, grpcPort).usePlaintext()
.build();
for (String userAgent : userAgents) {
Entry entry = null;
try {
entry = SphU.entry(KEY);
UserAgentServiceGrpc.UserAgentServiceBlockingStub stub
= UserAgentServiceGrpc.newBlockingStub(channel);
UserAgentParseRequest request = UserAgentRequest.newBuilder().setUserAgent(userAgent).build();
UserAgentResponse userAgentResponse = stub.getUserAgentDetails(request);
} catch (BlockException e) {
logger.error("Circuit-breaker is on and the call has been blocked");
} catch (Throwable t) {
logger.error("Exception was thrown", t);
} finally {
if (entry != null) {
entry.exit();
}
}
}
channel.shutdown();
}
private void initDegradeRule() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(KEY);
rule.setCount(0.5);
rule.setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
rule.setTimeWindow(60);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}

Long tap and drop pin in xamarin forms maps

I used Xamarin.Forms.Maps nuget package and displayed map on the device. I am able to show the pin on external button tap with the help of following code, but unable to achieve same on map tap to drop a pin on a specific location.
public void addPin(double latitude, double longitude, string labelName)
{
Position position = new Position(latitude, longitude);
_assignedPin = new Pin
{
Type = PinType.Place,
Position = position,
Label = labelName,
Address = "custom detail info"
};
map.Pins.Add(_assignedPin);
}
I followed this blog to get lat long on map, but map does not display the pin on the map.
We need to add the code in renderer itself to drop pin using xamarin.forms.maps
In Android: Renderer class:
private void googleMap_MapClick(object sender, GoogleMap.MapClickEventArgs e)
{
Map.Pins.Add(new Pin
{
Label = "Pin from tap",
Position = new Position(e.Point.Latitude, e.Point.Longitude))
}
}
And in iOS Renderer class:
[assembly: ExportRenderer(typeof(ExtMap), typeof(ExtMapRenderer))]
namespace Xamarin.iOS.CustomRenderers
{
/// <summary>
/// Renderer for the xamarin ios map control
/// </summary>
public class ExtMapRenderer : MapRenderer
{
private readonly UITapGestureRecognizer _tapRecogniser;
public ExtMapRenderer()
{
_tapRecogniser = new UITapGestureRecognizer(OnTap)
{
NumberOfTapsRequired = 1,
NumberOfTouchesRequired = 1
};
}
protected override IMKAnnotation CreateAnnotation(Pin pin)
{
return base.CreateAnnotation(pin);
}
class BasicMapAnnotation : MKAnnotation
{
CLLocationCoordinate2D coord;
string title, subtitle;
public override CLLocationCoordinate2D Coordinate { get { return coord; } }
public override void SetCoordinate(CLLocationCoordinate2D value)
{
coord = value;
}
public override string Title { get { return title; } }
public override string Subtitle { get { return subtitle; } }
public BasicMapAnnotation(CLLocationCoordinate2D coordinate, string title, string subtitle)
{
this.coord = coordinate;
this.title = title;
this.subtitle = subtitle;
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
}
private async void OnTap(UITapGestureRecognizer recognizer)
{
var cgPoint = recognizer.LocationInView(Control);
var nativeMap = Control as MKMapView;
var location = ((MKMapView)Control).ConvertPoint(cgPoint, Control);
((ExtMap)Element).OnTap(new Position(location.Latitude, location.Longitude));
try
{
var lat = location.Latitude;
var lon = location.Longitude;
var placemarks = await Geocoding.GetPlacemarksAsync(lat, lon);
var placemark = placemarks?.FirstOrDefault();
if (placemark != null)
{
var geocodeAddress =
$"AdminArea: {placemark.AdminArea}\n" +
$"CountryCode: {placemark.CountryCode}\n" +
$"CountryName: {placemark.CountryName}\n" +
$"FeatureName: {placemark.FeatureName}\n" +
$"Locality: {placemark.Locality}\n" +
$"PostalCode: {placemark.PostalCode}\n" +
$"SubAdminArea: {placemark.SubAdminArea}\n" +
$"SubLocality: {placemark.SubLocality}\n" +
$"SubThoroughfare: {placemark.SubThoroughfare}\n" +
$"Thoroughfare: {placemark.Thoroughfare}\n";
Console.WriteLine(geocodeAddress);
var annotation = new BasicMapAnnotation(new CLLocationCoordinate2D(lat, lon), placemark.Thoroughfare, placemark.SubThoroughfare);
nativeMap.AddAnnotation(annotation);
}
}
catch (FeatureNotSupportedException fnsEx)
{
// Feature not supported on device
Console.WriteLine(fnsEx);
}
catch (Exception ex)
{
// Handle exception that may have occurred in geocoding
Console.WriteLine(ex);
}
}
protected override void OnElementChanged(ElementChangedEventArgs<View> e)
{
if (Control != null)
Control.RemoveGestureRecognizer(_tapRecogniser);
base.OnElementChanged(e);
if (Control != null)
Control.AddGestureRecognizer(_tapRecogniser);
}
}
}

How do you print TextArea to a USB Thermal Printer 58mm?(JAVAFX)

So I'm trying to make a billing system in which I want to print a receipt.I was able to do it with some code that I found online,but the font size is too big to print in the 58mm wide paper.I'm not able to adjust the font size.Any kind of help with this issue will be highly appreciated.Thank You.
Here is The Code :
public class PrinterService implements Printable {
public List<String> getPrinters(){
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printServices[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
List<String> printerList = new ArrayList<String>();
for(PrintService printerService: printServices){
printerList.add( printerService.getName());
}
return printerList;
}
#Override
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException {
if (page > 0) { /* We have only one page, and 'page' is zero-based */
return NO_SUCH_PAGE;
}
/*
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
*/
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX(), pf.getImageableY());
/* Now we perform our rendering */
g.setFont(new Font("Roman", 0, 8));
g.drawString("Hello world !", 0, 10);
return PAGE_EXISTS;
}
public void printString(String printerName, String text) {
// find the printService of name printerName
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printService[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
PrintService service = findPrintService(printerName, printService);
DocPrintJob job = service.createPrintJob();
try {
byte[] bytes;
// important for umlaut chars
bytes = text.getBytes("CP437");
Doc doc = new SimpleDoc(bytes, flavor, null);
job.print(doc, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void printBytes(String printerName, byte[] bytes) {
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
PrintService printService[] = PrintServiceLookup.lookupPrintServices(
flavor, pras);
PrintService service = findPrintService(printerName, printService);
DocPrintJob job = service.createPrintJob();
try {
Doc doc = new SimpleDoc(bytes, flavor, null);
job.print(doc, null);
} catch (Exception e) {
e.printStackTrace();
}
}
private PrintService findPrintService(String printerName,
PrintService[] services) {
for (PrintService service : services) {
if (service.getName().equalsIgnoreCase(printerName)) {
return service;
}
}
return null;
}
}
#FXML
public void printit(ActionEvent actionEvent)
{
PrinterService printerService = new PrinterService();
System.out.println(printerService.getPrinters());
//print some stuff
printerService.printString("POS-58-Series", area.getText());
}

Fail to connect to camera service at sometimes

Am calling my camera function as separate fragment during first 2 times of calling the class camera is opening but if am calling the class third time app is crashing.
private int findFrontFacingCamera() {
int cameraId = 0;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
logcat
01-19 10:56:15.164 11477-11477/com.example.siva.prep E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.siva.prep, PID: 11477
java.lang.RuntimeException: Fail to connect to camera service
at android.hardware.Camera.native_setup(Native Method)
at android.hardware.Camera.<init>(Camera.java:393)
at android.hardware.Camera.open(Camera.java:347)
at com.example.siva.prep.Selfie.onResume(Selfie.java:146)
It's showing error on the following line in "onResume()" method:
mCamera = Camera.open(findFrontFacingCamera());
Here is the full my code am using:
public class Selfie extends Fragment implements OnClickListener {
private Camera mCamera;
private CameraPreview mPreview;
private PictureCallback mPicture;
private Button capture, switchCamera;
private Context myContext;
private LinearLayout cameraPreview;
private boolean cameraFront = false;
Bitmap bmp;
ImageView iv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_selfie, container, false);
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
iv=(ImageView) view.findViewById(R.id.image);
myContext = getActivity().getApplicationContext();
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
cameraPreview = (LinearLayout) view.findViewById(R.id.camera_preview);
mPreview = new CameraPreview(myContext, mCamera);
cameraPreview.addView(mPreview);
ImageView capture = (ImageView) view.findViewById(R.id.button_capture);
capture.setOnClickListener(captrureListener);
ImageView switchCamera = (ImageView) view.findViewById(R.id.button_ChangeCamera);
switchCamera.setOnClickListener(switchCameraListener);
ImageView button1 = (ImageView) view.findViewById(R.id.back);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FreeFragment fragment2 = new FreeFragment();
FragmentManager fragmentManager = getFragmentManager();
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.container, fragment2);
fragmentTransaction.commit();
}
});
getSupportActionBar().hide();
return view;
}
private ActionBar getSupportActionBar() {
return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
#Override
public void onClick(View v) {
}
private int findFrontFacingCamera() {
int cameraId = 0;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
cameraId = i;
cameraFront = true;
break;
}
}
return cameraId;
}
private int findBackFacingCamera() {
int cameraId = -1;
//Search for the back facing camera
//get the number of cameras
int numberOfCameras = Camera.getNumberOfCameras();
//for every camera check
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_BACK) {
cameraId = i;
cameraFront = false;
break;
}
}
return cameraId;
}
public void onResume() {
super.onResume();
if (!hasCamera(myContext)) {
Toast toast = Toast.makeText(myContext, "Sorry, your phone does not have a camera!", Toast.LENGTH_LONG);
toast.show();
finish();
}
if (mCamera == null) {
//if the front facing camera does not exist
if (findFrontFacingCamera() < 0) {
Toast.makeText(getActivity().getApplicationContext(), "No front facing camera found.", Toast.LENGTH_LONG).show();
switchCamera.setVisibility(View.GONE);
}
mCamera = Camera.open(findFrontFacingCamera());
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
private void finish() {
}
OnClickListener switchCameraListener = new OnClickListener() {
#Override
public void onClick(View v) {
//get the number of cameras
int camerasNumber = Camera.getNumberOfCameras();
if (camerasNumber >= 1) {
//release the old camera instance
//switch camera, from the front and the back and vice versa
releaseCamera();
chooseCamera();
} else {
Toast toast = Toast.makeText(myContext, "Sorry, your phone has only one camera!", Toast.LENGTH_LONG);
toast.show();
}
}
};
public void chooseCamera() {
// if the camera preview is the front
if (cameraFront) {
int cameraId = findBackFacingCamera();
if (cameraId <= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
} else
{
int cameraId = findFrontFacingCamera();
if (cameraId >= 0) {
//open the backFacingCamera
//set a picture callback
//refresh the preview
mCamera = Camera.open(cameraId);
mPicture = getPictureCallback();
mPreview.refreshCamera(mCamera);
}
}
}
#Override
public void onPause() {
super.onPause();
//when on Pause, release camera in order to be used from other applications
releaseCamera();
}
private boolean hasCamera(Context context) {
//check if the device has camera
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
private PictureCallback getPictureCallback() {
PictureCallback picture = new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
//make a new picture file
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
//write the file
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast toast = Toast.makeText(myContext, "Picture saved: " + pictureFile.getName(), Toast.LENGTH_LONG);
iv.setImageURI(Uri.fromFile(pictureFile));
//Intent intent = new Intent(AndroidCameraExample.this,Fina.class);
String stringUri;
stringUri = pictureFile.toString();
//intent.putExtra("imagePath", stringUri);
//startActivity(intent);
FreeFragment ldf = new FreeFragment ();
Bundle args = new Bundle();
args.putString("Image", stringUri);
ldf.setArguments(args);
Log.d("Passing image", String.valueOf(args));
getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();
toast.show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
//refresh camera to continue preview
mPreview.refreshCamera(mCamera);
}
};
return picture;
}
//make picture and save to a folder
public static File getOutputMediaFile() {
//make a new file directory inside the "sdcard" folder
File mediaStorageDir = new File("/sdcard/", "JCG Camera");
//if this "JCGCamera folder does not exist
if (!mediaStorageDir.exists()) {
//if you cannot make this folder return
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
//take the current timeStamp
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
//and make a media file:
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
return mediaFile;
}
OnClickListener captrureListener = new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, mPicture);
}
};
private void releaseCamera() {
// stop and release camera
if (mCamera != null) {
mCamera.release();
mCamera = null;
}
}
}
Irrespective of the reason, not obtaining Camera handle is a case that needs to be handled with proper error handling. In the current case in your Pause handler, is the Camera instance being released ? Check for proper usage at http://developer.android.com/training/basics/activity-lifecycle/pausing.html

BlackBerry - Exception when sending SMS

The code below should send a text message to a mobile number. It currently fails to work properly.
When the program attempts a message, the following error is reported:
Blocking operation not permitted on event dispatch thread
I created a separate thread to execute the SMS code, but I am still observing the same exception.
What am I doing wrong?
class DummyFirst extends MainScreen {
private Bitmap background;
private VerticalFieldManager _container;
private VerticalFieldManager mainVerticalManager;
private HorizontalFieldManager horizontalFldManager;
private BackGroundThread _thread;
CustomControl buttonControl1;
public DummyFirst() {
super();
LabelField appTitle = new LabelField("Dummy App");
setTitle(appTitle);
background = Bitmap.getBitmapResource("HomeBack.png");
_container = new VerticalFieldManager(Manager.NO_VERTICAL_SCROLL
| Manager.NO_VERTICAL_SCROLLBAR) {
protected void paint(Graphics g) {
// Instead of these next two lines, draw your bitmap
int y = DummyFirst.this.getMainManager()
.getVerticalScroll();
g.clear();
g.drawBitmap(0, 0, background.getWidth(), background
.getHeight(), background, 0, 0);
super.paint(g);
}
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
mainVerticalManager = new VerticalFieldManager(
Manager.NO_VERTICAL_SCROLL |
Manager.NO_VERTICAL_SCROLLBAR) {
protected void sublayout(int maxWidth, int maxHeight) {
int width = background.getWidth();
int height = background.getHeight();
super.sublayout(width, height);
setExtent(width, height);
}
};
HorizontalFieldManager horizontalFldManager =
new HorizontalFieldManager(Manager.USE_ALL_WIDTH);
buttonControl1 = new CustomControl("Send", ButtonField.CONSUME_CLICK,
83, 15);
horizontalFldManager.add(buttonControl1);
this.setStatus(horizontalFldManager);
FieldListener listner = new FieldListener();
buttonControl1.setChangeListener(listner);
_container.add(mainVerticalManager);
this.add(_container);
}
class FieldListener implements FieldChangeListener {
public void fieldChanged(Field f, int context) {
if (f == buttonControl1) {
_thread = new BackGroundThread();
_thread.start();
}
}
}
private class BackGroundThread extends Thread {
public BackGroundThread() {
/*** initialize parameters in constructor *****/
}
public void run() {
// UiApplication.getUiApplication().invokeLater(new Runnable()
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
try {
MessageConnection msgConn =
(MessageConnection) Connector
.open("sms://:0");
Message msg = msgConn
.newMessage(
MessageConnection.TEXT_MESSAGE);
TextMessage txtMsg = (TextMessage) msg;
String msgAdr = "sms://+919861348735";
txtMsg.setAddress(msgAdr);
txtMsg.setPayloadText("Test Message");
// here exception is thrown
msgConn.send(txtMsg);
System.out.println("Sending" +
" SMS success !!!");
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} // run
});
}
}
public boolean onClose() {
System.out.println("close event called, request to be" +
" in the backgroud....");
UiApplication.getUiApplication().requestBackground();
return true;
}
}
Dec 14, 2009 Stella answered their own question:
I resolved this issue by creating a separate thread and then not using Port etc.
Here it is:
SMSThread smsthread = new SMSThread("Some message",mobNumber);
smsthread.start();
class SMSThread extends Thread {
Thread myThread;
MessageConnection msgConn;
String message;
String mobilenumber;
public SMSThread( String textMsg, String mobileNumber ) {
message = textMsg;
mobilenumber = mobileNumber;
}
public void run() {
try {
msgConn = (MessageConnection) Connector.open("sms://+"+ mobilenumber);
TextMessage text = (TextMessage) msgConn.newMessage(MessageConnection.TEXT_MESSAGE);
text.setPayloadText(message);
msgConn.send(text);
msgConn.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}

Resources