I tried to read a json string loading from an URL, but I could not find complete code sample. Can any one provide or point me to a complete client code. I'm newer to BB development.
this is what I have done but still can't get it work please help me.
Thanks!
To read and parse data from an URL you need to implement two routines. First one of them will handle reading data from the specified URL over HTTP connection, and the second one will parse the data.
Check the following application HttpUrlReaderDemoApp, which will first read the data from specified URL and then parse the retrieved data.
URL used to retrieve data: http://codeincloud.tk/json_android_example.php
Sample data format: {"name":"Froyo", "version":"Android 2.2"}
Classes:
HttpUrlReaderDemoApp - UiApplication instance
HttpResponseListener - Interface used to notify other classes about HTTP request status
HttpUrlReader - Reads the data from given url
AppMainScreen - MainScreen instance
DataParser - Parse data
DataModel - Data definition
Screenshots:
Request for data
When data retrieved successfully
Parsed data
Implementation:
HttpUrlReaderDemoApp
public class HttpUrlReaderDemoApp extends UiApplication {
public static void main(String[] args) {
HttpUrlReaderDemoApp theApp = new HttpUrlReaderDemoApp();
theApp.enterEventDispatcher();
}
public HttpUrlReaderDemoApp() {
pushScreen(new AppMainScreen("HTTP Url Reader Demo Application"));
}
}
HttpResponseListener
public interface HttpResponseListener {
public void onHttpResponseFail(String message, String url);
public void onHttpResponseSuccess(byte bytes[], String url);
}
HttpUrlReader
public class HttpUrlReader implements Runnable {
private String url;
private HttpResponseListener listener;
public HttpUrlReader(String url, HttpResponseListener listener) {
this.url = url;
this.listener = listener;
}
private String getConncetionDependentUrlSuffix() {
// Not implemented
return "";
}
private void notifySuccess(byte bytes[], String url) {
if (listener != null) {
listener.onHttpResponseSuccess(bytes, url);
}
}
private void notifyFailure(String message, String url) {
if (listener != null) {
listener.onHttpResponseFail(message, url);
}
}
private boolean isValidUrl(String url) {
return (url != null && url.length() > 0);
}
public void run() {
if (!isValidUrl(url) || listener == null) {
String message = "Invalid parameters.";
message += !isValidUrl(url) ? " Invalid url." : "";
message += (listener == null) ? " Invalid HttpResponseListerner instance."
: "";
notifyFailure(message, url);
return;
}
// update URL depending on connection type
url += DeviceInfo.isSimulator() ? ";deviceside=true"
: getConncetionDependentUrlSuffix();
// Open the connection and retrieve the data
try {
HttpConnection httpConn = (HttpConnection) Connector.open(url);
int status = httpConn.getResponseCode();
if (status == HttpConnection.HTTP_OK) {
InputStream input = httpConn.openInputStream();
byte[] bytes = IOUtilities.streamToBytes(input);
input.close();
notifySuccess(bytes, url);
} else {
notifyFailure("Failed to retrieve data, HTTP response code: "
+ status, url);
return;
}
httpConn.close();
} catch (Exception e) {
notifyFailure("Failed to retrieve data, Exception: ", e.toString());
return;
}
}
}
AppMainScreen
public class AppMainScreen extends MainScreen implements HttpResponseListener {
private final String URL = "http://codeincloud.tk/json_android_example.php";
public AppMainScreen(String title) {
setTitle(title);
}
private MenuItem miReadData = new MenuItem("Read data", 0, 0) {
public void run() {
requestData();
}
};
protected void makeMenu(Menu menu, int instance) {
menu.add(miReadData);
super.makeMenu(menu, instance);
}
public void close() {
super.close();
}
public void showDialog(final String message) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.alert(message);
}
});
}
private void requestData() {
Thread urlReader = new Thread(new HttpUrlReader(URL, this));
urlReader.start();
showDialog("Request for data from\n \"" + URL + "\"\n started.");
}
public void onHttpResponseFail(String message, String url) {
showDialog("Failure Mesage:\n" + message + "\n\nUrl:\n" + url);
}
public void onHttpResponseSuccess(byte bytes[], String url) {
showDialog("Data retrived from:\n" + url + "\n\nData:\n"
+ new String(bytes));
// now parse response
DataModel dataModel = DataParser.getData(bytes);
if (dataModel == null) {
showDialog("Failed to parse data: " + new String(bytes));
} else {
showDialog("Parsed Data:\nName: " + dataModel.getName()
+ "\nVersion: " + dataModel.getVersion());
}
}
}
DataParser
public class DataParser {
private static final String NAME = "name";
private static final String VERSION = "version";
public static DataModel getData(byte data[]) {
String rawData = new String(data);
DataModel dataModel = new DataModel();
try {
JSONObject jsonObj = new JSONObject(rawData);
if (jsonObj.has(NAME)) {
dataModel.setName(jsonObj.getString(NAME));
}
if (jsonObj.has(VERSION)) {
dataModel.setVersion(jsonObj.getString(VERSION));
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dataModel;
}
}
DataModel
public class DataModel {
private String name;
private String version;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersion() {
return version;
}
public void setVersion(String model) {
this.version = model;
}
}
Related
So, the main goal here is to connect to the Bitfinex WebSocket by building a WebSocket Client. I would like to start receiving a stream of information(price,trades,etc). The problem is that at this stage I cannot even subscribe to a specific currency pair. In other words, I am sending a request for information to the WebSocket server but I am not receiving any responses and I cannot figure why this is. My code is below.
This is the main method
public class Main {
public static void main(String[] args) throws ExecutionException, InterruptedException {
String URL = "wss://api-pub.bitfinex.com/ws/2/";
WebSocketClient client = new StandardWebSocketClient();
WebSocketStompClient stompClient = new WebSocketStompClient(client);
stompClient.setMessageConverter(new MappingJackson2MessageConverter());
StompSessionHandler sessionHandler = new MyStompSessionHandler();
stompClient.connect(URL,sessionHandler);
new Scanner(System.in).nextLine(); // Don't close immediately.
}
}
This is the MyStompSessionHandler
public class MyStompSessionHandler extends StompSessionHandlerAdapter{
#Override
public void afterConnected(
StompSession session, StompHeaders connectedHeaders) {
System.out.println("New session established : " + session.getSessionId());
System.out.println("wss://api-pub.bitfinex.com/ws/2");
session.send("wss://api-pub.bitfinex.com/ws/2/", getSampleMessage());
System.out.println("Message sent to websocket server");
}
#Override
public void handleException(StompSession session, StompCommand command, StompHeaders headers, byte[] payload, Throwable exception) {
System.out.println("Got an exception:" + exception);
}
#Override
public Type getPayloadType(StompHeaders headers) {
return OutboundMessage.class;
}
private Object getSampleMessage() {
InboundMessage inboundMessage = new InboundMessage();
inboundMessage.setEvent("subscribe");
inboundMessage.setChannel("ticker");
inboundMessage.setSymbol("tBTCUSD");
return inboundMessage;
}
#Override
public void handleFrame(StompHeaders headers, Object payload) {
InboundMessage msg = (InboundMessage) payload;
System.out.println(msg.toString());
}
}
This is the InboundMessage class
public class InboundMessage {
private String event;
private String channel;
private String symbol;
public InboundMessage() {
}
public InboundMessage(String event, String channel, String symbol) {
this.event = event;
this.channel = channel;
this.symbol = symbol;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getChannel() {
return channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getSymbol() {
return symbol;
}
public void setSymbol(String symbol) {
this.symbol = symbol;
}
#Override
public String toString() {
return "InboundMessage{" +
"event='" + event + '\'' +
", channel='" + channel + '\'' +
", symbol='" + symbol + '\'' +
'}';
}
I looked at the Bitfinex website and I don't see any evidence that STOMP is supported. They just have a REST and a WebSocket API. Therefore, using STOMP from your client isn't going to work.
I have web project I which I am using Struts2 framework. In this people uploads the pdf file, for that I have used struts File upload API.
But the strange this, every second file upload is corrupted on server, when I try to open file, it gives me error:
There was an error opening this document. The file is damaged and could not be repaired.enter image description here
struts.xml
<action name="uploadFiles" class="org.webpannel.action.FileHandlingAction"
method="saveFiles">
<interceptor-ref name="customeUploadStack" />
<result name="success">/admin/WindowCloser.jsp</result>
<result name="input">/service/AttachmentPopup.jsp</result>
</action>
FileHandlingAction:
public class FileHandlingAction extends BaseAction implements Preparable{
/**
*
*/
private static final long serialVersionUID = -470622101009022548L;
private File[] file;
private String[] contentType;
private String[] filename;
private List<String> attachmentsList= new ArrayList<String>();
private String directoryPath;
// the name is written like this, so that no one can easily manipulate.
private String istbamefi;
private static Logger logger = Logger.getLogger(FileHandlingAction.class);
public void prepare() throws Exception {
directoryPath = getText("attachments.dirctory")+File.separator+getS3IdFromSession();
System.out.println("directoryPath::"+directoryPath);
}
#Override
public String execute() throws Exception {
try{
File[] filesStored = Utility.listFilesInDirectory(directoryPath);
if(filesStored==null){
return SUCCESS;
}
for(File fil : filesStored){
attachmentsList.add(fil.getName());
}
}catch(Exception e1){
logger.error(e1.getMessage(),e1);
}
return SUCCESS;
}
public String saveFiles() {
logger.info("Going to save the Uploaded files");
if(logger.isDebugEnabled()){
logger.debug("Directory path :"+directoryPath);
if(file==null){
addActionMessage("Please Select a file to upload");
return INPUT;
}
for (File f : file) {
logger.debug("File :"+f);
}
}
for (int i = 0; i < file.length; i++) {
try {
uploadDocument(file[i], filename[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("Exiting successfully after saving the files:");
setMessage("succesfully saved the files");
return SUCCESS;
}
public String removeFile(){
logger.debug("Going to delete file:"+istbamefi);
File file = new File(directoryPath+File.separator+istbamefi);
if(file.exists()){
logger.debug("File found");
file.delete();
logger.debug("File Deleted");
}else{
logger.debug("File Doest not exists");
setMessage("File Does not exists");
return SUCCESS;
}
setMessage("File Successfully Removed");
return SUCCESS;
}
private void uploadDocument(File file, String fileName) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
File dir = new File(directoryPath);
if (!dir.exists()) {
dir.mkdir();
}
logger.info("Uploaded File Name :" +fileName);
logger.info("Uploaded File Length :" +file.length());
String targetPath = dir.getPath() + File.separator + fileName;
System.out.println("targetPath::"+targetPath);
File picDestination = new File(targetPath);
logger.info("Destination Path :"+picDestination);
try {
in = new FileInputStream(file);
out = new FileOutputStream(picDestination);
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
public List<String> getAttachmentsList() {
return attachmentsList;
}
public void setAttachmentsList(List<String> attachmentsList) {
this.attachmentsList = attachmentsList;
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getContentType() {
return contentType;
}
public void setContentType(String[] contentType) {
this.contentType = contentType;
}
public String[] getFilename() {
return filename;
}
public void setUpload(File[] file) {
this.file = file;
}
public void setUploadContentType(String[] contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String[] filename) {
this.filename = filename;
}
public void setFilename(String[] filename) {
this.filename = filename;
}
public String getDirectoryPath() {
return directoryPath;
}
public void setDirectoryPath(String directoryPath) {
this.directoryPath = directoryPath;
}
public String getIstbamefi() {
return istbamefi;
}
public void setIstbamefi(String istbamefi) {
this.istbamefi = istbamefi;
}
}
I am building a download manager
Here I have shown a test code which tries to update fileNameColumn of a row of tableView but it is not being updated after I connect to url
To be specific, here fileName remains hello1 and it doesnt get updated to hello2. Yhy's that so?
Main.java :
public static TableView<DownloadEntry> downloadsTable;
public TableColumn<DownloadEntry, String> fileNameColumn;
public void initialize(URL location, ResourceBundle resources) {
downloadsTable = new TableView<DownloadEntry>();
fileNameColumn = new TableColumn<>("File Name");
fileNameColumn.setCellValueFactory(new PropertyValueFactory<>("fileName"));
executor = Executors.newFixedThreadPool(4);
}
public void addDownloadButtonClicked() {
try{
String urlText = urlTextBox.getText();
DownloadEntry task = new DownloadEntry(new URL(urlText));
downloadsTable.getItems().add(task);
executor.execute(task);
}
catch(Exception e) {
System.out.println("addDownloadButtonClicked: " + e);
}
}
DownloadEntry.java:
public class DownloadEntry extends Task<Void> {
public SimpleStringProperty fileName;
public URL url;
//Constructor
public DownloadEntry(URL ur) throws Exception{
fileName = new SimpleStringProperty("hello");
url = ur;
}
#Override
protected Void call() {
try {
HttpURLConnection connect=(HttpURLConnection)url.openConnection();
fileName.set("hello1");
connect.connect();
fileName.set("hello2");
}
catch(Exception E) {
this.updateMessage("Error");
E.printStackTrace();
}
return null;
}
public String getFileName() {
return fileName.get();
}
public void setFileName(String fileName) {
this.fileName = new SimpleStringProperty(fileName);
}
}
Please tell if you need more details..
Your model is incorrectly implemented. The setFileName method should be
public void setFileName(String fileName) {
this.fileName.set(fileName);
}
(The problem with your implementation is that the table is still observing the old property, not the new one you create.)
You will also need to provide a "property accessor" method:
public StringProperty fileNameProperty() {
return fileName ;
}
which will allow the table to properly bind to the property (so that it "knows" when its value changes).
I have an app that uses a browserfield to connect to a web-page.
All is working ok and the simulator shows the right page.
If I set the simulator Network Properties to "Out of Coverage" and click on a link in my web-page then I get an exception - in the BrowserFieldConnectionManagerImpl
How can catch this exception so I can take appropriate action?
The app is using BlackBerry SDK
The code is here:
public final class example_Screen extends MainScreen {
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
protected MyBrowserFieldErrorHandler(BrowserField browserField){
super(browserField);
}
public void displayContentError(String url, String errorMessage) {
System.out.println("JERRY: displayContentError" + url);
System.out.println("JERRY: displayContentError" + errorMessage);
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void navigationRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
}
public InputConnection resourceRequestError(BrowserFieldRequest request, Throwable t) {
displayContentError(request.getURL(), t.getMessage());
InputConnection connection = null;
return connection;
}
}
/**
* Creates a new example_Screen object
*/
public example_Screen() {
GIFEncodedImage ourAnimation = (GIFEncodedImage) GIFEncodedImage.getEncodedImageResource("2.gif");
AnimatedGIFField _ourAnimation = new AnimatedGIFField(ourAnimation, Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourAnimation);
LabelField _ourLabelField = new LabelField("Updating ...", Field.FIELD_HCENTER + Field.FIELD_VCENTER);
this.add(_ourLabelField);
int anim_ht = _ourAnimation.getPreferredHeight();
int label_ht = _ourLabelField.getPreferredHeight();
EncodedImage ei = EncodedImage.getEncodedImageResource("img/menu.png");
int currentWidthFixed32 = Fixed32.toFP(ei.getWidth());
int currentHeightFixed32 = Fixed32.toFP(ei.getHeight());
int displayWidthFixed32 = Fixed32.toFP(Display.getWidth());
int displayHeightFixed32 = Fixed32.toFP((Display.getHeight() - anim_ht - label_ht));
int scaleXFixed32 = Fixed32.div(currentWidthFixed32, displayWidthFixed32);
int scaleYFixed32 = Fixed32.div(currentHeightFixed32, displayHeightFixed32);
ei = ei.scaleImage32(scaleXFixed32, scaleYFixed32);
BitmapField bmp = new BitmapField(ei.getBitmap(), Field.FIELD_HCENTER + Field.FIELD_VCENTER);
add(bmp);
BrowserFieldConfig myBrowserFieldConfig = new BrowserFieldConfig();
myBrowserFieldConfig.setProperty(BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER);
BrowserField browserField = new BrowserField(myBrowserFieldConfig);
add(browserField);
browserField.requestContent("http://www.bbc.co.uk");
BrowserFieldListener listener = new BrowserFieldListener() {
public void documentAborted(BrowserField browserField, Document document) {
System.out.println("JERRY: documentAborted");
}
public void documentCreated(BrowserField browserField, ScriptEngine scriptEngine, Document document) {
System.out.println("JERRY: documentCreated");
}
public void documentError(BrowserField browserField, Document document) {
System.out.println("JERRY: documentError");
}
public void documentLoaded(BrowserField browserField, Document document) {
System.out.println("JERRY: documentLoaded");
Node node = document.getFirstChild();
String nodeText = node.getTextContent();
int index = -1;
if (nodeText != null) {
String errorText = "Error requesting content for:";
index = nodeText.indexOf(errorText);
}
Screen screen = browserField.getScreen();
try {
synchronized (Application.getEventLock()) {
if (index == -1) {
System.out.println("JERRY: documentLoaded: no error");
int count = screen.getFieldCount();
if (count > 1) {
screen.deleteRange(0, (count-1));
System.out.println("JERRY: documentLoaded: " + (count-1) + " fields deleted");
} else {
System.out.println("JERRY: documentLoaded: only 1 field so none deleted");
}
} else {
System.out.println("JERRY: documentLoaded: error");
}
}
} catch (final Exception ex) {
System.out.println("example_Screen: documentLoaded: exception caught: " + ex.toString());
}
}
public void documentUnloading(BrowserField browserField, Document document) {
System.out.println("JERRY: documentUnloading");
}
public void downloadProgress(BrowserField browserField, ContentReadEvent event) {
System.out.println("JERRY: downloadProgress");
}
};
browserField.addListener(listener);
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler(browserField);
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER, eHandler);
}
}
BrowserField contains a method, addListener() which takes a reference to BrowserFieldListener implementation.
Extend BrowserFieldListener and process errors in methods documentError() and documentAborted() of this implementation.
Then add a reference of your class instance that extends BrowserFieldListener to your browser field via browserField.addListener(browserFieldListener);.
EDIT:
If this does not work, then use BrowserFieldErrorHandler class from RIM API. Build your own error handler and pass its instance to the browserfield configuration.
Below, there's sample code:
// Create the ErrorHandler class
public class MyBrowserFieldErrorHandler extends BrowserFieldErrorHandler {
public void displayContentError(String url, String errorMessage) {
String error = "Error: (url=" + url + "): " + t.getMessage();
Dialog.ask(Dialog.D_OK, error);
logMessage(“BrowserFieldError: “ + error );
}
public void displayContentError(String url, InputConnection connection, Throwable t) {
displayContentError(url, t.getMessage());
}
public void requestContentError(BrowserFieldRequest request, Throwable t){
displayContentError(request.getURL(), t.getMessage());
}
}
// Attach the Error Handler to the BrowserField
BrowserFieldErrorHandler eHandler = new MyBrowserFieldErrorHandler();
browserField.getConfig().setProperty(BrowserFieldConfig.ERROR_HANDLER,eHandler);
I get this sample code from DevCon2010 presentation of BrowserField capabilities. You can get it here: http://dev.tuyennguyen.ca/wp-content/uploads/2011/02/DEV49.pdf
Here is my full push notification listener.
public class MyApp extends UiApplication {
public static void main(String[] args) {
PushAgent pa = new PushAgent();
pa.enterEventDispatcher();
}
}
Is this class extended correctly?
public class PushAgent extends Application {
private static final String PUSH_PORT = "32023";
private static final String BPAS_URL = "http://pushapi.eval.blackberry.com";
private static final String APP_ID = "2727-c55087eR3001rr475448i013212a56shss2";
private static final String CONNECTION_SUFFIX = ";deviceside=false;ConnectionType=mds-public";
public static final long ID = 0x749cb23a75c60e2dL;
private MessageReadingThread messageReadingThread;
public PushAgent() {
if (!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_BIS_B)) {
return;
}
if (DeviceInfo.isSimulator()) {
return;
}
messageReadingThread = new MessageReadingThread();
messageReadingThread.start();
registerBpas();
}
private static class MessageReadingThread extends Thread {
private boolean running;
private ServerSocketConnection socket;
private HttpServerConnection conn;
private InputStream inputStream;
private PushInputStream pushInputStream;
public MessageReadingThread() {
this.running = true;
}
public void run() {
String url = "http://:" + PUSH_PORT + CONNECTION_SUFFIX;
try {
socket = (ServerSocketConnection) Connector.open(url);
} catch (IOException ex) {
}
while (running) {
try {
Object o = socket.acceptAndOpen();
conn = (HttpServerConnection) o;
inputStream = conn.openInputStream();
pushInputStream = new MDSPushInputStream(conn, inputStream);
PushMessageReader.process(pushInputStream, conn);
} catch (Exception e) {
if (running) {
running = false;
}
} finally {
close(conn, pushInputStream, null);
}
}
}
}
public static void close(Connection conn, InputStream is, OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (conn != null) {
try {
conn.close();
} catch (IOException e) {
}
}
}
private String formRegisterRequest(String bpasUrl, String appId,
String token) {
StringBuffer sb = new StringBuffer(bpasUrl);
sb.append("/mss/PD_subReg?");
sb.append("serviceid=").append(appId);
sb.append("&osversion=").append(DeviceInfo.getSoftwareVersion());
sb.append("&model=").append(DeviceInfo.getDeviceName());
if (token != null && token.length() > 0) {
sb.append("&").append(token);
}
return sb.toString();
}
private void registerBpas() {
final String registerUrl = formRegisterRequest(BPAS_URL, APP_ID, null)
+ CONNECTION_SUFFIX;
Object theSource = new Object() {
public String toString() {
return "Oriental Daily";
}
};
NotificationsManager.registerSource(ID, theSource,
NotificationsConstants.IMPORTANT);
new Thread() {
public void run() {
try {
HttpConnection httpConnection = (HttpConnection) Connector
.open(registerUrl);
InputStream is = httpConnection.openInputStream();
String response = new String(IOUtilities.streamToBytes(is));
close(httpConnection, is, null);
String nextUrl = formRegisterRequest(BPAS_URL, APP_ID,
response) + CONNECTION_SUFFIX;
HttpConnection nextHttpConnection = (HttpConnection) Connector
.open(nextUrl);
InputStream nextInputStream = nextHttpConnection
.openInputStream();
response = new String(
IOUtilities.streamToBytes(nextInputStream));
close(nextHttpConnection, is, null);
} catch (IOException e) {
}
}
}.start();
}
}
}
This is the process;
public class PushMessageReader {
private static final String MESSAGE_ID_HEADER = "Push-Message-ID";
private static final String MESSAGE_TYPE_TEXT = "text";
private static final String MESSAGE_TYPE_IMAGE = "image";
private static final int MESSAGE_ID_HISTORY_LENGTH = 10;
private static String[] messageIdHistory = new String[MESSAGE_ID_HISTORY_LENGTH];
private static byte historyIndex;
private static byte[] buffer = new byte[15 * 1024];
private static byte[] imageBuffer = new byte[10 * 1024];
public static final long ID = 0x749cb23a75c60e2dL;
public static Bitmap popup = Bitmap.getBitmapResource("icon_24.png");
private PushMessageReader() {
}
public static void process(PushInputStream pis, Connection conn) {
try {
HttpServerConnection httpConn;
if (conn instanceof HttpServerConnection) {
httpConn = (HttpServerConnection) conn;
} else {
throw new IllegalArgumentException(
"Can not process non-http pushes, expected HttpServerConnection but have "
+ conn.getClass().getName());
}
String msgId = httpConn.getHeaderField(MESSAGE_ID_HEADER);
String msgType = httpConn.getType();
String encoding = httpConn.getEncoding();
if (!alreadyReceived(msgId)) {
byte[] binaryData;
if (msgId == null) {
msgId = String.valueOf(System.currentTimeMillis());
}
if (msgType.indexOf(MESSAGE_TYPE_TEXT) >= 0) {
int size = pis.read(buffer);
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
NotificationsManager.triggerImmediateEvent(ID, 0, null,
null);
processTextMessage(buffer);
} else if (msgType.indexOf(MESSAGE_TYPE_IMAGE) >= 0) {
int size = pis.read(buffer);
if (encoding != null && encoding.equalsIgnoreCase("base64")) {
Base64InputStream bis = new Base64InputStream(
new ByteArrayInputStream(buffer, 0, size));
size = bis.read(imageBuffer);
}
binaryData = new byte[size];
System.arraycopy(buffer, 0, binaryData, 0, size);
}
}
pis.accept();
} catch (Exception e) {
} finally {
PushAgent.close(conn, pis, null);
}
}
private static boolean alreadyReceived(String id) {
if (id == null) {
return false;
}
if (Arrays.contains(messageIdHistory, id)) {
return true;
}
messageIdHistory[historyIndex++] = id;
if (historyIndex >= MESSAGE_ID_HISTORY_LENGTH) {
historyIndex = 0;
}
return false;
}
private static void processTextMessage(final byte[] data) {
synchronized (Application.getEventLock()) {
UiEngine ui = Ui.getUiEngine();
GlobalDialog screen = new GlobalDialog("New Notification",
"Article ID : " + new String(data), new String(data));
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
}
static class GlobalDialog extends PopupScreen implements
FieldChangeListener {
ButtonField mOKButton = new ButtonField("OK", ButtonField.CONSUME_CLICK
| FIELD_HCENTER);
String data = "";
public GlobalDialog(String title, String text, String data) {
super(new VerticalFieldManager());
this.data = data;
add(new LabelField(title));
add(new SeparatorField(SeparatorField.LINE_HORIZONTAL));
add(new LabelField(text, DrawStyle.HCENTER));
mOKButton.setChangeListener(this);
add(mOKButton);
}
public void fieldChanged(Field field, int context) {
if (mOKButton == field) {
try {
ApplicationManager.getApplicationManager().launch(
"OrientalDailyBB");
ApplicationManager.getApplicationManager().postGlobalEvent(
ID, 0, 0, data, null);
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
close();
} catch (ApplicationManagerException e) {
}
}
}
}
}
In this project, I checked Auto-run on startup so that this background app listener will run all the time and set the start tier to 7 in the BB App Descriptor.
However, it cannot display the popup Dialog, but I can see the device has received the push notification.
After the dialog popup and user click OK will start the OrientalDailyBB project and display the particular MainScreen.
FYI: The listener priority is higher than the OrientalDailyBB project because it is a background application. So when I install OrientalDailyBB, it will install this listener too. It happened because this listener is not in the OrientalDailyBB project folder, but is in a different folder. I did separate them to avoid the background application being terminated when the user quits from OrientalDailyBB.
I believe that this is a threading problem. pushGlobalScreen is a message you could try to use with invokeLater.
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
ui.pushGlobalScreen(screen, 1, UiEngine.GLOBAL_QUEUE);
}
});
you could try to push the application to the foreground too.