In my application, I want to record the call upto 10 mins. Is there any way to implement this?
Any help is much appreciated.
I think it works:
Call Recorder for Blackberry
public final class MyScreen extends MainScreen {
/**
* Creates a new MyScreen objects
*
*/
Player player;
RecordControl recorder;
private ByteArrayOutputStream output;
byte[] data;
boolean yes = false;
int st;
public MyScreen() {
// Set the displayed title of the screen
setTitle("Call Recorder");
Phone.addPhoneListener(new PhoneListener() {
public void conferenceCallDisconnected(int callId) {
// TODO Auto-generated method stub
}
public void callWaiting(int callid) {
// TODO Auto-generated method stub
}
public void callResumed(int callId) {
// TODO Auto-generated method stub
}
public void callRemoved(int callId) {
// TODO Auto-generated method stub
}
public void callInitiated(int callid) {
PhoneCall phoneCall = Phone.getCall(callid);
if (phoneCall != null) {
st = Dialog.ask(Dialog.D_YES_NO,
"Are u sure to record this call");
if (st == Dialog.YES)
yes = true;
else
yes = false;
// TODO Auto-generated method stub
}
}
public void callIncoming(int callId) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
Dialog.ask(Dialog.D_YES_NO, "Are u sure to record this call");
// TODO Auto-generated method stub
}
public void callHeld(int callId) {
// TODO Auto-generated method stub
}
public void callFailed(int callId, int reason) {
// TODO Auto-generated method stub
}
public void callEndedByUser(int callId) {
// TODO Auto-generated method stub
}
public void callDisconnected(int callId) {
// TODO Auto-generated method stub
if (yes) {
try {
recorder.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.close();
data = output.toByteArray();
saveRecordedFile(data);
}
}
public void callDirectConnectDisconnected(int callId) {
// TODO Auto-generated method stub
}
public void callDirectConnectConnected(int callId) {
// TODO Auto-generated method stub
}
public void callConnected(int callId) {
// TODO Auto-generated method s
PhoneCall phoneCall = Phone.getCall(callId);
if (phoneCall != null) {
if (yes)
initPlay();
}
}
public void callConferenceCallEstablished(int callId) {
// TODO Auto-generated method stub
}
public void callAnswered(int callId) {
// TODO Auto-generated method stub
// yes = true;
// TODO Auto-generated method stub
}
public void callAdded(int callId) {
// TODO Auto-generated method stub
}
});
}
// private void initMenuItem() {
// final String[] path = new String[1];
// ApplicationDescriptor appDesc = ApplicationDescriptor
// .currentApplicationDescriptor();
//
// final ApplicationDescriptor newDesc = new ApplicationDescriptor(
// appDesc, path);
//
// ApplicationMenuItemRepository amir = ApplicationMenuItemRepository
// .getInstance();
// ApplicationMenuItem a = new ApplicationMenuItem(1) {
// public Object run(final Object context) {
// Application.getApplication().invokeLater(new Runnable() {
//
// public void run() {
//
// }
// });
//
// return context;
// }
//
// public String toString() {
// return "Record Call";
// }
//
// };
// amir.addMenuItem(ApplicationMenuItemRepository.MENUITEM_PHONE, a,
// newDesc);
//
// }
private void initPlay() {
// TODO Auto-generated method stub
try {
player = Manager.createPlayer("capture://audio");
player.realize();
recorder = (RecordControl) player.getControl("RecordControl");
output = new ByteArrayOutputStream();
recorder.setRecordStream(output);
recorder.startRecord();
player.start();
} catch (Exception e) {
// TODO: handle exception
Dialog.alert(e + "");
}
}
public static boolean saveRecordedFile(byte[] data) {
try {
String filePath1 = System.getProperty("fileconn.dir.music");
String fileName = "Call Recorder(";
boolean existed = true;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
FileConnection fc = (FileConnection) Connector
.open(filePath1 + fileName + i + ").amr");
if (!fc.exists()) {
existed = false;
}
fc.close();
} catch (IOException e) {
Dialog.alert("unable to save");
return existed;
}
if (!existed) {
fileName += i + ").amr";
filePath1 += fileName;
break;
}
}
System.out.println(filePath1);
// output---file:///store/home/user/pictures/Photo Editor(10).bmp
System.out.println("");
FileConnection fconn = (FileConnection) javax.microedition.io.Connector
.open(filePath1, javax.microedition.io.Connector.READ_WRITE);
if (fconn.exists())
fconn.delete();
fconn.create();
OutputStream outputStream = fconn.openOutputStream();
outputStream.write(data);
outputStream.close();
fconn.close();
return true;
} catch (Exception e) {
}
return false;
}
}
Yes, you need to register PhoneListener with your application and need to implement required methods like:
callInitiated()
callEnded() etc..etc
i.e. whenever particular call gets initiated you can listen that event and execute custom code.
You can use the PhoneCall class to read the call information.
Hope this helps.
Related
I am trying to take screen shot on test failure but it is giving null pointer exception ,Please check my entire code and help.
I am using one main Class where screen shot method is there, one listener class and and testng.XML file to run listener.
Please some help me with this.
package framework;
public class SafeLaunch extends ExtentReportCreation {
public static AndroidDriver<AndroidElement> driver;
public static AppiumDriverLocalService service;
public AppiumDriverLocalService startServer() {
boolean flag = checkIfServerIsRunning(4723);
if (!flag) {
service = AppiumDriverLocalService.buildDefaultService();
service.start();
}
return service;
}
public AndroidDriver<AndroidElement> capabilities() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
// File appDir = new File("src");
// File app = new File(appDir, "app-staging-debug.apk");
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "4200f532f00d4400");
// capabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
capabilities.setCapability("appPackage", "versionx.safeChild");
capabilities.setCapability("appActivity", "versionx.safeChild.SplashScreenActivity");
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiAutomator2");
capabilities.setCapability("newCommandTimeout", 100000);
capabilities.setCapability("--session-override", true);
capabilities.setCapability(MobileCapabilityType.NO_RESET, true);
driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
public static void getScreenshot(String s) throws IOException {
File srcfile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//FileUtils.copyFile(srcfile, new File("C:\\Users\\Developer\\eclipse-workspace\\SafeChildAutomate\\screenshots\\" + s + ".png"));
FileHandler.copy(srcfile,new File("C:\\Users\\Developer\\eclipse-workspace\\SafeChildAutomate\\screenshots\\" + s + ".png"));
}
public static boolean checkIfServerIsRunning(int port) {
boolean IsServerRunning = false;
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(port);
serverSocket.close();
} catch (IOException e) {
IsServerRunning = true;
} finally {
`serverSocket` = null;
}
return IsServerRunning;
}
}
Below is Listener Class:-
package resources;
i
mport java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import framework.SafeLaunch;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class Listeners implements ITestListener {
public void onTestStart(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestSuccess(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestFailure(ITestResult result) {
String s = result.getName();
try {
SafeLaunch.getScreenshot(s);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void onTestSkipped(ITestResult result) {
// TODO Auto-generated method stub
}
public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
// TODO Auto-generated method stub
}
public void onStart(ITestContext context) {
// TODO Auto-generated method stub
}
public void onFinish(ITestContext context) {
// TODO Auto-generated method stub
}
}
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);
}
}
Hi i made one small application to show all sdcard images should display in my application as Thumbnail view .my program is like following
Here problem is that in simulator it loads fast and accurate where as phone it take lots of time. it is loaded some of 30MB around not getting problem. whare it is 80MB around it is not showing images on my screen.
Note: This is perfectly working in simulator but Not device
and my images path is "file:///SDCard/images/"
My code is:
this is my application starter class
public class StartUp extends UiApplication{
public static void main(String[] args) {
StartUp start=new StartUp();
start.enterEventDispatcher();
}
public StartUp() {
pushScreen(new ViewerMainScreen());
}
}
this is my ViewerMainScreen.java
public class ViewerMainScreen extends MainScreen implements FieldChangeListener{
private ObjectListField fileList;
private String currentPath = "file:///";
public VerticalFieldManager vert_manager=null;
private BitmapField before[]=null,next[]=null;
private int size=0;Border b1,b2;
TableLayoutManager colFMgr=null;
private Vector img_data=null;
private int count=0;
public ViewerMainScreen() {
super();
setTitle("Browse to image...");
initGUI();
}
public void initGUI() {
try {
// add(getFileList());
img_data=getAllList("file:///SDCard/images");
b1=BorderFactory.createSimpleBorder(new XYEdges(3,3,3,3),new XYEdges(Color.RED, Color.RED, Color.RED, Color.RED),Border.STYLE_SOLID);
b2=BorderFactory.createSimpleBorder(new XYEdges(0,0,0,0));
size=img_data.size();
before=new BitmapField[size];
next=new BitmapField[size];
vert_manager=new VerticalFieldManager(VERTICAL_SCROLL|VERTICAL_SCROLLBAR){
protected void sublayout(int maxWidth, int maxHeight) {
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(),Display.getHeight());
}
};
colFMgr = new TableLayoutManager(new int[] {
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
TableLayoutManager.USE_PREFERRED_SIZE,
}, Manager.HORIZONTAL_SCROLL|VERTICAL_SCROLL|VERTICAL_SCROLLBAR);
for(int i= 0;i < size;i++)
{
EncodedImage load_img=EncodedImage.getEncodedImageResource("loading.jpg");
before[i] = new BitmapField(load_img.getBitmap(),Field.FOCUSABLE){
protected boolean navigationClick(int status,int time) {
fieldChangeNotify(0);
return super.navigationClick(status, time);
}
protected void onFocus(int direction)
{
this.setBorder(b1);
invalidate();
}
protected void onUnfocus()
{
this.setBorder(b2);
invalidate();
}
};
colFMgr.add(before[i]);
}
add(colFMgr);
Thread t=new Thread(){
public void run() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
callImageThread();
}
};
t.start();
} catch (Exception e) {
Dialog.alert(e.getMessage());
}
}
private void callImageThread() {
for(int i=0;i<size;i++)
{
if(count==6){
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ImageThread th=new ImageThread(this, "file:///SDCard/images/"+img_data.elementAt(i), i);
th.start();
count++;
}
}
public void ReplaceImage(EncodedImage img,int index)
{
before[index].setBitmap(img.getBitmap());
before[index].setChangeListener(this);
count--;
System.out.println("Thread count: ========================"+Thread.activeCount()+"============================================="+count);
}
public void fieldChanged(Field field, int context) {
for(int i=0;i<size;i++)
{
if(field==before[i])
{
synchronized (UiApplication.getEventLock()) {
EncodedImage img=null;
img=loadFile("file:///SDCard/images/"+img_data.elementAt(i));
int displayWidth = Fixed32.toFP(Display.getWidth()-100);
int imageWidth = Fixed32.toFP(img.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(Display.getHeight()-100);
int imageHeight = Fixed32.toFP(img.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
EncodedImage scaledImage = img.scaleImage32(scalingFactorX, scalingFactorY);
UiApplication.getUiApplication().pushScreen(new ZoomScreen(scaledImage));
}
}
}
}
public void displayMessage(final String message)
{
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
Dialog.inform(message);
}
});
}
private Vector getAllList(String path){
Vector data=new Vector();
FileConnection fileConnection=null;
try{
fileConnection = (FileConnection) Connector.open(path);
if (fileConnection.isDirectory()) {
Enumeration directoryEnumerator = fileConnection.list();
while (directoryEnumerator.hasMoreElements()) {
data.addElement(directoryEnumerator.nextElement());
}
}
}catch (Exception e) {
System.out.println(e.getMessage());
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return data;
}
private EncodedImage loadFile(String path) {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
return encodedImage;
}
}
This is my ImageThread.java
public class ImageThread extends Thread{
private ViewerMainScreen screen;
private String path;
private int index;
private EncodedImage scaledImage=null;
public ImageThread(ViewerMainScreen screen,String path,int index) {
this.screen=screen;
this.path=path;
this.index=index;
}
public void callMainScreen(EncodedImage eimg,int Rindex) {
screen.ReplaceImage(eimg, Rindex);
}
public void run() {
FileConnection fileConnection =null;
InputStream inputStream =null;
EncodedImage encodedImage=null;
try {
fileConnection = (FileConnection) Connector.open(path);
if(fileConnection.exists()){
inputStream = fileConnection.openInputStream();
byte[] imageBytes = new byte[(int)fileConnection.fileSize()];
inputStream.read(imageBytes);
encodedImage = EncodedImage.createEncodedImage(imageBytes, 0, imageBytes.length);
int displayWidth = Fixed32.toFP(100);
int imageWidth = Fixed32.toFP(encodedImage.getWidth());
int scalingFactorX = Fixed32.div(imageWidth, displayWidth);
int displayHeight = Fixed32.toFP(100);
int imageHeight = Fixed32.toFP(encodedImage.getHeight());
int scalingFactorY = Fixed32.div(imageHeight, displayHeight);
scaledImage = encodedImage.scaleImage32(scalingFactorX, scalingFactorY);
callMainScreen(scaledImage, index);
}
} catch (IOException e) {
Dialog.alert("Insert an SD Card.");
}
finally
{
if(fileConnection!=null){
try {
fileConnection.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
please help me how to increase performance of my code
I would load images only when user scrolls screen. For example load first two screens on screen start (in different thread) and load next when user is moving down. So set ScrollListener to your manager and use field postion and height to determine which is on the screen and which is going to be on screen soon.
Also use limited size thread pool and queue for images loading. Unfortunately java concurrent is not par of j2me. But there are several similar pattern implementations, like ThreadPool.
And It would be super if you also remember case when user scrolls fast - cancel scheduled loading if it's not required. For every loading task remember BitmapField position and size. Before task starts file loading check if BitmapField is visible (going to be visible) with current scroll position.
Also be aware about threads count. I see that you try to sleep main loading thread when count is 6. But there is still small possibility that 400 ms is not enough to finish work for current threads and you can easily start to create more threads.
Also minor things - use Bitmap.scaleInto (If you target is 5.0+), use synchronization around size field, next is never used, use a little better names like nextImages, threadsCount, etc.
I want to create an call recorder application in blackberry. While searching in this forum i have got call-recorder-in-blackberry this link. The code given in the below link is fairly understood.
It might be a silly question to you experts but my question is how to us that piece of code. I mean the MyScreen object will work on UIApplication. But how can i make my module start while starting the device, and run in background waiting for the phone call listener to invoke.
I have used this below code, it records the call but only if the call is on loud speaker mode. Now how can i do the same without putting in loud speaker mode.
import java.io.ByteArrayOutputStream;
import java.io.IOException;
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.RecordControl;
import net.rim.blackberry.api.phone.Phone;
import net.rim.blackberry.api.phone.PhoneCall;
import net.rim.blackberry.api.phone.PhoneListener;
import net.rim.device.api.system.Application;
import net.rim.device.api.ui.component.Dialog;
public class CatchCall extends Application implements PhoneListener {
Player player;
RecordControl recorder;
private ByteArrayOutputStream output;
byte[] data;
boolean yes = false;
int st;
public CatchCall() {
Phone.addPhoneListener(this);
}
public static void main(String[] args) {
new CatchCall().enterEventDispatcher();
}
public void callAdded(int callId) {
}
public void callAnswered(int callId) {
}
public void callConferenceCallEstablished(int callId) {
}
public void callConnected(int callId) {
// TODO Auto-generated method s
PhoneCall phoneCall = Phone.getCall(callId);
if (phoneCall != null) {
if (yes)
initPlay();
}
}
public void callDirectConnectConnected(int callId) {
}
public void callDirectConnectDisconnected(int callId) {
}
public void callDisconnected(int callId) {
// TODO Auto-generated method stub
if (yes) {
try {
recorder.commit();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.close();
data = output.toByteArray();
saveRecordedFile(data);
}
}
public void callEndedByUser(int callId) {
}
public void callFailed(int callId, int reason) {
}
public void callHeld(int callId) {
}
public void callIncoming(int callId) {
Dialog.ask(Dialog.D_YES_NO, "Are u sure to record this call");
}
public void callInitiated(int callid) {
PhoneCall phoneCall = Phone.getCall(callid);
if (phoneCall != null) {
st = Dialog.ask(Dialog.D_YES_NO, "Are u sure to record this call");
if (st == Dialog.YES)
yes = true;
else
yes = false;
}
}
public void callRemoved(int callId) {
}
public void callResumed(int callId) {
}
public void callWaiting(int callid) {
}
public void conferenceCallDisconnected(int callId) {
}
private void initPlay() {
try {
player = Manager.createPlayer("capture://audio");
player.realize();
recorder = (RecordControl) player.getControl("RecordControl");
output = new ByteArrayOutputStream();
recorder.setRecordStream(output);
recorder.startRecord();
player.start();
} catch (Exception e) {
Dialog.alert(e + "");
}
}
public static boolean saveRecordedFile(byte[] data) {
try {
String filePath1 = System.getProperty("fileconn.dir.music");
String fileName = "Call Recorder(";
boolean existed = true;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
try {
FileConnection fc = (FileConnection) Connector.open(filePath1 + fileName + i + ").amr");
if (!fc.exists()) {
existed = false;
}
fc.close();
} catch (IOException e) {
Dialog.alert("unable to save");
return existed;
}
if (!existed) {
fileName += i + ").amr";
filePath1 += fileName;
break;
}
}
System.out.println(filePath1);
System.out.println("");
FileConnection fconn = (FileConnection) javax.microedition.io.Connector .open(filePath1, javax.microedition.io.Connector.READ_WRITE);
if (fconn.exists())
fconn.delete();
fconn.create();
OutputStream outputStream = fconn.openOutputStream();
outputStream.write(data);
outputStream.close();
fconn.close();
return true;
} catch (Exception e) {
}
return false;
}
}
Actually direct call recording not possible with blackberry. AFAIK that posted code is call recording when call on speakerphone. That means If mobile have the loud speaker, then put a call to loud speaker and record that voice. And look at this discussion, Call recorder in Blackberry.
It's not possible to record the audio of a phone call (other than with a loud speakerphone) as you are trying to do. This is intentional. You would need another approach off the device to do this. However, I can answer your other questions:
To make your application autostart, you can follow these steps: http://supportforums.blackberry.com/t5/Java-Development/Configure-an-application-to-start-automatically-when-the/ta-p/444748
Also, as this application above doesn't extend from UiApplication, you should check the "run as a system module" box as well, when you follow the directions above. That way it won't appear on the ribbon or as an icon in the list of applications.
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.