Blackberry - Running Background Application - blackberry

Good afternoon.
I'm starting programming in java and blackberry.
I am developing an application with three windows, which I will show basic information about the device, these windows are already done and working.
I need to create a process running in the background, this process will run every 10 minutes.
As I make this process run in the background and is working to close the windows?
This is the kind that runs the application:
public class InfoBerry extends UiApplication{
public vtnprincipal vtnprincipal;
public vtnbateria vtnbateria;
public vtnestado vtnestado ;
public vtnacerca vtnacerca;
public InfoBerry(){
}
public static void main(String[] args) {
InfoBerry theApp = new InfoBerry();
theApp.mostrarpantalla();
}
public void mostrarpantalla(){
vtnprincipal = new vtnprincipal(this);
vtnbateria = new vtnbateria(this);
vtnestado = new vtnestado(this);
vtnacerca = new vtnacerca(this);
// Inicailizamos los componentes de la pantalla principal
vtnprincipal.incventana();
// La pnemos en lo alto de la pila de pantallas
pushScreen(this.vtnprincipal);
}
}
And this is the class you need to run in the background.
As I have to make the call to this class to run in the background?
class iconnoti extends MainScreen{
//icono de la temperatura
EncodedImage imgtem =
EncodedImage.getEncodedImageResource("icon_bateria_t.png");
ApplicationIcon icontem = new ApplicationIcon(imgtem);
//icono de la carga de la bateria
EncodedImage imgcarga =
EncodedImage.getEncodedImageResource("icon_bateria.png");
ApplicationIcon iconcarga = new ApplicationIcon(imgcarga);
//icono de la memoria
EncodedImage imgmemo =
EncodedImage.getEncodedImageResource("icon_memoria.png");
ApplicationIcon iconmemo = new ApplicationIcon(imgmemo);
ApplicationIcon mIcon = icontem;
boolean act;
public iconnoti() {
}
public void rotar_temperatura(){
cron c1;
actualizar_icono(icontem);
actualizar_valor(DeviceInfo.getBatteryTemperature());
c1 = new cron(2,10000);
c1.start();
}
public void rotar_memoria(){
cron c1;
actualizar_icono(iconmemo);
actualizar_valor(34);
c1 = new cron(3,10000);
c1.start();
}
public void rotar_nivel(){
cron c1;
actualizar_icono(iconcarga);
actualizar_valor(DeviceInfo.getBatteryLevel());
c1 = new cron(1,10000);
c1.start();
}
public void iniciar_servicio() {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator Indicator =
reg.register(mIcon, false, true);
} catch (Exception e) {
}
}
public void parar_servicio() {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
reg.unregister();
} catch (Exception e) {
}
}
void actualizar_valor(int value) {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator =
reg.getApplicationIndicator();
appIndicator.setValue(value);
} catch (Exception e) {
}
}
void actualizar_icono(ApplicationIcon icon) {
try {
ApplicationIndicatorRegistry reg =
ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator =
reg.getApplicationIndicator();
appIndicator.setIcon(icon);
} catch (Exception e) {
}
}
}
class cron extends Thread {
//private ApplicationIcon icono;
public int valor;
private int tiempo;
iconnoti icon = new iconnoti();
public cron(int v, int t){
valor = v;
tiempo = t;
}
public void run() {
try {
sleep(tiempo);
} catch (InterruptedException e) {
}
if(valor == 1){
icon.rotar_temperatura();
}else if(valor == 2){
icon.rotar_memoria();
}else if(valor == 3){
icon.rotar_nivel();
}
}
}
Thanks for the help.

