New to Nokia development. I am trying to write a hello world for get GPS coordinates of my current location. What am I doing wrong here ?
public class HomeScreen extends MIDlet {
public HomeScreen() {
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
Displayable current = Display.getDisplay(this).getCurrent() ;
if (current == null) {
UpdateJourney updateJourney = new UpdateJourney(this) ;
Display.getDisplay(this).setCurrent(updateJourney) ;
}
}
}
public class UpdateJourney extends Form implements CommandListener, Runnable {
private LocationProvider myLocation;
private Criteria myCriteria;
private Location myCurrentLocation;
private HomeScreen helloScreen;
private Command exitCommand;
private Thread getLocationThread = new Thread(this);;
public UpdateJourney(HomeScreen helloScreen) {
super("Taxeeta");
StringItem helloText = new StringItem("", "Taxeeta");
super.append(helloText);
this.helloScreen = helloScreen;
getLocationThread.start();
}
public double getMyLatitude() {
return myCurrentLocation.getQualifiedCoordinates().getLatitude();
}
public double getMyLongitude() {
return myCurrentLocation.getQualifiedCoordinates().getLongitude();
}
public void commandAction(Command command, Displayable arg1) {
if (command == exitCommand) {
helloScreen.notifyDestroyed();
}
}
public void run() {
myCriteria = new Criteria();
myCriteria.setHorizontalAccuracy(500);
try {
myLocation = LocationProvider.getInstance(myCriteria);
myCurrentLocation = myLocation.getLocation(60);
} catch (LocationException e) {
e.printStackTrace();
System.out
.println("Error : Unable to initialize location provider");
return;
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("Error: Waited enough for location to return");
return;
}
System.out.println("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude());
exitCommand = new Command("Location returned Lat:"
+ myCurrentLocation.getQualifiedCoordinates().getLatitude()
+ " Lng:"
+ myCurrentLocation.getQualifiedCoordinates().getLongitude(),
Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
}
}
In the application descriptor I had UpdateJourney as the MIDlet, I changed it to HomeScreen and it worked.
Related
i am tried to stream video from uvc camera with agora video call api. but it doesn't work . but the uvc camera preview show proferly on '''''' .
public class VideoChatViewActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback{
private static final String TAG = VideoChatViewActivity.class.getSimpleName();
private static final int PERMISSION_REQ_ID = 22;
// Permission WRITE_EXTERNAL_STORAGE is not mandatory
// for Agora RTC SDK, just in case if you wanna save
// logs to external sdcard.
private static final String[] REQUESTED_PERMISSIONS = {
Manifest.permission.RECORD_AUDIO,
Manifest.permission.CAMERA
};
private RtcEngine mRtcEngine;
private boolean mCallEnd;
private boolean mMuted;
private FrameLayout mLocalContainer;
private RelativeLayout mRemoteContainer;
private VideoCanvas mLocalVideo;
private VideoCanvas mRemoteVideo;
private ImageView mCallBtn;
private ImageView mMuteBtn;
private ImageView mSwitchCameraBtn;
// Customized logger view
private LoggerRecyclerView mLogView;
private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("Join channel success, uid: " + (uid & 0xFFFFFFFFL));
}
});
}
#Override
public void onUserJoined(final int uid, int elapsed) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("First remote video decoded, uid: " + (uid & 0xFFFFFFFFL));
setupRemoteVideo(uid);
}
});
}
#Override
public void onUserOffline(final int uid, int reason) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLogView.logI("User offline, uid: " + (uid & 0xFFFFFFFFL));
onRemoteUserLeft(uid);
}
});
}
};
private void setupRemoteVideo(int uid) {
ViewGroup parent = mRemoteContainer;
if (parent.indexOfChild(mLocalVideo.view) > -1) {
parent = mLocalContainer;
}
if (mRemoteVideo != null) {
return;
}
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(parent == mLocalContainer);
parent.addView(view);
mRemoteVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, uid);
// Initializes the video view of a remote user.
mRtcEngine.setupRemoteVideo(mRemoteVideo);
}
private void onRemoteUserLeft(int uid) {
if (mRemoteVideo != null && mRemoteVideo.uid == uid) {
removeFromParent(mRemoteVideo);
// Destroys remote view
mRemoteVideo = null;
}
}
//usb
private static final int DEFAULT_CAPTURE_WIDTH = 1280;
private static final int DEFAULT_CAPTURE_HEIGHT = 720;
#BindView(R.id.camer_view)
public View mTextureView;
private static final String TAG1 = "Debug";
private UVCCameraHelper mCameraHelper;
private CameraViewInterface mUVCCameraView;
private AlertDialog mDialog;
private boolean isRequest;
private boolean isPreview;
private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
#Override
public void onAttachDev(UsbDevice device) {
// request open permission
if (!isRequest) {
isRequest = true;
if (mCameraHelper != null) {
mCameraHelper.requestPermission(0);
}
}
}
#Override
public void onDettachDev(UsbDevice device) {
// close camera
if (isRequest) {
isRequest = false;
mCameraHelper.closeCamera();
showShortMsg(device.getDeviceName() + " is out");
}
}
#Override
public void onConnectDev(UsbDevice device, boolean isConnected) {
if (!isConnected) {
showShortMsg("fail to connect,please check resolution params");
isPreview = false;
} else {
isPreview = true;
showShortMsg("connecting");
// initialize seekbar
// need to wait UVCCamera initialize over
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2500);
} catch (InterruptedException e) {
e.printStackTrace();
}
Looper.prepare();
if(mCameraHelper != null && mCameraHelper.isCameraOpened()) {
}
Looper.loop();
}
}).start();
}
}
#Override
public void onDisConnectDev(UsbDevice device) {
showShortMsg("disconnecting");
}
};
//usb
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
ButterKnife.bind(this);//uvc
initUI();
mUVCCameraView = (CameraViewInterface) mTextureView;
mUVCCameraView.setCallback(this);
//mLocalContainer.setCallback(this);
mCameraHelper = UVCCameraHelper.getInstance();
mCameraHelper.setDefaultPreviewSize(1280,720);
mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);
mCameraHelper.setOnPreviewFrameListener(new AbstractUVCCameraHandler.OnPreViewResultListener() {
#Override
public void onPreviewResult(byte[] bytes) {
try {
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = bytes;
frame.format = AgoraVideoFrame.FORMAT_NV21;
frame.stride = DEFAULT_CAPTURE_WIDTH;
frame.height = DEFAULT_CAPTURE_HEIGHT;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}catch (Exception e){
e.printStackTrace();
}
}
});
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
}
private void initUI() {
mLocalContainer = findViewById(R.id.local_video_view_container);
mRemoteContainer = findViewById(R.id.remote_video_view_container);
mCallBtn = findViewById(R.id.btn_call);
mMuteBtn = findViewById(R.id.btn_mute);
mSwitchCameraBtn = findViewById(R.id.btn_switch_camera);
mLogView = findViewById(R.id.log_recycler_view);
// Sample logs are optional.
showSampleLogs();
}
private void showSampleLogs() {
mLogView.logI("Welcome to Agora 1v1 video call");
mLogView.logW("You will see custom logs here");
mLogView.logE("You can also use this to show errors");
}
private boolean checkSelfPermission(String permission, int requestCode) {
if (ContextCompat.checkSelfPermission(this, permission) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQ_ID) {
if (grantResults[0] != PackageManager.PERMISSION_GRANTED ||
grantResults[1] != PackageManager.PERMISSION_GRANTED ||
grantResults[2] != PackageManager.PERMISSION_GRANTED) {
showLongToast("Need permissions " + Manifest.permission.RECORD_AUDIO +
"/" + Manifest.permission.CAMERA);
finish();
return;
}
// Here we continue only if all permissions are granted.
// The permissions can also be granted in the system settings manually.
initEngineAndJoinChannel();
}
}
private void showLongToast(final String msg) {
this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void initEngineAndJoinChannel() {
initializeEngine();
setupVideoConfig();
setupLocalVideo();
joinChannel();
}
private void initializeEngine() {
try {
mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
} catch (Exception e) {
Log.e(TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
}
private void setupVideoConfig() {
mRtcEngine.enableVideo();
mRtcEngine.setVideoEncoderConfiguration(new VideoEncoderConfiguration(
VideoEncoderConfiguration.VD_640x360,
VideoEncoderConfiguration.FRAME_RATE.FRAME_RATE_FPS_15,
VideoEncoderConfiguration.STANDARD_BITRATE,
VideoEncoderConfiguration.ORIENTATION_MODE.ORIENTATION_MODE_FIXED_PORTRAIT));
}
private void setupLocalVideo() {
.
SurfaceView view = RtcEngine.CreateRendererView(getBaseContext());
view.setZOrderMediaOverlay(true);
mLocalContainer.addView(view);
mLocalVideo = new VideoCanvas(view, VideoCanvas.RENDER_MODE_HIDDEN, 0);
mRtcEngine.setupLocalVideo(mLocalVideo);
}
private void joinChannel() {
String token = getString(R.string.agora_access_token);
if (TextUtils.isEmpty(token) || TextUtils.equals(token, "#YOUR ACCESS TOKEN#")) {
token = null; // default, no token
}
mRtcEngine.joinChannel(token, "streaming", "Extra Optional Data", 0);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (!mCallEnd) {
leaveChannel();
}
RtcEngine.destroy();
}
private void leaveChannel() {
mRtcEngine.leaveChannel();
}
public void onLocalAudioMuteClicked(View view) {
mMuted = !mMuted;
mRtcEngine.muteLocalAudioStream(mMuted);
int res = mMuted ? R.drawable.btn_mute : R.drawable.btn_unmute;
mMuteBtn.setImageResource(res);
}
public void onSwitchCameraClicked(View view) {
mRtcEngine.switchCamera();
}
public void onCallClicked(View view) {
if (mCallEnd) {
startCall();
mCallEnd = false;
mCallBtn.setImageResource(R.drawable.btn_endcall);
} else {
endCall();
mCallEnd = true;
mCallBtn.setImageResource(R.drawable.btn_startcall);
}
showButtons(!mCallEnd);
}
private void startCall() {
setupLocalVideo();
joinChannel();
}
private void endCall() {
removeFromParent(mLocalVideo);
mLocalVideo = null;
removeFromParent(mRemoteVideo);
mRemoteVideo = null;
leaveChannel();
}
private void showButtons(boolean show) {
int visibility = show ? View.VISIBLE : View. SurfaceView view .GONE;
mMuteBtn.setVisibility(visibility);
mSwitchCameraBtn.setVisibility(visibility);
}
private ViewGroup removeFromParent(VideoCanvas canvas) {
if (canvas != null) {
ViewParent parent = canvas.view.getParent();
if (parent != null) {
ViewGroup group = (ViewGroup) parent;
group.removeView(canvas.view);
return group;
}
}
return null;
}
private void switchView(VideoCanvas canvas) {
ViewGroup parent = removeFromParent(canvas);
if (parent == mLocalContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(false);
}
mRemoteContainer.addView(canvas.view);
} else if (parent == mRemoteContainer) {
if (canvas.view instanceof SurfaceView) {
((SurfaceView) canvas.view).setZOrderMediaOverlay(true);
}
mLocalContainer.addView(canvas.view);
}
}
public void onLocalContainerClick(View view) {
switchView(mLocalVideo);
switchView(mRemoteVideo);
}
///uvc
#Override
protected void onStart() {
super.onStart();
// step.2 register USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.registerUSB();
}
}
#Override
protected void onStop() {
super.onStop();
// step.3 unregister USB event broadcast
if (mCameraHelper != null) {
mCameraHelper.unregisterUSB();
}
}
private void showShortMsg(String msg) {
//
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
public USBMonitor getUSBMonitor(){ return mCameraHelper.getUSBMonitor();
}
#Override
public void onDialogResult(boolean canceled) {
if (canceled) {
showShortMsg("cancel");
}
}
#Override
public void onSurfaceCreated(CameraViewInterface cameraViewInterface, Surface surface) {
if (!isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.startPreview(mUVCCameraView);
isPreview = true;
}
}
#Override
public void onSurfaceChanged(CameraViewInterface cameraViewInterface, Surface surface, int i, int i1) {
}
#Override
public void onSurfaceDestroy(CameraViewInterface cameraViewInterface, Surface surface) {
if (isPreview && mCameraHelper.isCameraOpened()) {
mCameraHelper.stopPreview();
isPreview = false;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat_view);
initUI();
// Ask for permissions at runtime.
// This is just an example set of permissions. Other permissions
// may be needed, and please refer to our online documents.
if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
initEngineAndJoinChannel();
}
//xiaobing add
final View view = findViewById(R.id.camera_view);
mUVCCameraView = (CameraViewInterface)view;
mUSBMonitor = new USBMonitor(this, mOnDeviceConnectListener);
mUVCCameraView.setAspectRatio(previewWidth / (float)previewHeight);
mCameraHandler = UVCCameraHandler.createHandler(this,
mUVCCameraView, previewWidth,
previewHeight, BANDWIDTH_FACTORS[0],
firstDataCallBack);
}
//xiaobing add
private void startPreview() {
final SurfaceTexture st = mUVCCameraView.getSurfaceTexture();
mCameraHandler.startPreview(new Surface(st));
}
//xiaobing add
UvcCameraDataCallBack firstDataCallBack = new UvcCameraDataCallBack() {
#Override
public void getData(byte[] data) {
if (DEBUG) {
Log.v(TAG, "data callback:" + data.length);
}
AgoraVideoFrame frame = new AgoraVideoFrame();
frame.buf = data;
frame.format = AgoraVideoFrame.FORMAT_NV12;
frame.stride = previewWidth;
frame.height = previewHeight;
frame.timeStamp = System.currentTimeMillis();
mRtcEngine.pushExternalVideoFrame(frame);
}
};
//xiaobing add
#Override
protected void onStart() {
super.onStart();
if (DEBUG) Log.v(TAG, "onStart:");
mUSBMonitor.register();
if (mUVCCameraView != null)
mUVCCameraView.onResume();
if (!mCameraHandler.isOpened()) {
UsbManager um = (UsbManager) (getSystemService(Context.USB_SERVICE));
HashMap<String, UsbDevice> map = um.getDeviceList();
ArrayList<String> names = new ArrayList<>();
final ArrayList<UsbDevice> devices = new ArrayList<>();
for(Map.Entry<String, UsbDevice> item : map.entrySet()) {
String name = item.getValue().getProductName();
String vid = Integer.toHexString(item.getValue().getVendorId());
String pid = Integer.toHexString(item.getValue().getProductId());
String all = "" + name + " VID:" + vid
+ " PID:" + pid;
Log.v("xiaobing", "all:" + all);
names.add(all);
devices.add(item.getValue());
if(item.getValue().getProductId()==1383 && (item.getValue().getVendorId() == 3034)){
mDev = item.getValue();
mUSBMonitor.requestPermission(mDev);
//为了同时支持手机和眼镜,只有获得了眼镜的设备才选择本地视频
mRtcEngine.setExternalVideoSource(true, true, true);
mLogView.logI("使用USB摄像头!");
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I managed to establish a bluetooth connection from my main activity but i want to print from another activity.
How can I do this?
Main Activity Where I Start A connection to a bluetooth printer
protected static final String TAG = "TAG";
private static final int REQUEST_ENABLE_BT = 2;
private static final int REQUEST_CONNECT_DEVICE = 1;
private ProgressDialog BluetoothConnectProgressDialog;
Button button_connect_to_bluetooth_printer;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter bluetoothAdapter;
private BluetoothSocket bluetoothSocket;
private BluetoothDevice bluetoothDevice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button_connect_to_bluetooth_printer = findViewById(R.id.btn_connect_bluetooth);
button_connect_to_bluetooth_printer.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this, BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
});
}
private void ListPairedDevices()
{
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : PairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + mDevice.getAddress());
}
}
}
public void onActivityResult(int RequestCode, int ResultCode, Intent DataIntent)
{
super.onActivityResult(RequestCode, ResultCode, DataIntent);
switch (RequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (ResultCode == Activity.RESULT_OK)
{
Bundle mExtra = DataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
bluetoothDevice = bluetoothAdapter
.getRemoteDevice(mDeviceAddress);
BluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", bluetoothDevice.getName() + " : " + bluetoothDevice.getAddress(), true, true);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (ResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
BluetoothDeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.this, "Message", Toast.LENGTH_SHORT).show();
}
break;
}
}
public void run()
{
try
{
bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
bluetoothAdapter.cancelDiscovery();
bluetoothSocket.connect();
handler.sendEmptyMessage(0);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(bluetoothSocket);
return;
}
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg)
{
BluetoothConnectProgressDialog.dismiss();
}
};
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
this is my device list activity
protected static final String TAG = "TAG";
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> paired_devices_list;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_bluetooth_device_list);
setResult(Activity.RESULT_CANCELED);
paired_devices_list = new ArrayAdapter<>(this, R.layout.bluetooth_device_name);
ListView PairedListDevices = findViewById(R.id.paired_devices);
PairedListDevices.setAdapter(paired_devices_list);
PairedListDevices.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
{
try
{
bluetoothAdapter.cancelDiscovery();
String mdeviceInfo = ((TextView) view).getText().toString();
String deviceAddress = mdeviceInfo.substring(mdeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + deviceAddress);
Bundle bundle = new Bundle();
bundle.putString("DeviceAddress", deviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(bundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> PairedDevices = bluetoothAdapter.getBondedDevices();
if (PairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : PairedDevices)
{
paired_devices_list.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String NoDevices = "None Paired";
paired_devices_list.add(NoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (bluetoothAdapter != null)
{
bluetoothAdapter.cancelDiscovery();
}
}
And this my print activity
public void print()
{
Thread t = new Thread()
{
public void run()
{
try
{
OutputStream os = bluetoothSocket.getOutputStream();
String account_no;
account_no_value = ""+ Account_No.getText().toString()+"\n";
os.write(account_no.getBytes());
}
catch (Exception e)
{
Log.e("PrintActivity", "Exe ", e);
}
}
};
t.start();
}
E/PrintActivity: Exe
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream android.bluetooth.BluetoothSocket.getOutputStream()' on a null object reference
at com.vicjames.qiimeterreader.PrintBill$6.run(PrintBill.java:1635)
how can I fix this?? The app is not crashing but it wont print either.
I Would like to execute a background task which executes multiple background tasks. What i am actually trying to do is execute a background process which executes some code for every Object in a list, and does it within a fixed thread pool. So, for example, i have 100 users in the list and i am executing code for each of them concurrently but no more than 5 at the same time.
Therefore i am using two service/task pairs: One service/task for executing on the whole list of users, this service uses a fixed thread pool as its executor and executes a series of second service/task pairs for every user in the list.
like in the following example:
class MainService extends Service<List<User>> {
private List<User> users;
public MainService(List<User> users) { this.users=users; }
protected Task<List<User>> createTask(){
return new MainTask(this.users)
}
}
class Maintask extends Task<List<User>> {
private List<User> users;
private Executor executor;
public MainTask(List<User> users) {
this.users=users;
this.executor=Executors.newFixedThreadPool(5);
}
protected List<User> call() throws Exception {
for (User user : this.users) {
System.out.println("Starting single service");
SingleService service=new SingleService(user)
service.setExecutor(this.executor);
service.start();
System.out.println("Single service started");
}
}
}
class SingleService extends Service<User> {
private User user;
public SingleService(User user) { this.user=user; }
protected Task<User> createTask() {
return new SingleTask(this.user)
}
}
class SingleTask extends Task<User> {
private User user;
public SingleTask(User user) { this.user=user; }
protected User call() throws Exception() {
// Do some work
}
}
The code executes up to the moment when first "starting single service" is printed, the "single service started" message is not being printed at all. As far as i see the SingleService is started, but its createTask() is not being executed at all. Am i making some mistake here?
Well, I am trying to do the same thing, in different context... launch multiple services from a single main Service.
I've overridden all methods of Service, and this is my printout:
Service must only be used from the FX Application Thread {from onFailed() method}
Service does not run on FX thread, but can only be called from the FX thread.
Therefore, all Services and Tasks called within a Service or Task will not be executed.
This is my work around:
public class FXComponentImporter extends Service<Void> implements JarImporter {
//Scanner<T> = Service<List<Class<T>>>
private Scanner<Node> nodeScanner = null;
private Scanner<Paint> paintScanner = null;
private Scanner<Animation> animationScanner = null;
private static int nodeCount = 0, paintCount = 0, animationCount = 0;
private final ObservableMap<String, Class<?>> foundComponents = FXCollections.observableHashMap();
public FXComponentImporter() {
this(null);
}
public FXComponentImporter(File file) {
if (file != null) {
try {
this.nodeScanner = new Scanner<>(file, Node.class);
this.paintScanner = new Scanner<>(file, Paint.class);
this.animationScanner = new Scanner<>(file, Animation.class);
} catch (IOException ex) {
Logger.getLogger(FXComponentImporter.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
File f = importJar();
try {
this.nodeScanner = new Scanner<>(f, Node.class);
this.paintScanner = new Scanner<>(f, Paint.class);
this.animationScanner = new Scanner<>(f, Animation.class);
} catch (IOException ex) {
Logger.getLogger(FXComponentImporter.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.scanningDone.bind(this.nodeScanningDone.and(this.paintScanningDone.and(this.animationScanningDone)));
this.scanningDone.addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
if (newValue) {
if(scanningDone.isBound()){
scanningDone.unbind();
}
start();
scanningDone.removeListener(this);
}
}
});
startScanning();
}
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
Map<String, Class<?>> map = new HashMap<>();
List<Class<Node>> nodes = new ArrayList<>();
List<Class<Paint>> paints = new ArrayList<>();
List<Class<Animation>> anims = new ArrayList<>();
CountDownLatch latch = new CountDownLatch(1);
//Platform needed due to Service only accessed from FX thread
Platform.runLater(() -> {
try {
//FX Stuff done here
nodes.addAll(nodeScanner.getMatchingClasses());
paints.addAll(paintScanner.getMatchingClasses());
anims.addAll(animationScanner.getMatchingClasses());
} finally {
latch.countDown();
}
});
latch.await();
this.updateMessage("Scanning for Nodes ... ");
nodes.stream().forEach(n -> {
if(n != null){
map.putIfAbsent(n.getSimpleName(), n);
}
nodeCount++;
});
this.updateMessage("Found : " + nodeCount + " Nodes ... ");
this.updateMessage("Scanning for Paints ... ");
paints.stream().forEach(p -> {
if(p != null){
map.putIfAbsent(p.getSimpleName(), p);
}
paintCount++;
});
this.updateMessage("Found : " + paintCount + " Paints ... ");
this.updateMessage("Scanning for Animations ... ");
anims.stream().forEach(a -> {
if(a != null){
map.putIfAbsent(a.getSimpleName(), a);
}
animationCount++;
});
this.updateMessage("Found : " + animationCount + " Animations ... ");
foundComponents.putAll(map);
return null;
}
};
}
#Override
protected void executeTask(Task<Void> task) {
super.executeTask(task);
System.out.println(getClass().getSimpleName() + " is Executing " + task.getTitle());
}
#Override
protected void cancelled() {
super.cancelled();
System.out.println(getClass().getSimpleName() + " was Cancelled ... ");
}
#Override
protected void running() {
super.running();
System.out.println(getClass().getSimpleName() + " is Running ... ");
}
#Override
protected void ready() {
super.ready();
System.out.println(getClass().getSimpleName() + " is Ready! ... ");
}
#Override
protected void scheduled() {
super.scheduled();
System.out.println(getClass().getSimpleName() + " is Scheduled ... ");
}
#Override
protected void failed() {
super.failed();
System.out.println(getException().getMessage());
}
#Override
protected void succeeded() {
super.succeeded();
System.out.println("Importing Succeeded ... with: " + foundComponents.entrySet().size() + " results.\n");
foundComponents.forEach((s, c) -> {
System.out.println(c.getSuperclass().getSimpleName() + " >> " + s + " : " + c.getSimpleName());
});
}
#Override
public void restart() {
super.restart();
System.out.println(getClass().getSimpleName() + " is Restarting ... ");
}
private void startScanning() {
nodeScanner.stateProperty().addListener(nsl);
paintScanner.stateProperty().addListener(psl);
animationScanner.stateProperty().addListener(asl);
nodeScanner.start();
paintScanner.start();
animationScanner.start();
}
private final BooleanProperty scanningDone = new SimpleBooleanProperty(false);
private final BooleanProperty nodeScanningDone = new SimpleBooleanProperty(false);
private final BooleanProperty paintScanningDone = new SimpleBooleanProperty(false);
private final BooleanProperty animationScanningDone = new SimpleBooleanProperty(false);
private final ChangeListener nsl = new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue.equals(State.SUCCEEDED)) {
nodeScanningDone.set(true);
nodeScanner.stateProperty().removeListener(this);
}
}
};
private final ChangeListener psl = new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue.equals(State.SUCCEEDED)) {
paintScanningDone.set(true);
paintScanner.stateProperty().removeListener(this);
}
}
};
private final ChangeListener asl = new ChangeListener<Worker.State>() {
#Override
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {
if (newValue.equals(State.SUCCEEDED)) {
animationScanningDone.set(true);
animationScanner.stateProperty().removeListener(this);
}
}
};
public ObservableMap<String, Class<?>> getFoundComponents() {
return foundComponents;
}
}
and my Interface if you wanna try it out:
public interface JarImporter {
public static File defaultDirectory = new File(System.getProperty("user.home"));
public static final FileChooser.ExtensionFilter classfilter = new FileChooser.ExtensionFilter("Jar files", "*.jar");
static FileChooser defaultFileChooser(){
FileChooser fc = new FileChooser();
fc.getExtensionFilters().add(classfilter);
fc.setInitialDirectory(defaultDirectory);
return fc;
}
public default File importJar(){
File jar = defaultFileChooser().showOpenDialog(null);
if(jar != null){
return jar;
}else{
return null;
}
}
}
Hope this helps.. though just looked at Question date, and was a while ago...
How to Implement a MIDlet that gets invoked when a SMS is sent to port 50000?
The code is not working. SMS can't be received on the phone, SMS is sent through the emulator (JAVA Me SDK).
What settings should be done to receive the SMS ?
my code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import javax.microedition.io.PushRegistry;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
/**
* #author bonni
*/
public class Midletsms extends MIDlet implements CommandListener{
protected Display display;
//boolean started=false;
Form form = new Form("Welcome");
Command mCommandQuit;
public void startApp() {
String url = "sms://:50000";
try {
PushRegistry.registerConnection(url,this.getClass().getName(), "*");
// PushRegistry.registerConnection(url,"Midletsms.class", "*");
} catch (IOException ex) {
} catch (ClassNotFoundException ex) {
}
form.append("This midlet gets invoked when message is sent to port:50000");
display = Display.getDisplay(this);
display.setCurrent(form);
mCommandQuit = new Command("Quit", Command.EXIT, 0);
form.addCommand(mCommandQuit);
form.setCommandListener(this);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable d) {
// throw new UnsupportedOperationException("Not supported yet.");
String label = c.getLabel();
if(label.equals("Quit"))
{
destroyApp(false);
notifyDestroyed();
}
}
}
Not sure I fully understand the problem. But you need to read about PushRegistry.
So there are two types of push registration, static and dynamic.
The code example you have given uses dynamic registration. You will need to manually invoke this MIDlet at least once in order for the push registration to happen. (Aside: In your example you are doing this in the startApp method, this is a very bad idea! Push registration is a potentially blocking operation, and therefore should not be done in a lifecycle method such as startApp. You should do this in a new thread).
The alternative is static registration, where you include the push information in the jad. The push port will be registered when the MIDlet is installed, without the need to run it.
Finally, you say
sms is sent through the emulator
what does this mean? In order for the app to start you need to send an SMS on the relevant port number from another MIDlet (this could be on the same handset if you want).
I found this code on net from Jimmy's blog and it is perfectly working. You can try it your self,
SMSSender.java
public class SMSSender extends MIDlet implements CommandListener {
private Form formSender = new Form("SMS Sender");
private TextField tfDestination = new TextField("Destination", "", 20, TextField.PHONENUMBER);
private TextField tfPort = new TextField("Port", "50000", 6, TextField.NUMERIC);
private TextField tfMessage = new TextField("Message", "message", 150, TextField.ANY);
private Command cmdSend = new Command("Send", Command.OK, 1);
private Command cmdExit = new Command("Exit", Command.EXIT, 1);
private Display display;
public SMSSender() {
formSender.append(tfDestination);
formSender.append(tfPort);
formSender.append(tfMessage);
formSender.addCommand(cmdSend);
formSender.addCommand(cmdExit);
formSender.setCommandListener(this);
display = Display.getDisplay(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(formSender);
}
public void commandAction(Command c, Displayable d) {
if (c==cmdSend) {
SendMessage.execute(tfDestination.getString(), tfPort.getString(), tfMessage.getString());
} else if (c==cmdExit) {
notifyDestroyed();
}
}
}
class SendMessage {
public static void execute(final String destination, final String port, final String message) {
Thread thread = new Thread(new Runnable() {
public void run() {
MessageConnection msgConnection;
try {
msgConnection = (MessageConnection)Connector.open("sms://"+destination+":" + port);
TextMessage textMessage = (TextMessage)msgConnection.newMessage(
MessageConnection.TEXT_MESSAGE);
textMessage.setPayloadText(message);
msgConnection.send(textMessage);
msgConnection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
SMSReceiver.java
public class SMSReceiver extends MIDlet implements CommandListener, MessageListener {
private Form formReceiver = new Form("SMS Receiver");
private TextField tfPort = new TextField("Port", "50000", 6, TextField.NUMERIC);
private Command cmdListen = new Command("Listen", Command.OK, 1);
private Command cmdExit = new Command("Exit", Command.EXIT, 1);
private Display display;
public SMSReceiver() {
formReceiver.append(tfPort);
formReceiver.addCommand(cmdListen);
formReceiver.addCommand(cmdExit);
formReceiver.setCommandListener(this);
display = Display.getDisplay(this);
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(formReceiver);
}
public void commandAction(Command c, Displayable d) {
if (c==cmdListen) {
ListenSMS sms = new ListenSMS(tfPort.getString(), this);
sms.start();
formReceiver.removeCommand(cmdListen);
} else if (c==cmdExit) {
notifyDestroyed();
}
}
public void notifyIncomingMessage(MessageConnection conn) {
Message message;
try {
message = conn.receive();
if (message instanceof TextMessage) {
TextMessage tMessage = (TextMessage)message;
formReceiver.append("Message received : "+tMessage.getPayloadText()+"\n");
} else {
formReceiver.append("Unknown Message received\n");
}
} catch (InterruptedIOException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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://:" + port);
msgConnection.setMessageListener(listener);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I've spent long on this but no success yet. In my application to capture image and send to the server, I get NullPointerException below;
java.lang.NullPointerException: 0
at Files.CameraMIDlet.snap(CameraMIDlet.java:120)
at Files.CameraForm.commandAction(CameraForm.java:116)
at javax.microedition.lcdui.Display$ChameleonTunnel.callScreenListener(), bci=46
at com.sun.midp.chameleon.layers.SoftButtonLayer.processCommand(), bci=74
at com.sun.midp.chameleon.layers.SoftButtonLayer.soft2(), bci=173
at com.sun.midp.chameleon.layers.SoftButtonLayer.keyInput(), bci=78
at com.sun.midp.chameleon.CWindow.keyInput(), bci=38
at javax.microedition.lcdui.Display$DisplayEventConsumerImpl.handleKeyEvent(), bci=17
at com.sun.midp.lcdui.DisplayEventListener.process(), bci=277
at com.sun.midp.events.EventQueue.run(), bci=179
at java.lang.Thread.run(Thread.java:722)
The errors happen at byte[] image = videoControl.getSnapshot("encoding = jpeg"); in the CameraMIDlet and also at midlet.snap(); in the CameraForm, in the code below.
The code for CameraForm is here:
package Files;
import javax.microedition.media.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.control.*;
import java.io.IOException;
class CameraForm extends Form implements CommandListener {
private final CameraMIDlet midlet;
private final Command exitCommand;
private Command captureCommand = null;
private Command showImageCommand = null;
private Player player = null;
private static VideoControl videoControl = null;
private boolean active = false;
private StringItem messageItem;
public CameraForm(CameraMIDlet midlet) {
super("Camera");
this.midlet = midlet;
messageItem = new StringItem("Message", "start");
append(messageItem);
exitCommand = new Command("EXIT", Command.EXIT, 1);
addCommand(exitCommand);
setCommandListener(this);
try {
//creates a new player and set it to realize
player = Manager.createPlayer("capture://video");
player.realize();
//Grap the Video control and set it to the current display
videoControl = (VideoControl) (player.getControl("VideoControl"));
if (videoControl != null) {
append((Item) (videoControl.initDisplayMode(
VideoControl.USE_GUI_PRIMITIVE, null)));
captureCommand = new Command("CAPTURE", Command.SCREEN, 1);
addCommand(captureCommand);
messageItem.setText("OK");
} else {
messageItem.setText("No video control");
}
} catch (IOException ioe) {
messageItem.setText("IOException: " + ioe.getMessage());
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
}
* the video should be visualized on the sreen
* therefore you have to start the player and set the videoControl visible
synchronized void start() {
if (!active) {
try {
if (player != null) {
player.start();
}
if (videoControl != null) {
videoControl.setVisible(true);
//midlet.snap();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
} catch (SecurityException se) {
messageItem.setText("Security Exception: " + se.getMessage());
}
active = true;
}
}
* to stop the player. First the videoControl has to be set invisible
* than the player can be stopped
synchronized void stop() {
if (active) {
try {
if (videoControl != null) {
videoControl.setVisible(false);
}
if (player != null) {
player.stop();
}
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
active = false;
}
}
* on the captureCommand a picture is taken and transmited to the server
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
midlet.cameraFormExit();
} else {
if (c == captureCommand) {
midlet.snap();
}
}
}
}
The code for CameraMIDlet is below:
package Files;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;
import javax.microedition.media.control.*;
import java.io.IOException;
import javax.microedition.media.MediaException;
public class CameraMIDlet extends MIDlet {
private CameraForm cameraSave = null;
private DisplayImage displayImage = null;
CameraForm captureThread;
private static VideoControl videoControl;
private StringItem messageItem;
public CameraMIDlet() {
}
/*
* startApp()
* starts the MIDlet and generates cameraSave, displayImage, database
*
**/
public void startApp() {
Displayable current = Display.getDisplay(this).getCurrent();
if (current == null) {
//first call
cameraSave = new CameraForm(this);
displayImage = new DisplayImage(this);
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
} else {
//returning from pauseApp
if (current == cameraSave) {
cameraSave.start();
}
Display.getDisplay(this).setCurrent(current);
}
}
public void pauseApp() {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
public void destroyApp(boolean unconditional) {
if (Display.getDisplay(this).getCurrent() == cameraSave) {
cameraSave.stop();
}
}
private void exitRequested() {
destroyApp(false);
notifyDestroyed();
}
void cameraFormExit() {
exitRequested();
}
/**
* restart the camera again
*
*/
void displayCanvasBack() {
Display.getDisplay(this).setCurrent(cameraSave);
cameraSave.start();
}
/**
* the byte[] of the image should be transmitted to a server
*
**/
void buildHTTPConnection(byte[] byteImage) {
displayImage.setImage(byteImage);
Display.getDisplay(this).setCurrent(displayImage);
HttpConnection hc = null;
OutputStream out = null;
try {
//enode the image data by the Base64 algorithm
String stringImage = Base64.encode(byteImage);
// URL of the Sevlet
String url = new String(
"http://ip-adress:8080/C:/Users/HASENDE/Documents/NetBeansProjects/Mobile/pics");
// Obtain an HTTPConnection
hc = (HttpConnection) Connector.open(url);
// Modifying the headers of the request
hc.setRequestMethod(HttpConnection.POST);
// Obtain the output stream for the HttpConnection
out = hc.openOutputStream();
out.write(stringImage.getBytes());
} catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
} finally {
try {
if (out != null)
out.close();
if (hc != null)
hc.close();
} catch (IOException ioe) {
}
}
// ** end network
}
/**
* stop the camera, show the captured image and transmit the image to a server
**/
void transmitImage(byte[] image) {
cameraSave.stop();
Display.getDisplay(this).setCurrent(displayImage);
buildHTTPConnection(image);
}
public void snap(){
try {
byte[] image = videoControl.getSnapshot("encoding = jpeg");
transmitImage(image);
messageItem.setText("Ok");
} catch (MediaException me) {
messageItem.setText("Media Exception: " + me.getMessage());
}
}
}
By identifying the statement that throws NPE you get 99% close to finding the bug:
byte[] image = videoControl.getSnapshot("encoding = jpeg");
NPE in above statement means videoControl is null. Now if you look at it closer, you may notice that in CameraMIDlet, videoControl is initialized with null and never changes to anything else - that's why you are getting NPE. By the way, from CameraForm code it looks like you intended to use videoControl object that is defined there, didn't you.
Side note. CameraForm seems to be designed to used in multiple threads (there are synchronized modifiers) - if this is the case, you better make sure that videoControl is also obtained from it in a synchronized way. Also in that case, add volatile modifier in definition of active flag:
private volatile boolean active = false; // in CameraForm
For Capturing photo use canvas instead of Form,
Check follwing code for Photo Capture
public class ImageCaptureCanvas extends Canvas {
UrMidlet midlet;
VideoControl videoControl;
Player player;
SnapShotCanvas snap;
private Display display;
public ImageCaptureCanvas(UrMidlet midlet) throws MediaException {
this.midlet = midlet;
this.display = Display.getDisplay(midlet);
this.setFullScreenMode(true);
try {
player = Manager.createPlayer("capture://image");
player.realize();
videoControl = (VideoControl) player.getControl("VideoControl");
} catch (Exception e) {
dm(e.getClass().getName());
}
videoControl.initDisplayMode(VideoControl.USE_DIRECT_VIDEO, this);
try {
videoControl.setDisplayLocation(0,0);
videoControl.setDisplaySize(getWidth(), getHeight());
} catch (MediaException me) {
try {
videoControl.setDisplayFullScreen(true);
} catch (MediaException me2) {
}
}
dm("icc10");
videoControl.setVisible(true);
dm("icc11");
player.start();
this.display.setCurrent(this);
}
public void dm(String message) {
Form form = new Form("Error");
form.append(message);
display.setCurrent(form);
}
public void paint(Graphics g) {
}
protected void keyPressed(int keyCode) {
boolean prv=false;
int actn=getGameAction(keyCode);
switch (keyCode) {
case KEY_NUM5:
prv=true;
Thread t = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t.start();
break;
}
if(!prv){
switch (actn) {
case Canvas.FIRE:
Thread t1 = new Thread() {
public void run() {
try {
byte[] raw = videoControl.getSnapshot(null);
Image image = Image.createImage(raw, 0, raw.length);
snap = new SnapShotCanvas(image);
display.setCurrent(snap);
} catch (Exception e) {
dm(e.getClass().getName() + " " + e.getMessage());
}
}
};
t1.start();
break;
}
}
}
}
SnapShotCanvas Code here
class SnapShotCanvas extends Canvas {
private Image image;
public SnapShotCanvas(Image image) {
this.image = image;
setFullScreenMode(true);
}
public void paint(Graphics g) {
g.drawImage(image, getWidth() / 2, getHeight() / 2, Graphics.HCENTER | Graphics.VCENTER);
}
}