Flashlight with strobe: turn flashlight ON when wheel view value is start from 1 to 10 then thread is not stop on zero value - multithreading

When the strobe value is increased from 1 to 10 the blinking of flashlight will never stop.neither it stops on zero nor it turns on beside it just get blinking and blinking constantly. here i am adding the code which i have written to do so. if someone knows the solutions please help me.
Thread is not stop thread works until you stop debugger..
cheers!
enter code here
flashButton = findViewById(R.id.flash_button);
mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
mCameraId = mCameraManager.getCameraIdList()[0];
} catch (CameraAccessException e) {
e.printStackTrace();
}
flashButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (!isTorchOn) {
turnOnFlashLight();
} else {
turnOffFlashLight();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
scrollValue = findViewById(R.id.value);
mWheel = findViewById(R.id.wheel);
mWheel.setOnScrollListener(new Wheel.OnScrollListener() {
#Override
public void onScrollStarted(Wheel view, float value, int roundValue) {
frequency = Math.abs(roundValue);
}
#Override
public void onScrollFinished(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
thread = new Thread(stroboRunner);
thread = null;
strobe(frequency);
}
else if(isTorchOn) {
strobe(0);
// thread.stop();
// thread=null;
}
}
#Override
public void onScroll(Wheel view, float value, int roundValue) {
scrollValue.setText("" + Math.abs(roundValue));
frequency = strobeFrequency(Math.abs(roundValue));
if(isTorchOn && frequency > 0) {
// thread = null;
strobe(frequency);
}
}
});
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOnFlashLight() {
/*
if(frequency > 0){
scrollValue.setText("0.0");
}
*/
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mCameraManager.setTorchMode(mCameraId, true);
} else {
try {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
cam.setParameters(camParams);
cam.startPreview();
} catch (RuntimeException e) {
Toast.makeText(this, "Camera Permission is not granted", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_on);
isTorchOn = true;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void turnOffFlashLight() {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
mCameraManager.setTorchMode(mCameraId, false);
}
} else {
try {
if(thread != null){
stroboRunner.stopRunning = true;
thread = null;
}else {
camParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
cam.stopPreview();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(), "Exception throws in turning off flashlight.", Toast.LENGTH_SHORT).show();
}
}
flashButton.setImageResource(R.drawable.power_off);
isTorchOn = false;
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private int strobeFrequency(int roundValue) {
int freq = 0;
switch (roundValue) {
case 1:
freq = Math.abs(50);
break;
case 2:
freq = Math.abs(150);
break;
case 3:
freq = Math.abs(300);
break;
case 4:
freq = Math.abs(600);
break;
case 5:
freq = Math.abs(900);
break;
case 6:
freq = Math.abs(1200);
break;
case 7:
freq = Math.abs(1500);
break;
case 8:
freq = Math.abs(1800);
break;
case 9:
freq = Math.abs(2000);
break;
case 10:
freq = Math.abs(2300);
break;
}
return freq;
}
#Override
protected void onResume() {
super.onResume();
try {
cam = Camera.open();
camParams = cam.getParameters();
cam.startPreview();
hasCam = true;
} catch (Exception e) {
// TODO: handle exception
}
compass.start();
}
#Override
protected void onPause() {
super.onPause();
compass.stop();
}
#Override
protected void onStop() {
super.onStop();
Log.d(TAG, "stop compass");
compass.stop();
}
private void strobe(int freq) {
if(thread == null){
stroboRunner = new StroboRunner();
stroboRunner.freq = freq;
thread = new Thread(stroboRunner);
thread.start();
} else if(freq == 0 && thread!=null) {
stroboRunner.stopRunning = true;
thread = null;
// thread.stop();
}
}
private class StroboRunner implements Runnable {
int freq;
boolean stopRunning = false;
#Override
public void run() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
try {
while (!stopRunning) {
mCameraManager.setTorchMode(mCameraId, true);
Thread.sleep(2600 - freq);
System.out.println(""+(2600-freq));
// Toast.makeText(MainActivity.this, ""+(2600-freq), Toast.LENGTH_SHORT).show();
mCameraManager.setTorchMode(mCameraId, false);
Thread.sleep(freq);
}
} catch (CameraAccessException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
// thread=null;
} else {
Camera.Parameters paramsOn = cam.getParameters();
Camera.Parameters paramsOff = camParams;
paramsOn.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
paramsOff.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
try {
while (!stopRunning) {
cam.setParameters(paramsOn);
cam.startPreview();
Thread.sleep(2600 - freq);
cam.setParameters(paramsOff);
cam.startPreview();
Thread.sleep(freq);
}
} catch (Exception e) {
// TODO: handle exception
}
}
}
}