Background Application is a kind of process, so there is no GUI at least on the beginning.
You should extend Application instead of UIApplication class
You should not push screen there, just move everything from iconnoti class to cron class and run it in Application constructor:
public class BerryInfoApp extends Application {
public BerryInfoApp() {
UpdateThread updateThread = new UpdateThread(10*60*1000);
updateThread.run();
}
public static void main(String[] args) {
(new BerryInfoApp()).enterEventDispatcher();
}
}
class UpdateThread extends Thread {
EncodedImage imgtem = EncodedImage
.getEncodedImageResource("icon_bateria_t.png");
ApplicationIcon icontem = new ApplicationIcon(imgtem);
EncodedImage imgcarga = EncodedImage
.getEncodedImageResource("icon_bateria.png");
ApplicationIcon iconcarga = new ApplicationIcon(imgcarga);
EncodedImage imgmemo = EncodedImage
.getEncodedImageResource("icon_memoria.png");
ApplicationIcon iconmemo = new ApplicationIcon(imgmemo);
ApplicationIcon mIcon = icontem;
static final int ACTION_NONE = 0;
static final int ACTION_BATTERY_TEMP = 1;
static final int ACTION_MEMORY = 2;
static final int ACTION_BATTERY_LEVEL = 3;
int mAction = ACTION_BATTERY_LEVEL;
long mPeriod;
public UpdateThread(int period) {
mPeriod = period;
}
public void stop() {
mAction = ACTION_NONE;
}
public void run() {
iniciar_servicio();
while (mAction != ACTION_NONE) {
switch (mAction) {
case ACTION_BATTERY_TEMP:
rotar_temperatura();
mAction = ACTION_MEMORY;
break;
case ACTION_MEMORY:
rotar_memoria();
mAction = ACTION_BATTERY_LEVEL;
break;
case ACTION_BATTERY_LEVEL:
rotar_nivel();
mAction = ACTION_BATTERY_TEMP;
break;
default:
break;
}
try {
sleep(mPeriod);
} catch (InterruptedException e) {
}
}
parar_servicio();
}
public void rotar_temperatura() {
actualizar_icono(icontem);
actualizar_valor(DeviceInfo.getBatteryTemperature());
}
public void rotar_memoria() {
actualizar_icono(iconmemo);
actualizar_valor(34);
}
public void rotar_nivel() {
actualizar_icono(iconcarga);
actualizar_valor(DeviceInfo.getBatteryLevel());
}
public void iniciar_servicio() {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator Indicator = reg.register(mIcon, false, true);
} catch (Exception e) {
}
}
public void parar_servicio() {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
reg.unregister();
} catch (Exception e) {
}
}
void actualizar_valor(int value) {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
appIndicator.setValue(value);
} catch (Exception e) {
}
}
void actualizar_icono(ApplicationIcon icon) {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry
.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
appIndicator.setIcon(icon);
} catch (Exception e) {
}
}
}

Related

Vaadin Combobox and LazyInitializationException

