Is it possible to set borders for a PanGestureRecognizer so it can only pan an image in a limited area/view?
thank you very mutch ;)
You can implement the delegate methods for the UIPanGestureRecognizer. Check to see if the location of the gesture is in the bounds you are interested in. For the should* methods you can return false to cancel the gesture. Once the gesture has been started you can cancel it by setting the State property to Cancelled.
public class GestureView: UIView
{
RectangleF _bounds;
public GestureView (RectangleF rect) : base (rect)
{
this.BackgroundColor = UIColor.Brown;
UIPanGestureRecognizer pan = new UIPanGestureRecognizer (this, new Selector ("panViewWithGestureRecognizer:"));
this.AddGestureRecognizer (pan);
pan.WeakDelegate = this;
_bounds = new RectangleF (0,0,200, 100);
}
[Export("panViewWithGestureRecognizer:")]
void PanGestureMoveAround (UIPanGestureRecognizer p)
{
if (_bounds.Contains (p.LocationInView (this)))
{
Console.WriteLine ("PanGestureMoveAround true");
return;
}
Console.WriteLine ("PanGestureMoveAround false");
p.State = UIGestureRecognizerState.Cancelled;
return;
}
[Export ("gestureRecognizerShouldBegin:")]
bool ShouldBegin (UIGestureRecognizer recognizer)
{
if (_bounds.Contains (recognizer.LocationInView (recognizer.View)))
{
Console.WriteLine ("ShouldBegin true");
return true;
}
Console.WriteLine ("ShouldBegin false");
return false;
}
[Export ("gestureRecognizer:shouldReceiveTouch:")]
public bool ShouldReceiveTouch (UIGestureRecognizer recognizer, UITouch touch)
{
if (_bounds.Contains (touch.LocationInView (recognizer.View)))
{
Console.WriteLine ("ShouldReceiveTouch true");
return true;
}
Console.WriteLine ("ShouldReceiveTouch false");
return false;
}
}
Related
I have custom annotation which I have subClass from MKPointAnnotation. Adding those is working properly. I also need to detect the Annotation select method. The problem is when I tap on the annotation it doesn't hit the "DidSelectAnnotationView" at first. if I tap into another annotation like userLocation annotation then "DidSelectAnnotationView" hits. and while debugging it shows the coordinates of the annotation view is not the user location but the annotation I tap previously. and same happens after this when I tap my custom annotation it hits the method and coordinates of the method is not the userLocation one. I have added my code, could someone look into it where I missed the bits.
override public MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
string resuseId = "customAnnotation";
MKAnnotationView annotationView = mapView.DequeueReusableAnnotation(resuseId);
if (ThisIsTheCurrentLocation(mapView, annotation))
{
return null;
}
if (annotationView == null)
{
if (annotation is CustomAnnotation)
{
switch (CustomAnnotation.MarkerType)
{
case MyMarkerType.Note:
annotationView = new MKAnnotationView(annotation, resuseId);
annotationView.Image = UIImage.FromBundle("Message");
annotationView.CanShowCallout = false;
annotationView.Enabled = true;
break;
case MyMarkerType.Photo:
annotationView = new MKAnnotationView(annotation, resuseId);
annotationView.Image = UIImage.FromBundle("Photo");
annotationView.CanShowCallout = false;
break;
case MyMarkerType.Story:
annotationView = new MKAnnotationView(annotation, resuseId);
var Img = UIImage.FromBundle("Story");
annotationView.CanShowCallout = false;
break;
case MyMarkerType.Custom:
annotationView = new MKAnnotationView(annotation, resuseId);
//using (var data = NSData.FromArray(CustomAnnotation.WayPoint.Image))
//{
// var image = UIImage.LoadFromData(data);
// annotationView.Image = image;
//}
NSData data = NSData.FromArray(CustomAnnotation.WayPoint.Image);
UIImage image = UIImage.LoadFromData(data);
// UIImage finalImage = image.MaxResizeImage(21f, 20f);
annotationView.Image = image;
annotationView.CanShowCallout = false;
break;
default:
annotationView = new MKAnnotationView(annotation, resuseId);
//var imaget = FromUrl(CustomAnnotation.WayPoint.IconUrl);
//annotationView.Image = imaget;
break;
}
}
else{
annotationView.Annotation = annotation;
annotationView.CanShowCallout = false;
//(annotationView as MKPinAnnotationView).AnimatesDrop = false; // Set to true if you want to animate the pin dropping
//(annotationView as MKPinAnnotationView).PinTintColor = UIColor.Red;
annotationView.SetSelected(false, false);
}
}
return annotationView;
}
And my DidSelect Method
public override void DidDeselectAnnotationView(MKMapView mapView, MKAnnotationView view)
{
if ( view.Annotation.Coordinate.Latitude == mapView.UserLocation.Coordinate.Latitude){
return;
}
CLLocationCoordinate2D coordinates = view.Annotation.Coordinate;
mapView.DeselectAnnotation(view.Annotation, false);
// GetAnnotationClickInfo.Invoke(coordinates);
}
Use DidSelectAnnotationView method,
not DidDeselectAnnotationView.
public override void DidSelectAnnotationView(MKMapView mapView, MKAnnotationView view)
DidDeselectAnnotationView
DidSelectAnnotationView
After checking your code , I think there is a mistaken when initializing that annotationView ,you should put annotationView.Annotation = annotation; outside the condition if (annotationView == null).
Mofidy your code :
if (annotationView == null)
{
if (annotation is CustomAnnotation)
{
//custom view logic
}
else //not custom view
{
annotationView = new MKPinAnnotationView(annotation, annotationIdentifier);
}
}
else
{
annotationView.Annotation = annotation;
}
annotationView.CanShowCallout = false;
//(annotationView as MKPinAnnotationView).AnimatesDrop = false; // Set to true if you want to animate the pin dropping
//(annotationView as MKPinAnnotationView).PinTintColor = UIColor.Red;
annotationView.SetSelected(false, false);
I need to get a view with two radio buttons working, where only one can be clicked at a time. Using the answer posted here by user Alanc Liu: Radio button in xamarin.ios I've got my View Controller looking correct, but I can't figure out how to listen for the tap to set the other radio button to false.
I've tried playing around with adding a gesture recognizer to the ViewDidLoad method, but haven't gotten anything to work yet (I've mostly just used the storyboard previously to add methods to button clicks).
My View Controller:
public partial class VerifyViewController : UIViewController
{
public VerifyViewController (IntPtr handle) : base (handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
MyRadioButton tBtn = new MyRadioButton(new CGPoint(100, 300), "TEXT PHONE");
MyRadioButton eBtn = new MyRadioButton(new CGPoint(100, 375), "EMAIL");
this.Add(tBtn);
this.Add(eBtn);
}
}
And his Radio Button Classes:
public class MyRadioButton : UIView
{
private CircleView circleView;
private UILabel lbTitle;
public bool State {
get {
return circleView.State;
}
set {
circleView.State = value;
}
}
public MyRadioButton (CGPoint pt,string title)
{
this.Frame = new CGRect (pt, new CGSize (150, 30));
circleView = new CircleView (new CGRect(0, 0, 30, 30));
lbTitle = new UILabel (new CGRect (30, 0, 120, 30));
lbTitle.Text = title;
lbTitle.TextAlignment = UITextAlignment.Center;
this.AddSubview (circleView);
this.AddSubview (lbTitle);
this.BackgroundColor = UIColor.FromRGBA(1,0,0,0.3f);
UITapGestureRecognizer tapGR = new UITapGestureRecognizer (() => {
State = !State;
});
this.AddGestureRecognizer (tapGR);
}
}
class CircleView : UIView
{
private bool state = false;
public bool State {
get {
return state;
}
set {
state = value;
this.SetNeedsDisplay ();
}
}
public CircleView (CGRect frame)
{
this.BackgroundColor = UIColor.Clear;
this.Frame = frame;
}
public override void Draw (CoreGraphics.CGRect rect)
{
CGContext con = UIGraphics.GetCurrentContext ();
float padding = 5;
con.AddEllipseInRect (new CGRect (padding, padding, rect.Width - 2 * padding, rect.Height - 2 * padding));
con.StrokePath ();
if (state) {
float insidePadding = 8;
con.AddEllipseInRect (new CGRect (insidePadding, insidePadding, rect.Width - 2 * insidePadding, rect.Height - 2 * insidePadding));
con.FillPath ();
}
}
}
Expose a public event in MyRadioButton ,call it when we tap the radio button.
Code in MyRadioButton:
//define the event inside MyRadioButton
public delegate void TapHandler(MyRadioButton sender);
public event TapHandler Tap;
//call it in MyRadioButton(CGPoint pt, string title)
UITapGestureRecognizer tapGR = new UITapGestureRecognizer(() => {
State = !State;
Tap(this);
});
Handle the event inside your viewController
Code in ViewController
MyRadioButton tBtn = new MyRadioButton(new CGPoint(100, 300), "TEXT PHONE");
MyRadioButton eBtn = new MyRadioButton(new CGPoint(100, 375), "EMAIL");
this.Add(tBtn);
this.Add(eBtn);
tBtn.Tap += Btn_Tap;
eBtn.Tap += Btn_Tap;
// set the default selection
Btn_Tap(tBtn);
MyRadioButton PreviousButton;
private void Btn_Tap(MyRadioButton sender)
{
if(PreviousButton != null)
{
//set previous to false
PreviousButton.State = false;
}
//set current to true
sender.State = true;
//assign current to previous
PreviousButton = sender;
}
Result:
I'm trying to draw an Icon over everything on the screen (TOP MOST) similar to the chathead of new Facebook messenger
I have create a service to work in the background and based on a specific condition my icon should appear on the screen (exactly like when someone sends you a message on facebook the messenger service will hook the message and shows the chathead on the screen to notify you about the new message)
What I did:
I have created the service and gave it the permission to show system alert windows (since the head is actually a system alert window)
[assembly: UsesPermission(Name = Android.Manifest.Permission.SystemAlertWindow)]
I have inherited a class (StickyHeadView) from ImageView and implemented OnTouchListener listener using the following way :
class StickyHeadView : ImageView, Android.Views.View.IOnTouchListener
{
private StickyHeadService OwnerService;
public StickyHeadView(StickyHeadService ContextService, Context context)
: base(context)
{
OwnerService = ContextService;
SetOnTouchListener(this);
}
float TouchMoveX;
float TouchMoveY;
public bool OnTouch(View v, MotionEvent e)
{
var windowService = OwnerService.GetSystemService(Android.Content.Context.WindowService);
var windowManager = windowService.JavaCast<Android.Views.IWindowManager>();
switch (e.Action & e.ActionMasked)
{
case MotionEventActions.Move:
TouchMoveX = (int)e.GetX();
TouchMoveY = (int)e.GetY();
OwnerService.LOParams.X = (int)(TouchMoveX);
OwnerService.LOParams.Y = (int)(TouchMoveY);
windowManager.UpdateViewLayout(this, OwnerService.LOParams);
Log.Debug("Point : ", "X: " + Convert.ToString(OwnerService.LOParams.X) + " Y: " + Convert.ToString(OwnerService.LOParams.Y));
return true;
case MotionEventActions.Down:
return true;
case MotionEventActions.Up:
return true;
}
return false;
}
}
The service has wiindow manager to show the Icon on it...in Service "OnStart" event I initialize the Head :
private StickyHeadView MyHead;
public Android.Views.WindowManagerLayoutParams LOParams;
public override void OnStart(Android.Content.Intent intent, int startId)
{
base.OnStart(intent, startId);
var windowService = this.GetSystemService(Android.Content.Context.WindowService);
var windowManager = windowService.JavaCast<Android.Views.IWindowManager>();
MyHead = new StickyHeadView(this, this);
MyHead.SetImageResource(Resource.Drawable.Icon);
LOParams = new Android.Views.WindowManagerLayoutParams(Android.Views.WindowManagerLayoutParams.WrapContent,
Android.Views.WindowManagerLayoutParams.WrapContent,
Android.Views.WindowManagerTypes.Phone,
Android.Views.WindowManagerFlags.NotFocusable,
Android.Graphics.Format.Translucent);
LOParams.Gravity = GravityFlags.Top | GravityFlags.Left;
LOParams.X = 10;
LOParams.Y = 10;
windowManager.AddView(MyHead, LOParams);
}
as you can see I have declared a WindowManager and added the view (MyHead) to it with special parameters
My Problem :
When ever I try to move the View (My head) it doesn't move in a stable way and keeps having a quake!
I'm testing it using android 4.0.4 on real HTC Phone
I'm using monodroid
Please help...if the implementation of the touch is not right please suggest a better way...thank you.
In your code just use...
TYPE_SYSTEM_ALERT
or
TYPE_PHONE
instead of
TYPE_SYSTEM_OVERLAY
Hope this will help you.
a working example:
#Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
chatHead = new ImageView(this);
chatHead.setImageResource(R.drawable.ic_launcher);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, //TYPE_PHONE
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 100;
windowManager.addView(chatHead, params);
chatHead.setOnTouchListener(new View.OnTouchListener() {
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
#Override public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
initialX = params.x;
initialY = params.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
return true;
case MotionEvent.ACTION_MOVE:
params.x = initialX + (int) (event.getRawX() - initialTouchX);
params.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(chatHead, params);
return true;
}
return false;
}
});
}
The e.GetX()/eGetY() you are using is relative to view position so when you move the view with UpdateViewLayout the next values will be relative to the move. It works using GetRawX()/GetRawY(), but you have to keep track of the initial Down rawX and rawY also.
Here is my JAVA that works:
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
layoutParams.x = Math.round(event.getRawX() - downX);
layoutParams.y = Math.round(event.getRawY() - downY);
windowManager.updateViewLayout(floatingView, layoutParams);
return true;
case MotionEvent.ACTION_DOWN:
downX = event.getRawX() - layoutParams.x;
downY = event.getRawY() - layoutParams.y;
return true;
case MotionEvent.ACTION_UP:
return true;
}
return false;
}
One comment, there's a big downside in using windowManager.updateViewLayout(...) this method will call onLayout on the floating view for each move, and that might be a performance issue, anyway until now I haven't found another method to move the floating view.
Try this might be help ful
first add global variable on your activity:
WindowManager wm;
LinearLayout lay;
float downX,downY;
after put in code to oncreate on your activity
Button btnstart=(Button)findViewById(R.id.button1);
Button btnstop=(Button)findViewById(R.id.button2);
btnstart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(lay==null)
{
wm = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
| WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
params.x = (int) wm.getDefaultDisplay().getWidth();
params.y = 0;
// params.height = wm.getDefaultDisplay().getHeight()/2;
params.width = LayoutParams.WRAP_CONTENT;
params.format = PixelFormat.TRANSLUCENT;
params.gravity = Gravity.TOP | Gravity.LEFT;
params.setTitle("Info");
lay = null;
lay = new LinearLayout(getApplicationContext());
lay.setOrientation(LinearLayout.VERTICAL);
// lay.setAlpha(0.5f);
TextView txt_no = new TextView(getApplicationContext());
txt_no.setTextSize(10.0f);
txt_no.setText("Moving view by stack user!");
txt_no.setTextColor(Color.BLACK);
// txt_no.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
// LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(0, 0, 0, 0); // margins as you wish
txt_no.setGravity(Gravity.RIGHT);
txt_no.setBackgroundColor(Color.WHITE);
txt_no.setLayoutParams(layoutParams);
txt_no.setPadding(10, 10, 10, 10);
lay.addView(txt_no);
AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); // Make animation instant
alpha.setFillAfter(true); // Tell it to persist after the animation ends
// And then on your layout
wm.addView(lay, params);
txt_no.startAnimation(alpha);
downX=params.x;
downY=params.y;
Log.v("MSES>", "x="+ downX +",y="+ downY);
lay.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
params.x = Math.round(event.getRawX() - downX);
params.y = Math.round(event.getRawY() - downY);
wm.updateViewLayout(lay, params);
Log.v("MSES EVENT>", "x="+ event.getRawX() +",y="+ event.getRawY());
Log.v("MSES MOVE>", "x="+ params.x +",y="+ params.y);
return true;
case MotionEvent.ACTION_DOWN:
downX = event.getRawX() - params.x;
downY = event.getRawY() - params.y;
Log.v("MSES DOWN>", "x="+ params.x +",y="+ params.y);
return true;
case MotionEvent.ACTION_UP:
//params.x = Math.round(event.getRawX() - downX);
//params.y = Math.round(event.getRawY() - downY);
//wm.updateViewLayout(lay, params);
return true;
}
return false;
}
});
}
}
});
btnstop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (lay != null) {
lay.removeAllViews();
wm.removeViewImmediate(lay);
lay = null;
}
}
});
I don't know what is the problem, but SMS is not received with below code and when I see in the phone memory, app is invalid.
Can anyone correct this code?
I am having a lot of issues with this, it compiles well, but when it is on the real phone, the app says it is invalid,Nokia 2630 supports MIDP 2.0, so not a phone problem.
package Pushtest;
import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.GridLayout;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.util.Date;
import java.io.*;
/**
* #author test
*/
public class SendApprooval extends MIDlet implements Runnable, ActionListener, MessageListener {
Date todaydate;
private Dialog content, alert;
Thread thread;
String[] connections;
boolean done;
String senderAddress, mess;
MessageConnection smsconn = null, clientConn = null;
Message msg;
// public SendApprooval() {
/*
smsPort = getAppProperty("SMS-Port");
content = new Dialog("");
content.addComponent(new Label("Waiting for Authentication Request"));
content.setDialogType(Dialog.TYPE_INFO);
content.setTimeout(2000);
// exitCommand = new Command("Exit", Command.EXIT, 2);
// content.addCommand(exitCommand)
content.addCommand(exitCommand);
content.addCommandListener(this);
content.show();
} */
public void startApp() {
Display.init(this);
String smsConnection = "sms://:" + 5000;
if (smsconn == null) {
try {
smsconn = (MessageConnection) Connector.open(smsConnection);
smsconn.setMessageListener(this);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
connections = PushRegistry.listConnections(true);
if ((connections == null) || (connections.length == 0)) {
content.addComponent(new Label("Waiting for Authentication Request"));
}
done = false;
thread = new Thread(this);
thread.start();
// display.setCurrent(resumeScreen);
}
public void run() {
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
} catch (IOException e) {
content.addComponent(new Label(e.toString()));
Display.init(content);
}
}
public void pauseApp() {
done = true;
thread = null;
Display.init(this);
}
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
}
notifyDestroyed();
}
}
public void showMessage(String message, Display displayable) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setTitle("Error");
alert.addComponent(new Label(message));
alert.setDialogType(Dialog.TYPE_ERROR);
alert.setTimeout(5000);
alert.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
content.addComponent(new Label("Waiting for Authentication Request"));
content.setLayout(new GridLayout(5, 1));
content.setDialogType(Dialog.TYPE_INFO);
content.show();
done = false;
thread = new Thread(this);
thread.start();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int id = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdName1 = cmd.getCommandName();
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
int k, j = 0;
for (k = 0; k <= senderAddress.length() - 1; k++) {
if (senderAddress.charAt(k) == ':') {
j++;
if (j == 2) {
break;
}
}
}
senderAddress = senderAddress.substring(0, k + 1);
content.addComponent(new Label(senderAddress));
senderAddress = senderAddress + 5000;
if (msg instanceof TextMessage) {
mess = ((TextMessage) msg).getPayloadText();
}
else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int) data[i] & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
mess = buf.toString();
}
if (mess.equals("Give me Rights")) {
try {
clientConn = (MessageConnection) Connector.open(senderAddress);
}catch (Exception e) {
alert = new Dialog("Alert");
alert.setLayout(new GridLayout(5, 1));
alert.addComponent(new Label("Unable to connect to Station because of network problem"));
alert.setTimeout(2000);
alert.setDialogType(Dialog.TYPE_INFO);
Display.init(alert);
alert.show();
}
try {
TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
textmessage.setAddress(senderAddress);
textmessage.setPayloadText("Approoved");
clientConn.send(textmessage);
} catch (Exception e) {
Dialog alert = new Dialog("");
alert.setLayout(new GridLayout(5, 1));
alert.setDialogType(Dialog.TYPE_INFO);
alert.setTimeout(2000);
alert.addComponent(new Label(e.toString()));
Display.init(alert);
alert.show();
}
}
} else {
}
if (("Exit").equals(cmdName1)) {
destroyApp(true);
notifyDestroyed();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This may be cause because your sending SMS might not send on the port you defined in your code,
Please look at to this working example.
i found it guys, Thanks for your support, i'm sure i would come back with more queries, i have written a sample receiving sms code with port 5000, It would Help someone in someway,
Before you start,
Right click your application in netbeans and select properties. Now select the application descriptor. select the attribute tab and select the Add button. Give the following in the corresponding fields.
Name : SMS-Port
Value : portno
Now u have registered the port no successfully.
Now again select the push registry tab.
give the following in the corresponding fields.
Class Name : Package name.class name
Sender ip : *
Connection String: sms://:portno
Now u have registered the push registry successfully.
CODE HERE:
public class SMSReceiver extends MIDlet implements ActionListener, MessageListener {
private Form formReceiver;
private TextField tfPort;
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() {
Display.init(this);
try {
Resources r = Resources.open("/m21.res");
UIManager.getInstance().setThemeProps(
r.getTheme(r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
e.printStackTrace();
}
formReceiver = new Form();
formReceiver.setTitle(" ");
formReceiver.setLayout(new GridLayout(4, 2));
formReceiver.setTransitionInAnimator(null);
TextField.setReplaceMenuDefault(false);
Label lblPort = new Label("Port");
tfPort = new TextField();
tfPort.setMaxSize(8);
tfPort.setUseSoftkeys(false);
tfPort.setHeight(10);
tfPort.setConstraint(TextField.DECIMAL);
formReceiver.addComponent(lblPort);
formReceiver.addComponent(tfPort);
formReceiver.addCommand(new Command("Listen"), 0);
formReceiver.addCommand(new Command("Exit"), 0);
formReceiver.addCommandListener(this);
formReceiver.show();
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.addComponent(new Label("Message received : "+tMessage.getPayloadText()+"\n"));
} else {
formReceiver.addComponent(new Label("Unknown Message received\n"));
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent ae) {
System.out.println("Event fired" + ae.getCommand().getCommandName());
int idi = ae.getCommand().getId();
Command cmd = ae.getCommand();
String cmdNam = cmd.getCommandName();
if ("Listen".equals(cmdNam)) {
ListenSMS sms = new ListenSMS(tfPort.getSelectCommandText(), this);
sms.start();
}
if ("Exit".equals(cmdNam)) {
notifyDestroyed();
}
}
}
class ListenSMS extends Thread {
private MessageConnection msgConnection;
private MessageListener Listener;
private String port;
public ListenSMS(String port, MessageListener listener) {
this.port = port;
this.Listener = listener;
}
public void run() {
try {
msgConnection = (MessageConnection)Connector.open("sms://:" + 5000);
msgConnection.setMessageListener(Listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want to create a LWUIT Image from the captured video. The problem is that the MediaException is raised when calling getSnapshot() :
private void showCamera() // called when clicking the "open camera" command
{
try
{
Player mPlayer;
VideoControl mVideoControl;
mPlayer = Manager.createPlayer("capture://video");
mPlayer.realize();
mVideoControl = (VideoControl) mPlayer.getControl("VideoControl");
Canvas canvas = new CameraCanvas(this, mVideoControl, mPlayer, getFirstAvailableRoot(), "ADC"+adcId); // adcId is "1"
isFromPositionnement = true; // static variable
javax.microedition.lcdui.Display.getDisplay(controler).setCurrent(canvas);
mPlayer.start();
} catch (IOException ex) {
handleException();
} catch (MediaException ex) {
handleException();
}
}
private String getFirstAvailableRoot()
{
short iter;
String root = "Phone:/";
iter = 0;
Enumeration drives = FileSystemRegistry.listRoots();
while(drives.hasMoreElements() && iter < 1) {
root = String.valueOf(drives.nextElement());
iter++;
}
return root;
}
Code in "CameraCanvas" :
public class CameraCanvas extends Canvas implements CommandListener
{
...
public CameraCanvas(Ecran form, VideoControl videoControl, Player pPlayer, String pRoot, String dossierPhoto)
{
...
mCaptureCommand = new Command("Capturer", Command.SCREEN, 1);
addCommand(mCaptureCommand);
setCommandListener(this);
...
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try
{
videoControl.setDisplayLocation(2, 2);
videoControl.setDisplaySize(width - 4, height - 4);
}
catch (MediaException me)
{
try
{
videoControl.setDisplayFullScreen(true);
}
catch (MediaException me2)
{}
}
videoControl.setVisible(true);
}
private void capture() // called when clicking the mCaptureCommand command
{
try
{
isPhotoCaptured = true;
rawImg = vidCtrl.getSnapshot(null); // this throws the exception
vidCtrl.setVisible(false);
vidCtrl = null;
mPlayer.close();
mPlayer = null;
repaint();
}
catch (MediaException me)
{
isPhotoCaptured = false;
rawImg = null;
vidCtrl.setVisible(false);
vidCtrl = null;
mPlayer.close();
mPlayer = null;
handleException("capture ");
}
}
}
So what may be the cause of the issue ?
MMAPI has the ability to create an image and you can easily turn it to a LWUIT image (which has a create image that accepts an object). However, for some reason the "geniuses" who came up with this API made image capture a restricted API to protect your privacy. So effectively you can't invoke this API without an operator/manufacturer signature.