i've used below code for notify the sms .
Its working on two blackberry simulator.
I've install the app on my device and send sms from android device.
The sms listener not working on device.
Incoming message received on device. but my app not notify the listener .
What is the problem how to resolve it.
What port number need to give for device?
class BackgroundApplication extends Application implements MessageListener
{
int i=0;
static String suffix;
MessageConnection _mc ;
public BackgroundApplication()
{
try {
_mc = (MessageConnection)Connector.open("sms://:0");
_mc.setMessageListener(this);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void notifyIncomingMessage(MessageConnection conn) {
try {
Message m = _mc.receive();
String address = m.getAddress();
String msg = null;
if ( m instanceof TextMessage )
{
TextMessage tm = (TextMessage)m;
msg = tm.getPayloadText();
}
else if (m instanceof BinaryMessage) {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage) m).getPayloadData();
// convert Binary Data to Text
msg = new String(data, "UTF-8");
}
else
System.out.println("Invalid Message Format");
System.out.println("Received SMS text from " + address + " : " + msg);
showDialog("Msg: "+msg);
} catch (Exception e) {
// TODO: handle exception
}
}
private void showDialog(String string) {
synchronized (UiApplication.getEventLock())
{
Status.show(""+string,Bitmap.getPredefinedBitmap(Bitmap.INFORMATION), 5000,
Status.GLOBAL_STATUS, true, false, 1);
}
}
}
Check this
http://supportforums.blackberry.com/t5/Java-Development/Different-ways-to-listen-for-SMS-messages/ta-p/445062
DatagramConnection _dc =
(DatagramConnection)Connector.open("sms://");
for(;;)
{
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println( "Received SMS text from " + address + " : " + msg);
}
Related
It's a table , My company assemble it,with no wifi no sim,but cable;
Now , how could i get Ipaddress and other configs?
I can't use WifiManager/WifiInfo ...
Because of connected by cable; we can't use WifiManger; i found Linux Shell could help;
but not what i know much.
private String do_exec(String cmd) {
String s = "\n";
try {
String[] cmdline = {"sh", "-c", cmd};
Process p = Runtime.getRuntime().exec(cmdline);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
s += line + "\n";
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("do_exec", s);
return s;
}
How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}
The following code reads an incoming sms then prints the body of the message. How do I get the app to print out the message without any spaces inbetween?
For example: The incoming sms reads "Here I am", so "Here I am" is printed out, but I want the app to print out "HereIam".
How can I do this? Any help would be most appreciated.
Here is my code:
public void run() {
try {
DatagramConnection _dc = (DatagramConnection)Connector.open("sms://");
for(;;) {
Datagram d = _dc.newDatagram(_dc.getMaximumLength());
_dc.receive(d);
byte[] bytes = d.getData();
String address = d.getAddress();
String msg = new String(bytes);
System.out.println(address);
System.out.println(msg);
}
}catch (Exception me) {
}
}
Thanks
try this
add this line to code
System.out.println(replaceAll(msg," ",""));
Add this method as well
public static String replaceAll(String source, String pattern,
String replacement) {
if (source == null)
return "";
StringBuffer sb = new StringBuffer();
int idx = -1;
int patIdx = 0;
while ((idx = source.indexOf(pattern, patIdx)) != -1) {
sb.append(source.substring(patIdx, idx));
sb.append(replacement);
patIdx = idx + pattern.length();
}
sb.append(source.substring(patIdx));
return sb.toString();
}
It replaces all the spaces with empty string, which is what you want.
Use the String.replace() method:
msg = msg.replace("\s+", "");
i am new to black berry.i am doing one task,i have one webservice to show some url.i need to retrive it and connect to that url.i tried with two threads one is to retrive url and other is to connect to url which is in webservice but it shows nullpointer exception.please help me.
Thank You.
since you have not posted any code, it's very difficult to diagnose the problem. But look at the following code which tries to open an absolute url. This can be helpful.
Use this method for both of your connection (Web Service and URL returned from Web Service). Be sure to call this method in a separate thread otherwise it will freeze the UI.
public static ResponseBean sendRequestAndReceiveResponse(
String method, String absoluteURL, String bodyData, boolean readResponseBody)
throws IOException
{
ResponseBean responseBean = new ResponseBean();
HttpConnection httpConnection = null;
try
{
String formattedURL = absoluteURL + "deviceside=true;interface=wifi"; // If you are using WiFi
//String formattedURL = absoluteURL + "deviceside=false"; // If you are using BES
//String formattedURL = absoluteURL + "deviceside=true"; // If you are using TCP
if(DeviceInfo.isSimulator()) // if simulator is running
formattedURL = absoluteURL;
httpConnection = (HttpConnection) Connector.open(formattedURL);
httpConnection.setRequestMethod(method);
if (bodyData != null && bodyData.length() > 0)
{
OutputStream os = httpConnection.openOutputStream();
os.write(bodyData.getBytes("UTF-8"));
}
int responseCode = httpConnection.getResponseCode();
responseBean.setResponseCode(responseCode);
if (readResponseBody)
{
responseBean.setBodyData(readBodyData(httpConnection));
}
}
catch (IOException ex)
{
System.out.println("!!!!!!!!!!!!!!! IOException in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw ex;
}
catch(Exception ex)
{
System.out.println("!!!!!!!!!!!!!!! Exception in NetworkUtil::sendRequestAndReceiveResponse(): " + ex);
throw new IOException(ex.toString());
}
finally
{
if (httpConnection != null)
httpConnection.close();
}
return responseBean;
}
public static StringBuffer readBodyData(HttpConnection httpConnection) throws UnsupportedEncodingException, IOException
{
if(httpConnection == null)
return null;
StringBuffer bodyData = new StringBuffer(256);
InputStream inputStream = httpConnection.openDataInputStream();
byte[] data = new byte[256];
int len = 0;
int size = 0;
while ( -1 != (len = inputStream.read(data)) )
{
bodyData.append(new String(data, 0, len,"UTF-8"));
size += len;
}
if (inputStream != null)
{
inputStream.close();
}
return bodyData;
}
I use Smack API to write my Google talk Client . Now i need to handle add request for this .
I set SubscriptionMode to manual & now I have to registering a listener for presence packets but i don't know how !!
can any body help ?
I have not tried it yet, but I guess the below should work. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of Presence.Type.subscribe.
First set the roster:
Roster roster = connection.getRoster();
roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
Then add a packet listner to the above connection, eg :
connection.addPacketListener(new SubscriptionListener(), new PacketFilter(){
public boolean accept(Packet packet) {
if(packet instanceof Presence)
if(((Presence)packet).getType().equals(Presence.Type.subscribe))
return true;
return false;
}});
The above code just returns true for all requests, But you can customize it i.e set it to true or false based on user GUI input.
public static void admitFriendsRequest() {
connection.getRoster().setSubscriptionMode(
Roster.SubscriptionMode.manual);
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet paramPacket) {
System.out.println("\n\n");
if (paramPacket instanceof Presence) {
Presence presence = (Presence) paramPacket;
String email = presence.getFrom();
System.out.println("chat invite status changed by user: : "
+ email + " calling listner");
System.out.println("presence: " + presence.getFrom()
+ "; type: " + presence.getType() + "; to: "
+ presence.getTo() + "; " + presence.toXML());
Roster roster = connection.getRoster();
for (RosterEntry rosterEntry : roster.getEntries()) {
System.out.println("jid: " + rosterEntry.getUser()
+ "; type: " + rosterEntry.getType()
+ "; status: " + rosterEntry.getStatus());
}
System.out.println("\n\n\n");
if (presence.getType().equals(Presence.Type.subscribe)) {
Presence newp = new Presence(Presence.Type.subscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
Presence subscription = new Presence(
Presence.Type.subscribe);
subscription.setTo(presence.getFrom());
connection.sendPacket(subscription);
} else if (presence.getType().equals(
Presence.Type.unsubscribe)) {
Presence newp = new Presence(Presence.Type.unsubscribed);
newp.setMode(Presence.Mode.available);
newp.setPriority(24);
newp.setTo(presence.getFrom());
connection.sendPacket(newp);
}
}
}
}, new PacketFilter() {
public boolean accept(Packet packet) {
if (packet instanceof Presence) {
Presence presence = (Presence) packet;
if (presence.getType().equals(Presence.Type.subscribed)
|| presence.getType().equals(
Presence.Type.subscribe)
|| presence.getType().equals(
Presence.Type.unsubscribed)
|| presence.getType().equals(
Presence.Type.unsubscribe)) {
return true;
}
}
return false;
}
});
connection.getRoster().addRosterListener(new RosterListener() {
public void presenceChanged(Presence presence) {
System.out.println(presence.getFrom() + "presenceChanged");
}
public void entriesUpdated(Collection<String> presence) {
System.out.println("entriesUpdated");
}
public void entriesDeleted(Collection<String> presence) {
System.out.println("entriesDeleted");
}
public void entriesAdded(Collection<String> presence) {
System.out.println("entriesAdded");
}
});
}