My question maybe simple simple but I don't understand why Vaadin combobox tries to get a colletion of nested entities set in a combobox if I do not call these items of collection.
See this:
#Entity
public class Estado extends AbstractEntity {
private String nome;
private String sigla;
#OneToMany(mappedBy = "estado")
private List<Municipio> municipios;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public List<Municipio> getMunicipios() {
return municipios;
}
public void setMunicipios(List<Municipio> municipios) {
this.municipios = municipios;
}
private void initCbEstados() {
if (cbEstados.isEmpty()) {
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
}
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void updateViewToEdit(){
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
***//this throws LazyInitializationException***
cbEstados.setValue(estado);
updateCbMunicipios();
}
I do not call at any time estado.getMunicipios. But apparently the behavior of the combobox tries to infer in the municipios released the exception.
Is this expected behavior?
I don't think it should be?
Sory, fisrt post on stack overflow and i was not familiar with the platform and ended not posting the entire code. The error occurred in
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
that during the debug was not visible because it was occurring within the vaadin classes. The problem was solved by searching for the municpios in updateCbMunicpios(); So when FormBase calls beforeEnter(BeforeEnterEvent event) the readBean() set values on cbEstados that fires ValuechangeListener and load the LazeInicializaTionExceptions because Entity comes from the Request Scoope and not Fully filed to set the Value of Municipio in cbMunicipios. And cbMunicipios would be empty firing anhoter error from Vaadin.
public class FornecedorForm extends CadastroFormBaseGenerics<Fornecedor, FornecedorService> {
private static final long serialVersionUID = -5599427454458715210L;
EstadoService estadoService;
#PropertyId("ativo")
private Checkbox ckAtivo;
#PropertyId("razaoSocial")
private TextField txtRazaoSocial;
#PropertyId("nomeFantasia")
private TextField txtNomeFantasia;
#PropertyId("cnpj")
private TextField txtCnpj;
#PropertyId("contato")
private TextField txtContato;
#PropertyId("telefoneContato")
private TextField txtTelContato;
#PropertyId("telefone")
private TextField txtTelefone;
#PropertyId("observacao")
TextArea txtObservacao;
private ComboBox<Estado> cbEstados;
private ComboBox<Municipio> cbMunicipios;
private TextField txtCep;
private TextField txtLogradouro;
private TextField txtNumero;
private TextField txtComplemento;
#PropertyId("emailContato")
EmailField txtEmailContato;
private FormLayout layout;
HorizontalLayout layoutEstado;
public FornecedorForm(#Autowired EstadoService estadoService) {
super(Fornecedor.class, "Fornecedor");
this.estadoService = estadoService;
updateViewToEdit();
}
protected void configureAdditionalBinds() {
getBinder().bind(cbEstados, "endereco.estado");
getBinder().bind(cbMunicipios, "endereco.municipio");
getBinder().bind(txtCep, "endereco.cep");
getBinder().bind(txtLogradouro, "endereco.logradouro");
getBinder().bind(txtNumero, "endereco.numero");
getBinder().bind(txtComplemento, "endereco.complemento");
}
private void initCbEstados() {
cbEstados = new ComboBox<Estado>("Estado");
List<Estado> estados = estadoService.findAllEager();
cbEstados.setItems(estados);
cbEstados.addValueChangeListener(e -> updateCbMunicipios());
cbEstados.setClearButtonVisible(true);
cbEstados.setItemLabelGenerator(Estado::getNome);
cbEstados.setWidth("50%");
}
private void initCbMunicpios() {
cbMunicipios = new ComboBox<Municipio>("Município");
cbMunicipios.setItemLabelGenerator(Municipio::getNome);
cbMunicipios.setWidth("50%");
cbMunicipios.setReadOnly(true);
}
private void updateCbMunicipios() {
if (cbEstados.getValue() != null) {
cbMunicipios.clear();
cbMunicipios.setReadOnly(false);
Estado estado = estadoService.findMunicipios(cbEstados.getValue());
cbMunicipios.setItems(estado.getMunicipios());
} else {
cbMunicipios.clear();
cbMunicipios.setReadOnly(true);
}
}
#Override
protected void initViewComponents() {
layoutEstado = new HorizontalLayout();
layout = new FormLayout();
layoutEstado.setSizeFull();
initCbEstados();
initCbMunicpios();
ckAtivo = new Checkbox("Ativo ?", true);
txtRazaoSocial = new TextField("Razão Social");
txtNomeFantasia = new TextField("Nome Fantasia");
txtCnpj = new TextField("CNPJ");
txtCnpj.setWidth("25%");
// txtCnpj.setErrorMessage("CNPJ Incorreto.");
// txtCnpj.setPattern("^[0-9]{2}?[-s.]?[0-9]{3}[-s.]?[0-9]{3}[-s/]?[0-9]{4}[-s-]?[0-9]{2}$");
txtTelefone = new TextField("Telefone");
txtContato = new TextField("Nome Contato");
txtTelContato = new TextField("Telefone Contato");
txtEmailContato = new EmailField("Email Contato");
txtEmailContato.setClearButtonVisible(true);
txtEmailContato.setErrorMessage("Formato do E-mail incorreto");
txtEmailContato.setRequiredIndicatorVisible(false);
txtLogradouro = new TextField("Logradouro");
txtNumero = new TextField("Número");
txtNumero.setWidth("50px");
txtCep = new TextField("CEP");
txtCep.setPattern("^[0-9]{5}?[-s-]?[0-9]{3}$");
txtCep.setPlaceholder("00000-000");
txtCep.setRequired(true);
txtCep.setErrorMessage("Informe o CEP");
txtCep.setWidth("75px");
txtComplemento = new TextField("Complemento");
txtObservacao = new TextArea("Observações");
layout.add(ckAtivo, 2);
layout.add(txtCnpj, 2);
layout.add(txtRazaoSocial, txtNomeFantasia);
layout.add(layoutEstado, 2);
layout.add(txtLogradouro, txtNumero);
layout.add(txtComplemento, txtCep, txtTelefone);
HorizontalLayout layoutContato = new HorizontalLayout(txtContato, txtTelContato, txtEmailContato);
layoutContato.setSizeFull();
txtContato.setWidth("40%");
txtEmailContato.setWidth("40%");
txtTelContato.setWidth("20%");
layout.add(layoutContato, 2);
layout.add(txtObservacao, 2);
super.formLayout.add(layout);
layoutEstado.add(cbEstados, cbMunicipios);
configureAdditionalBinds();
}
protected void updateViewToEdit() {
if (isEditMode) {
Estado estado = entity.getEndereco().getEstado();
estado = estadoService.findMunicipios(estado);
cbEstados.setValue(estado);
}
}
#Override
protected void getNewEntityToPersist() {
entity = new Fornecedor();
entity.setEndereco(new Endereco());
ckAtivo.setValue(true);
}
}
public abstract class CadastroFormBaseGenerics<T, SERVICE extends ServiceInterface<T>> extends FormLayout
implements BeforeEnterObserver {
private static final long serialVersionUID = 7069232922824142288L;
protected T entity;
#Autowired
private SERVICE service;
private final Class<T> beanClass;
private Binder<T> binder;
private String nomeDoBean;
protected boolean isEditMode;
private Button btnSave = new Button("Salvar");
private Button btnDelete = new Button("Excluir");
private Button btnCancel = new Button("Cancelar");
protected VerticalLayout formLayout = new VerticalLayout();;
private HorizontalLayout buttonsLayout = new HorizontalLayout();
public CadastroFormBaseGenerics(Class<T> beanClass, String nomeDoBean) {
this.beanClass = beanClass;
this.nomeDoBean = nomeDoBean;
}
protected abstract void initViewComponents();
#PostConstruct
private void inicialize() {
checkEditMode();
initBinder();
initViewComponents();
addComponentAsFirst(formLayout);
configureFormLayout();
getEntityToEdit();
updateViewToEdit();
}
protected abstract void updateViewToEdit();
protected void initBinder() {
binder = new BeanValidationBinder<T>(beanClass);
}
protected void setPlaceHolders(String beanName) {
String primeiraLetra = "" + beanName.charAt(0);
primeiraLetra = primeiraLetra.toUpperCase();
char letraMaiuscula = primeiraLetra.charAt(0);
char[] cArray = beanName.toCharArray();
cArray[0] = letraMaiuscula;
beanName = new String(cArray);
for (int i = 0; i < formLayout.getComponentCount(); i++) {
Component c = formLayout.getComponentAt(i);
if (c.getClass().getName().equals("com.vaadin.flow.component.textfield.TextField")) {
TextField aux = (TextField) c;
aux.setPlaceholder(aux.getLabel() + " " + beanName + "...");
aux.setClearButtonVisible(true);
}
}
}
protected void configureFormLayout() {
formLayout.setSizeFull();
// formLayout.setMargin(true);
formLayout.setSpacing(true);
formLayout.setPadding(true);
formLayout.setAlignItems(Alignment.AUTO);
formLayout.setMargin(true);
// add(formLayout, 2);
configureButtonsLayout();
}
void configureButtonsLayout() {
btnDelete.setVisible(false);
btnSave.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
btnDelete.addThemeVariants(ButtonVariant.LUMO_ERROR);
buttonsLayout = new HorizontalLayout();
buttonsLayout.add(btnSave, btnDelete, btnCancel);
buttonsLayout.setMargin(true);
buttonsLayout.setPadding(true);
buttonsLayout.setSizeFull();
configureButtonEvents();
add(buttonsLayout, 2);
}
private void configureButtonEvents() {
btnSave.addClickListener(saveEvent -> save());
btnDelete.addClickListener(deleteEvent -> delete());
btnCancel.addClickListener(cancelEvent -> clearForm());
}
private void save() {
String msg = nomeDoBean + " Alterada(o) com sucesso.";
if (!isEditMode) {
msg = nomeDoBean + " Cadastrada(o) com sucesso.";
getNewEntityToPersist();
// getNewEntity();
}
try {
getBinder().writeBean(entity);
service.save(entity);
clearForm();
showSucess(msg);
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " já cadastrado. Verique.");
logException(e, "Metodo save()");
} catch (ValidationException e) {
showWarnig("Verique os campos obrigatórios.");
}
}
/**
* {#summary} Você deve implementar o {#code} entity = New POJO este método é
* chamado toda vez que {#code} save() para criar um novo BEAN a ser persistido.
*/
protected abstract void getNewEntityToPersist();
private void delete() {
try {
service.delete(entity);
clearForm();
showSucess(nomeDoBean + " removida(o) com sucesso.");
} catch (DoisCsCrudException e) {
showWarnig(nomeDoBean + " não pode ser removida(o), pois existem registros que dependem dele. %/n "
+ "Inative-o para que não seja mais exibido.");
}
}
#SuppressWarnings("unchecked")
private void getEntityToEdit() throws ClassCastException {
if (isEditMode) {
btnDelete.setVisible(true);
this.entity = (T) VaadinServletRequest.getCurrent().getAttribute("entityToEdit");
}
}
private boolean checkEditMode() {
if (VaadinServletRequest.getCurrent().getAttribute("entityToEdit") != null) {
isEditMode = true;
} else {
isEditMode = false;
}
return isEditMode;
}
/**
* Sempre deve ser chamado após um click no botão salvar, cancelar ou excluir
*/
protected void clearForm() {
// Desabilita o botão para excluir um Bean Cadastrado
btnDelete.setVisible(false);
// Seta editmode para falso, garantido que a proxima interação
// seja com um bean novo
isEditMode = false;
clearBinder();
}
protected void clearBinder() {
binder.readBean(null);
}
protected void showSucess(String message) {
createNotification(message, NotificationVariant.LUMO_SUCCESS, 3000);
}
protected void showError(String message) {
createNotification(message, NotificationVariant.LUMO_ERROR, 5000);
}
protected void showWarnig(String message) {
createNotification(message, NotificationVariant.LUMO_CONTRAST, 10000);
}
private void createNotification(String message, NotificationVariant variant, int duration) {
Notification n = new Notification(message);
n.setDuration(7000);
n.addThemeVariants(variant);
n.setPosition(Position.TOP_CENTER);
n.open();
}
protected void logException(Exception e, String logDesc) {
System.out.println("################ " + logDesc.toUpperCase() + " $$ " + getClass().getSimpleName()
+ " ################");
e.printStackTrace();
}
public Binder<T> getBinder() {
return binder;
}
#Override
public void beforeEnter(BeforeEnterEvent event) {
binder.bindInstanceFields(this);
if (entity != null) {
getBinder().readBean(entity);
}
}
}

Background Application unable to display UI when receive push notification

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.

Get Camera captured images and create bitmap image

How to get camera captured images after native camera app exits ?
How to create an Bitmap image from the already existing SD card Jpeg image ?
I want to add this Bitmap to the screen.
ButtonField btn_Take_Pic = new ButtonField("Take a pic",Field.FIELD_HCENTER|FOCUSABLE)
{
protected boolean navigationClick(int status, int time) {
// TODO Auto-generated method stub
InvokeCameraScreen screen = new InvokeCameraScreen(CaptureImage.this);
screen.addCam();
UiApplication.getUiApplication().invokeLater (new Runnable() {
public void run()
{
//Perform screen changes here.
//Calling invalidate() on your screen forces the paint
//method to be called.
CaptureImage deal_Screen = new CaptureImage();
deal_Screen.invalidate();
}
});
return true;
}
};
Add body part of ImagePath() method
public void ImagePath(String path) {
try
{
Img_path = path;
EncodedImage.createEncodedImage(imgarr,0,imgarr.length);
Bitmap setimage = resizeBitmap(getBitmapFromFile(info.getImg_Path()),(int) (ScreenWidth *0.20),(int) (ScreenHeight *0.20));
Img_Field.setBitmap(setimage);
}
catch (Exception e) {
// TODO: handle exception
Dialog.alert("Ex path: " + e.toString());
}
}
implements ImagePath interface
public interface ImagePath {
public void ImagePath(String path);
}
public class InvokeCameraScreen implements FileSystemJournalListener {
private long lastUSN;
private String resultData, imagepath;
private VerticalFieldManager addToSCreen;
private boolean isAlreadeyExcuted = true;
private byte[] imageData;
private ImagePath pathImage;
public InvokeCameraScreen(ImagePath path) {
this.pathImage = path;
}
public void addCam() {
isAlreadeyExcuted = true;
getAddToSCreen().deleteAll();
startCam();
}
private void startCam() {
lastUSN = FileSystemJournal.getNextUSN();
UiApplication.getUiApplication().addFileSystemJournalListener(this);
try {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA,
new CameraArguments());
}
});
} catch (Exception e) {
System.out.println("CheckinFormScreen Exception: " + e.toString());
}
}
private void closeCamera() {
System.out.println("Closing Cam");
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 25);
inject.post();
try {
Thread.sleep(500);
} catch (Exception e) {
}
UiApplication.getUiApplication().removeFileSystemJournalListener(this);
System.out.println("Done with closing cam");
}
public byte[] getImageData() {
return imageData;
}
public void setImageData(byte[] imageData) {
this.imageData = imageData;
}
public String getImagepath() {
return imagepath;
}
public void setImagepath(String imagepath) {
this.imagepath = imagepath;
}
public void fileJournalChanged() {
try {
closeCamera();
} catch (Exception e) {
}
long USN = FileSystemJournal.getNextUSN();
for (long i = USN - 1; i >= lastUSN && i < USN; --i) {
FileSystemJournalEntry entry = FileSystemJournal.getEntry(i);
if (entry == null) {
break;
}
if (entry.getEvent() == FileSystemJournalEntry.FILE_ADDED) {
String path = entry.getPath();
if (path != null && path.indexOf(".jpg") != -1) {
if (isAlreadeyExcuted) {
isAlreadeyExcuted = false;
resultData = "file://" + path;
pathImage.ImagePath(resultData);
// ShowUploadImage(resultData);
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(
EventInjector.KeyEvent.KEY_DOWN,
Characters.ESCAPE, 0, 25);
inject.post();
inject.post();
if (Display.getWidth() == 480
&& Display.getHeight() == 360
|| Display.getWidth() == 360
&& Display.getHeight() == 480) {
try {
Thread.sleep(500);
inject.post();
} catch (Exception e) {
}
}
}
}
return;
}
}
}
public VerticalFieldManager getAddToSCreen() {
if (addToSCreen == null) {
addToSCreen = new VerticalFieldManager();
addToSCreen.setPadding(10, 10, 10, 10);
}
return addToSCreen;
}
public void setAddToSCreen(VerticalFieldManager addToSCreen) {
this.addToSCreen = addToSCreen;
}
private void ShowUploadImage(String path) {
}
}
try this,
CAll Below Class Like:
EncodedImage result = NcCamera.getInstance().getPictureTaken();
//
This is class in which you can get Camera images.
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.control.VideoControl;
import net.rim.device.api.system.Bitmap;
import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;
import net.rim.device.api.ui.Screen;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;
public class NcCamera extends MainScreen
{
private VideoControl videoControl;
private Field videoField;
public static EncodedImage pictureTaken = null;
private boolean initialized = false;
private boolean result;
public static boolean CAPTURING_DONE = true;
public static boolean CAPTURING_CANCELED = false;
private VerticalFieldManager main;
private static NcCamera instance;
CommonFunction cmn_fun;
public static byte[] raw;
public NcCamera()
{
super(NO_VERTICAL_SCROLL);
main = new VerticalFieldManager(USE_ALL_WIDTH | USE_ALL_HEIGHT)
{
// I wan't to force the backgound to black
public void paintBackground(Graphics g)
{
g.setBackgroundColor(0x000000);
g.clear();
}
};
super.add(main);
}
public void add(Field field)
{
main.add(field);
}
public EncodedImage getPictureTaken()
{
return pictureTaken;
}
public Screen getThisScreen()
{
return this;
}
public void reset()
{
pictureTaken = null;
result = CAPTURING_CANCELED;
}
public boolean showDialog()
{
result = CAPTURING_CANCELED;
UiApplication.getUiApplication().invokeAndWait(new Runnable()
{
public void run()
{
UiApplication.getUiApplication().pushModalScreen(getThisScreen());
if (pictureTaken != null)
result = CAPTURING_DONE;
}
});
return result;
}
public static NcCamera getInstance()
{
if (instance == null)
instance = new NcCamera();
return instance;
}
public void onDisplay() {
if (!initialized)
{
initializeCamera();
if (videoField!=null) add(videoField);
else {
LabelField sorry = new LabelField("Sorry, we cannot use camera right now.") {
// I need to force the label to be white colored to be visible above
// it's underlying manager (that is black).
public void paint(Graphics g) {
int color = g.getColor();
g.setColor(0xffffff);
super.paint(g);
g.setColor(color);
}
};
add(sorry);
}
initialized = true;
}
}
private void initializeCamera()
{
try {
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
if (videoControl != null)
{
videoField = (Field) videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE,
"net.rim.device.api.ui.Field");
videoControl.setDisplayFullScreen(true);
videoControl.setVisible(true);
}
player.start();
} catch (Exception e)
{
}
}
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if (!handled)
{
switch (action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void takePicture()
{
try {
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
raw = videoControl.getSnapshot(null);
// SaveImageSdcard(raw);
Bitmap img= Bitmap.createBitmapFromBytes(raw, 0, raw.length,3);
Constants.PICTURE_TAKEN=cmn_fun.resizeBitmap(img, 150, 150);
// save the picture taken into pictureTaken variable
pictureTaken = EncodedImage.createEncodedImage(raw, 0, raw.length);
result = CAPTURING_DONE;
close();
} catch (Exception e)
{
}
}
}
public boolean keyDown(int keycode,
int time) {
if (keycode == 1769472)
{ // escape pressed
reset();
close();
return true;
}
return super.keyDown(keycode, time);
}
}