Related

My handlers don't work smooth.How can i fix it?

Hello everyone i try to get commands from txt file and I want to run these commands in order for a certain period of time.I can get the commands from the txt file correctly but when I want to do these commands using handlers for a certain period of time but there is a problem.The problem is handlers work together,the other Handler comes into play before the first Handler's time expires.When i did that with same runnable it did same thing.
My txt file looks like:
Ileri,5,1 /n
Sol,10,1 /n -->10 is operation time 1 is The number of repetitions.
Sag,5,1 /n
Geri,10,1 /n
My output:
I/System.out: Ileri
6000
1
I/System.out: Sol
11000
1
I/System.out: Sag
6000
1
I/System.out: Geri
11000
1
I/System.out: A
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer=new Timer();
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line[i];
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
//String gonderilecek=new String();
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2)
{
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1=sure1*1000;
sure1=sure1+1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e=0;
switch (yon)
{
case "Ileri":
runnable=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp.start();
}
else
{
handler.removeCallbacks(runnable);
}
}
};
handler.postDelayed(runnable,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sol":
runnable2=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp2.start();
}
else
{
handler.removeCallbacks(runnable2);
}
}
};
handler.postDelayed(runnable2,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Sag":
runnable3=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp3.start();
}
else
{
handler.removeCallbacks(runnable3);
}
}
};
handler.postDelayed(runnable3,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
case "Geri":
runnable4=new Runnable() {
#Override
public void run() {
sure1=sure1-1000;
if(sure1>0)
{
handler.postDelayed(this,1000);
mp4.start();
}
else
{
handler.removeCallbacks(runnable4);
}
}
};
handler.postDelayed(runnable4,1000);
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
}
});
I solved my problem by using thread.sleep(); and i'm writing here because someone might need my code.
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
timer=new Timer();
///data/data/com.example.emrecan.myapplication/files/komutlar.txt
String yon;
String saniye1;
String tekrar;
int i=0,j=0,c=0,d=0;
ArrayList<String> listS=new ArrayList<String>();
try {
Scanner s=new Scanner(new File("/data/data/com.example.emrecan.myapplication/files/komutlar.txt"));
while(s.hasNextLine())
{
listS.add(s.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String[] line2=new String[100];
for(String str:listS)
{
String[] line=str.split(",");
line2[c]=line[i];
line2[c+1]=line[i+1];
line2[c+2]=line[i+2];
c=c+3;
}
String [] line3=new String[c+2];
while(d<c)
{
line3[d]=line2[d];
d=d+1;
}
d=0;
tekrar=line3[2];
int tekrar1=Integer.parseInt(tekrar);
while(d<tekrar1)
{
while(j<=c-2) {
yon = line3[j];
saniye1 = line3[j + 1];
sure1 = Long.parseLong(saniye1);
sure1 = sure1 * 1000;
//sure1 = sure1 + 1000;
System.out.println(yon);
System.out.println(sure1);
System.out.println(tekrar1);
e = 0;
while (sure1>0)
{
switch (yon) {
case "Ileri":
try {
outputStream.write(1);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sol":
try {
outputStream.write(2);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Sag":
try {
outputStream.write(3);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
case "Geri":
mp4.start();
try {
outputStream.write(4);
} catch (IOException e1) {
e1.printStackTrace();
}
Toast.makeText(getApplicationContext(), "Komut Tamamlandı!", Toast.LENGTH_LONG).show();
try {
Thread.sleep(1000); //1000 milliseconds is one second.
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
break;
default:
Toast.makeText(getApplicationContext(), "Sıkıntı var!", Toast.LENGTH_LONG).show();
break;
}
sure1=sure1-1000;
}
j=j+3;
}
j=0;
d=d+1;
System.out.println('A');
}
try {
outputStream.write(10);
} catch (IOException e1) {
e1.printStackTrace();
}
}
});

self hosted pushsharp - Events_OnNotificationSendFailure Failure: There were not enough free threads in the ThreadPool to complete the operation

i my PushSharp service is self hosted in windows service,
but after a short while it always throws:
Events_OnNotificationSendFailure
- the exception is "There were not enough free threads in the ThreadPool to complete the operation". what is the proper way to do that?
public partial class PushNotificationService : ServiceBase
{
private static bool flagNotification = true;
static PushService push;
protected override void OnStart(string[] args)
{
SetPushService();
//start console service worker
Thread t = new Thread(NotificationServiceWorker);
t.IsBackground = true;
t.Start();
}
private static void NotificationServiceWorker()
{
try
{
int sendNotificationTimeGap = Convert.ToInt32(ConfigurationManager.AppSettings["SendNotificationTimeGap"]);
while (flagNotification)
{
try
{
/// get IosPushNotificationService
IosPushNotificationService pns = new IosPushNotificationService();
/// Get The New Notification from db
List<NewPushNotifications> notificationToSend = pns.GetIosNotificationsToSend().Where(n => (n.CreatedDate ?? DateTime.Now) > DateTime.Now.AddMinutes(-5)).ToList();
if (notificationToSend != null && notificationToSend.Count > 0)
{
SendNotificationToIphone(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Iphone).ToList());
SendNotificationToAndroid(notificationToSend.Where(gn => gn.deviceType.Value == (int)DeviceType.Android).ToList());
}
Thread.Sleep(sendNotificationTimeGap);
}
catch (Exception ex)
{
CustomError.Error("error in flagNotification loop", ex);
}
}
}
catch (Exception ex)
{
CustomError.Error("error in NotificationServiceWorker", ex);
}
}
private static void SetPushService()
{
push = new PushService();
push.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
push.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
push.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
push.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
push.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
string androidSenderId = ConfigurationManager.AppSettings["AndroidSenderId"];
string androidSenderAuthToken = ConfigurationManager.AppSettings["AndroidSenderAuthToken"];
string androidPackage = ConfigurationManager.AppSettings["androidPackage"];
push.StartGoogleCloudMessagingPushService(new GcmPushChannelSettings(androidSenderId, androidSenderAuthToken, androidPackage), new PushSharp.Common.PushServiceSettings() { AutoScaleChannels = false });
string appleCertificates = ConfigurationManager.AppSettings["AppleCertificates"];
var appleCert = File.ReadAllBytes(appleCertificates);
var appleCertPassword = ConfigurationManager.AppSettings["AppleCertPassword"];
var appleIsProduction = ConfigurationManager.AppSettings["AppleIsProduction"].ToLower() == bool.TrueString;
push.StartApplePushService(new ApplePushChannelSettings(appleIsProduction, appleCert, appleCertPassword));
}
}
Don't use thread instead you can use timer like this
protected override void OnStart(string[] args)
{
NotificationServiceEventLog.WriteEntry("Service Started at"+DateTime.Now);
if (oNotificationComponent ==null)
oNotificationComponent = new NotificationComponent();
Heading
try
{
if (StartAppleNotificationService())
StartTimer();
}
catch (Exception ex)
{
NotificationServiceEventLog.WriteEntry(ex.Message);
}
base.OnStart(args);
}
private bool StartAppleNotificationService() {
bool IsStarted = false;
try
{
if (oPushService == null)
oPushService = new PushService();
NotificationServiceEventLog.WriteEntry("Apple Notification Service started successfully");
oPushService.Events.OnChannelCreated += new PushSharp.Common.ChannelEvents.ChannelCreatedDelegate(Events_OnChannelCreated);
oPushService.Events.OnChannelDestroyed += new PushSharp.Common.ChannelEvents.ChannelDestroyedDelegate(Events_OnChannelDestroyed);
oPushService.Events.OnChannelException += new PushSharp.Common.ChannelEvents.ChannelExceptionDelegate(Events_OnChannelException);
oPushService.Events.OnDeviceSubscriptionExpired += new PushSharp.Common.ChannelEvents.DeviceSubscriptionExpired(Events_OnDeviceSubscriptionExpired);
oPushService.Events.OnDeviceSubscriptionIdChanged += new PushSharp.Common.ChannelEvents.DeviceSubscriptionIdChanged(Events_OnDeviceSubscriptionIdChanged);
oPushService.Events.OnNotificationSendFailure += new PushSharp.Common.ChannelEvents.NotificationSendFailureDelegate(Events_OnNotificationSendFailure);
oPushService.Events.OnNotificationSent += new PushSharp.Common.ChannelEvents.NotificationSentDelegate(Events_OnNotificationSent);
byte[] appleCert = File.ReadAllBytes("PushNSCert.p12");
var settings = new ApplePushChannelSettings(true, appleCert, "123456");
oPushService.StartApplePushService(settings);
IsStarted = true;
}
catch (Exception ex)
{
throw new Exception("Exception in starting Apple Service :" + ex.Message + Environment.NewLine + ex.StackTrace);
}
return IsStarted;
}
private bool StartTimer() {
try
{
Double Ms = Convert.ToDouble(ConfigurationManager.AppSettings["TickInterval"]);
NotificationServiceEventLog.WriteEntry("Time Interval" + Ms.ToString());
MyTimer = new Timer();
MyTimer.Interval += (1)*(60)*(1000);
MyTimer.Enabled = true;
MyTimer.Elapsed += new ElapsedEventHandler(ServiceTimer_Tick);
}
catch (Exception ex) {
throw ex;
}
return true;
}
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
string SentNotificationIDz = "";
try
{
MyTimer.Enabled = false;
string szConnectionString = #"Server=.\SQL2K8;Database=PaychecksDB_Live;User Id=sa;Password=tdsadmin#321";
//ConfigurationManager.AppSettings["connString"];
lNotifictaion = oNotificationComponent.GetNotificationsList(szConnectionString);
foreach (NotificationModel oNotificationModel in lNotifictaion)
{
SendNotification(oNotificationModel.DeviceToken, oNotificationModel.NotificationMessage + " (" + oNotificationModel.NotificationTitle + ")");
if (SentNotificationIDz == null)
SentNotificationIDz += oNotificationModel.Oid;
else
SentNotificationIDz += "," + oNotificationModel.Oid;
}
oNotificationComponent.DeleteSentNotifications(SentNotificationIDz, szConnectionString);
MyTimer.Enabled = true;
}
catch (Exception ex) {
throw ex;
}
//
}
private void SendNotification(string p_szDeviceToken,string p_szAlert)
{
try
{
oPushService.QueueNotification(NotificationFactory.Apple()
.ForDeviceToken(p_szDeviceToken)
.WithAlert(p_szAlert)
.WithBadge(2)
.WithSound("default")
.WithExpiry(DateTime.Now.AddDays(1))
);
}
catch (Exception ex)
{
throw new Exception("Error in sending Push Notification:" + ex.Message + Environment.NewLine + ex.StackTrace);
}
}

How to connect to bluetoothbee device using j2me?

I developed a simple bluetooth connection application in j2me.
I try it on emulator, both server and client can found each other, but when I deploy the application to blackberry mobile phone and connect to a bluetoothbee device it says service search no records.
What could it be possibly wrong? is it j2me can not find a service in bluetoothbee?
The j2me itself succeed to found the bluetoothbee device, but why it can not find the service?
My code is below. What I don't understand is the UUID? how to set UUID for unknown source? since I didn't know the UUID for the bluetoothbee device.
class SearchingDevice extends Canvas implements Runnable,CommandListener,DiscoveryListener{
//......
public SearchingDevice(MenuUtama midlet, Display display){
this.display = display;
this.midlet = midlet;
t = new Thread(this);
t.start();
timer = new Timer();
task = new TestTimerTask();
/*--------------------Device List------------------------------*/
select = new Command("Pilih",Command.OK,0);
back = new Command("Kembali",Command.BACK,0);
btDevice = new List("Pilih Device",Choice.IMPLICIT);
btDevice.addCommand(select);
btDevice.addCommand(back);
btDevice.setCommandListener(this);
/*------------------Input Form---------------------------------*/
formInput = new Form("Form Input");
nama = new TextField("Nama","",50,TextField.ANY);
umur = new TextField("Umur","",50,TextField.ANY);
measure = new Command("Ukur",Command.SCREEN,0);
gender = new ChoiceGroup("Jenis Kelamin",Choice.EXCLUSIVE);
formInput.addCommand(back);
formInput.addCommand(measure);
gender.append("Pria", null);
gender.append("Wanita", null);
formInput.append(nama);
formInput.append(umur);
formInput.append(gender);
formInput.setCommandListener(this);
/*---------------------------------------------------------------*/
findDevice();
}
/*----------------Gambar screen searching device---------------------------------*/
protected void paint(Graphics g) {
g.setColor(0,0,0);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(255,255,255);
g.drawString("Mencari Device", 20, 20, Graphics.TOP|Graphics.LEFT);
if(this.counter == 1){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
}
if(this.counter == 2){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
}
if(this.counter == 3){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
g.setColor(255,115,200);
g.fillRect(100, 60, 20, 60);
}
if(this.counter == 4){
g.setColor(255,115,200);
g.fillRect(20, 100, 20, 20);
g.setColor(100,255,255);
g.fillRect(60, 80, 20, 40);
g.setColor(255,115,200);
g.fillRect(100, 60, 20, 60);
g.setColor(100,255,255);
g.fillRect(140, 40, 20, 80);
//display.callSerially(this);
}
}
/*--------- Running Searching Screen ----------------------------------------------*/
public void run() {
while(run){
this.counter++;
if(counter > 4){
this.counter = 1;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("interrupt"+ex.getMessage());
}
repaint();
}
}
/*-----------------------------cari device bluetooth yang -------------------*/
public void findDevice(){
try {
devices = new java.util.Vector();
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
local.setDiscoverable(DiscoveryAgent.GIAC);
agent.startInquiry(DiscoveryAgent.GIAC, this);
} catch (BluetoothStateException ex) {
System.out.println("find device"+ex.getMessage());
}
}
/*-----------------------------jika device ditemukan--------------------------*/
public void deviceDiscovered(RemoteDevice rd, DeviceClass dc) {
devices.addElement(rd);
}
/*--------------Selesai tes koneksi ke bluetooth server--------------------------*/
public void inquiryCompleted(int param) {
switch(param){
case DiscoveryListener.INQUIRY_COMPLETED: //inquiry completed normally
if(devices.size()>0){ //at least one device has been found
services = new java.util.Vector();
this.findServices((RemoteDevice)devices.elementAt(0));
this.run = false;
do_alert("Inquiry completed",4000);
}else{
do_alert("No device found in range",4000);
}
break;
case DiscoveryListener.INQUIRY_ERROR:
do_alert("Inquiry error",4000);
break;
case DiscoveryListener.INQUIRY_TERMINATED:
do_alert("Inquiry canceled",4000);
break;
}
}
/*-------------------------------Cari service bluetooth server----------------------------*/
public void findServices(RemoteDevice device){
try {
// int[] attributes = {0x100,0x101,0x102};
UUID[] uuids = new UUID[1];
//alamat server
uuids[0] = new UUID("F0E0D0C0B0A000908070605040302010",false);
//uuids[0] = new UUID("8841",true);
//menyiapkan device lokal
local = LocalDevice.getLocalDevice();
agent = local.getDiscoveryAgent();
//mencari service dari server
agent.searchServices(null, uuids, device, this);
//server = (StreamConnectionNotifies)Connector.open(url.toString());
} catch (BluetoothStateException ex) {
// ex.printStackTrace();
System.out.println("Errorx"+ex.getMessage());
}
}
/*---------------------------Pencarian service selesai------------------------*/
public void serviceSearchCompleted(int transID, int respCode) {
switch(respCode){
case DiscoveryListener.SERVICE_SEARCH_COMPLETED:
if(currentDevice == devices.size() - 1){
if(services.size() > 0){
this.run = false;
display.setCurrent(btDevice);
do_alert("Service found",4000);
}else{
do_alert("The service was not found",4000);
}
}else{
currentDevice++;
this.findServices((RemoteDevice)devices.elementAt(currentDevice));
}
break;
case DiscoveryListener.SERVICE_SEARCH_DEVICE_NOT_REACHABLE:
do_alert("Device not Reachable",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_ERROR:
do_alert("Service search error",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_NO_RECORDS:
do_alert("No records return",4000);
break;
case DiscoveryListener.SERVICE_SEARCH_TERMINATED:
do_alert("Inquiry canceled",4000);
break;
} }
public void servicesDiscovered(int i, ServiceRecord[] srs) {
for(int x=0; x<srs.length;x++)
services.addElement(srs[x]);
try {
btDevice.append(((RemoteDevice)devices.elementAt(currentDevice)).getFriendlyName(false),null);
} catch (IOException ex) {
System.out.println("service discover"+ex.getMessage());
}
}
public void do_alert(String msg, int time_out){
if(display.getCurrent() instanceof Alert){
((Alert)display.getCurrent()).setString(msg);
((Alert)display.getCurrent()).setTimeout(time_out);
}else{
Alert alert = new Alert("Bluetooth");
alert.setString(msg);
alert.setTimeout(time_out);
display.setCurrent(alert);
}
}
private String getData(){
System.out.println("getData");
String cmd="";
try {
ServiceRecord service = (ServiceRecord)services.elementAt(btDevice.getSelectedIndex());
String url = service.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false);
conn = (StreamConnection)Connector.open(url);
DataInputStream in = conn.openDataInputStream();
int i=0;
timer.schedule(task, 15000);
char c1;
while(time){
//while(((c1 = in.readChar())>0) && (c1 != '\n')){
//while(((c1 = in.readChar())>0) ){
c1 = in.readChar();
cmd = cmd + c1;
//System.out.println(c1);
// }
}
System.out.print("cmd"+cmd);
if(time == false){
in.close();
conn.close();
}
} catch (IOException ex) {
System.err.println("Cant read data"+ex);
}
return cmd;
}
//timer task fungsinya ketika telah mencapai waktu yg dijadwalkan putus koneksi
private static class TestTimerTask extends TimerTask{
public TestTimerTask() {
}
public void run() {
time = false;
}
}
}

How to sort search dictionary result based on frequency in j2me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

not able to receive sms, Help me correct the code

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();
}
}
}

Resources