Create Notifications On Home Screen

I want to create notification icon on home screen when the application is run in background,,in the application have thread for check upcoming respon,,and i want to show in home screen use notification icon,,can help me??
Use the following code:
public static void registerIndicator() {
EncodedImage mImageGreen = EncodedImage.getEncodedImageResource("res/mail.png");
ApplicationIcon mIconGreen = new ApplicationIcon(mImageGreen);
ApplicationIcon mIcon = mIconGreen;
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator indicator = reg.register(mIcon, false, true);
} catch (Exception ex) { }
}
public static void updateIndicatorValue(int value) {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
appIndicator.setValue(value);
} catch (Exception e) { }
}
public static int getIndicatorValue() {
try {
ApplicationIndicatorRegistry reg = ApplicationIndicatorRegistry.getInstance();
ApplicationIndicator appIndicator = reg.getApplicationIndicator();
return appIndicator.getValue();
} catch (Exception e) { }
return -1;
}

Adding Editfield to Popup screen

I have created my own custom popup screen to which now I am trying to add a editfield , everything seems to be fine but the problem is that I am not able to write anything in the edit field
class sveetIt extends PopupScreen implements FieldChangeListener, DialogClosedListener {
Hashtable pitemData;
ButtonField sveetNowlabelField;
ButtonField sveetLaterlabelField;
WatingScreen watingScreen;
long scheduledTime;
Dialog updateDialog;
public sveetIt() {
super(new MyCustimGridFieldManager());
LabelField messageLabelField = new LabelField("Enter your Sveet Message:",Field.FIELD_HCENTER) {
protected void paint(Graphics graphics) {
graphics.setColor(Color.YELLOWGREEN);
super.paint(graphics);
}
};
EditField sveetTexteditField= new EditField(null, "Sveet Message", 50, EditField.FIELD_HCENTER
| EditField.FIELD_VCENTER
| EditField.NON_SPELLCHECKABLE | EditField.NO_NEWLINE);
VerticalFieldManager buttonVFManager = new VerticalFieldManager(VerticalFieldManager.FIELD_HCENTER);
HorizontalFieldManager hfManager = new HorizontalFieldManager();
sveetNowlabelField = new ButtonField("Sveet Now");
sveetLaterlabelField = new ButtonField("Sveet Later");
sveetNowlabelField.setChangeListener(this);
sveetLaterlabelField.setChangeListener(this);
add(messageLabelField);
add(sveetTexteditField);
hfManager.add(sveetNowlabelField);
hfManager.add(sveetLaterlabelField);
buttonVFManager.add(hfManager);
add(buttonVFManager);
}
public boolean isEditable() {
return true;
}
protected boolean keyChar(char c, int status, int time) {
boolean retVal = false;
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
retVal = super.keyChar(c, status, time);
}
return retVal;
}
public void fieldChanged(Field field, int context) {
if (sveetNowlabelField == field) {
//Here directly starts uploading file
beginUpload();
} else if (sveetLaterlabelField == field) {
// first picks up time when to upload
scheduledTime = getScheduleTime();
if(scheduledTime!=1L) {
//now begins uploading file
beginUpload();
}
}}
class SubscribingThread extends StoppableThread {
int network = 50;
public void run() {
}
}
public void beginUpload() {
try {
watingScreen = new WatingScreen("Uploading Sveet...");
/*
* UiApplication.getUiApplication().invokeAndWait( new Runnable() {
* public void run() { Ui.getUiEngine().pushScreen(watingScreen); }
* });
*/
BaseScreen.pushScreen(watingScreen);
Thread thread = new Thread(new Runnable() {
public void run() {
uploadToServer();
}
});
thread.start();
// uploadToServer();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
}
}
private long getScheduleTime() {
scheduledTime = 0;
final DateTimePicker datePick = DateTimePicker.createInstance();
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Calendar currentCalendar = datePick.getDateTime();
datePick.setMinimumDate(currentCalendar);
datePick.doModal();
Calendar cal = datePick.getDateTime();
if (cal.after(currentCalendar)) {
Date date = cal.getTime();
Dialog.alert("You selected " + date.toString());
scheduledTime = date.getTime();
} else {
Dialog.alert("Invalid date selection");
scheduledTime = 1L;
}
}
});
System.out.println("date in MilliSeconds is:" + scheduledTime);
return scheduledTime;
}
public void uploadToServer() {
} public void dialogClosed(Dialog arg0, int arg1) {
}
}
class MyCustimGridFieldManager extends VerticalFieldManager {
public MyCustimGridFieldManager() {
super(VERTICAL_SCROLL | USE_ALL_WIDTH | FIELD_HCENTER);
}
protected void paint(Graphics gr) {
super.paint(gr);
}
}
try this:
protected boolean keyChar(char c, int status, int time) {
if (c == Characters.ESCAPE) {
Ui.getUiEngine().popScreen(this);
}
return super.keyChar(c, status, time);
}
Try adding Field.EDITABLE to your style for the EditField.

Resources