I'm using custom TileProviders in my Android app to display offline maps and OpenStreetMap maps. It works, but there is a problem with the tiles resolution, which is quite bad. The files have a size of 256x256, and setting the width/height of my TileProvider to 128 doesn't change anything.
Here is some piece of code :
public class GenericUrlTileProvider extends UrlTileProvider {
// ---------------------------------------------------------------------------------------
// Private attributes :
private String _baseUrl;
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// Constructor :
public GenericUrlTileProvider(int width, int height, String url) {
super(width, height);
this._baseUrl = url;
}
#Override
public URL getTileUrl(int x, int y, int zoom) {
try {
return new URL(_baseUrl.replace("{z}", "" + zoom).replace("{x}", "" + x).replace("{y}", "" + y));
}
catch (MalformedURLException e) { e.printStackTrace(); }
return null;
}
// ---------------------------------------------------------------------------------------
}
Does anyone know how to fix this to support high resolution devices ?
Thanks
On #grub request, here is what I did for getting the 4 tiles of the next zoom level :
public Tile getTileFromNextZoomLevel(int x, int y, int zoom) {
final String topLeftTileUrl = _source.getUrlSchema().replace("{z}", "" + (zoom + 1)).replace("{x}", "" + (x * 2)).replace("{y}", "" + (y * 2));
final String topRightTileUrl = _source.getUrlSchema().replace("{z}", "" + (zoom + 1)).replace("{x}", "" + (x * 2 + 1)).replace("{y}", "" + (y * 2));
final String bottomLeftTileUrl = _source.getUrlSchema().replace("{z}", "" + (zoom + 1)).replace("{x}", "" + (x * 2)).replace("{y}", "" + (y * 2 + 1));
final String bottomRightTileUrl = _source.getUrlSchema().replace("{z}", "" + (zoom + 1)).replace("{x}", "" + (x * 2 + 1)).replace("{y}", "" + (y * 2 + 1));
final Bitmap[] tiles = new Bitmap[4];
Thread t1 = new Thread() {
#Override
public void run() { tiles[0] = Utils.getBitmapFromURL(topLeftTileUrl); }
};
t1.start();
Thread t2 = new Thread() {
#Override
public void run() { tiles[1] = Utils.getBitmapFromURL(topRightTileUrl); }
};
t2.start();
Thread t3 = new Thread() {
#Override
public void run() { tiles[2] = Utils.getBitmapFromURL(bottomLeftTileUrl); }
};
t3.start();
Thread t4 = new Thread() {
#Override
public void run() { tiles[3] = Utils.getBitmapFromURL(bottomRightTileUrl); }
};
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
}
catch (InterruptedException e) { e.printStackTrace(); }
byte[] tile = Utils.mergeBitmaps(tiles, Bitmap.CompressFormat.JPEG); // PNG is a lot slower, use it only if you really need to
return tile == null ? TileProvider.NO_TILE : new Tile( (int) _source.getTileSize().getWidth(), (int) _source.getTileSize().getHeight(), tile);
}
And the Utils methods :
public static byte[] mergeBitmaps(Bitmap[] parts, Bitmap.CompressFormat format) {
// Check if all the bitmap are null (if so return null) :
boolean allNulls = true;
for (int i = 0; i < parts.length; i++) {
if(parts[i] != null) {
allNulls = false;
break;
}
}
if(allNulls) return null;
Bitmap tileBitmap = Bitmap.createBitmap(512, 512, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(tileBitmap);
Paint paint = new Paint();
for (int i = 0; i < parts.length; i++) {
if(parts[i] == null) {
parts[i] = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888);
}
canvas.drawBitmap(parts[i], parts[i].getWidth() * (i % 2), parts[i].getHeight() * (i / 2), paint);
}
ByteArrayOutputStream stream = new ByteArrayOutputStream();
tileBitmap.compress(format, 100, stream);
byte[] bytes = stream.toByteArray();
return bytes;
}
public static Bitmap getBitmapFromURL(String urlString) {
try {
// Ensure the file exists :
if(Utils.getResponseCode(urlString) != 200) return null;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
Bitmap bitmap = BitmapFactory.decodeStream(connection.getInputStream());
return bitmap;
}
catch (IOException e) { return null; }
}
You may have to adapt it for your needs. Please note that my app is still under development, and this code may need some tests / improvements.
Related
In CameraX Analysis, setTargetResolution(new Size(2560, 800), but in Analyzer imageProxy.getImage.getWidth=1280 and getHeight=400, and YUVToByte(imageProxy.getImage).length()=768000。In Camera, parameter.setPreviewSize(2560, 800) then byte[].length in onPreviewFrame is 3072000(equales 768000*(2560/1280)*(800/400))。How can I make CameraX Analyzer imageProxy.getImage.getWidth and getHeight = 2560 and 800, and YUVToByte(ImageProxy.getImage).length()=3072000? In CameraX onPreviewFrame(), res always = null, in Camera onPreviewFrame(), res can get currect value, what's the different between CameraX and Camera? And what should I do in CameraX?
CameraX:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
getSupportActionBar().hide();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
viewFinder = findViewById(R.id.previewView);
executor = Executors.newSingleThreadExecutor();
if (!allPermissionGranted()) {
ActivityCompat.requestPermissions(this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS);
}
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
width = metric.widthPixels;
height = metric.heightPixels;
l = 100;
r = width - 100;
ntmpH = (r - l) * 58 / 100;
t = (height - ntmpH) / 2;
b = t + ntmpH;
double proportion = (double) width / (double) preHeight;
double hproportion = (double) height / (double) preWidth;
l = (int) (l / proportion);
t = (int) (t / hproportion);
r = (int) (r / proportion);
b = (int) (b / hproportion);
m_ROI[0] = l;
m_ROI[1] = t;
m_ROI[2] = r;
m_ROI[3] = b;
cameraProviderFuture = processCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
#SuppressLint("RestrictedApi") Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder().
requireLensFacing(CameraSelector.LENS_FACING_BACK).build();
ImageAnalysis imageAnalysis = new ImageAnalysis.Builder()
.setTargetResolution(new Size(2560, 800))
.setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
.setTargetRotation(Surface.ROTATION_90)
.build();
imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
#SuppressLint("UnsafeExperimentalUsageError")
#Override
public void analyze(#NonNull ImageProxy imageProxy) {
if (imageProxy.getFormat() == ImageFormat.YUV_420_888) {
image = imageProxy.getImage();
bIninKernal();
Log.d("Size ", image.getWidth() + "/" + image.getHeight());
onPreviewFrame(YUVToByte(image));
} else {
Log.d("Status ", "照片格式錯誤" + imageProxy.getFormat());
}
imageProxy.close();
}
});
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
preview.setSurfaceProvider(viewFinder.createSurfaceProvider());
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
}
}, ContextCompat.getMainExecutor(this));
}
#NonNull
#Override
public CameraXConfig getCameraXConfig() {
return Camera2Config.defaultConfig();
}
private boolean allPermissionGranted() {
for (String permission : REQUIRED_PERMISSIONS) {
if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
private byte[] YUVToByte(Image image) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer0 = planes[0].getBuffer();
ByteBuffer buffer1 = planes[1].getBuffer();
ByteBuffer buffer2 = planes[2].getBuffer();
int width = image.getWidth();
int height = image.getHeight();
byte[] data = new byte[image.getWidth() * image.getHeight() * ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) / 8];
byte[] rowData1 = new byte[planes[1].getRowStride()];
byte[] rowData2 = new byte[planes[2].getRowStride()];
int bytesPerPixel = ImageFormat.getBitsPerPixel(ImageFormat.YUV_420_888) / 8;
// loop via rows of u/v channels
int offsetY = 0;
int sizeY = width * height * bytesPerPixel;
int sizeUV = (width * height * bytesPerPixel) / 4;
for (int row = 0; row < height; row++) {
// fill data for Y channel, two row
{
int length = bytesPerPixel * width;
buffer0.get(data, offsetY, length);
if (height - row != 1)
buffer0.position(buffer0.position() + planes[0].getRowStride() - length);
offsetY += length;
}
if (row >= height / 2)
continue;
{
int uvlength = planes[1].getRowStride();
if ((height / 2 - row) == 1) {
uvlength = width / 2 - planes[1].getPixelStride() + 1;
}
buffer1.get(rowData1, 0, uvlength);
buffer2.get(rowData2, 0, uvlength);
// fill data for u/v channels
for (int col = 0; col < width / 2; ++col) {
// u channel
data[sizeY + (row * width) / 2 + col] = rowData1[col * planes[1].getPixelStride()];
// v channel
data[sizeY + sizeUV + (row * width) / 2 + col] = rowData2[col * planes[2].getPixelStride()];
}
}
}
return data;
}
private void bIninKernal() {
api = new LPR();
String FilePath = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
int nRet = api.Init(this, m_ROI[0], m_ROI[1], m_ROI[2], m_ROI[3], preHeight, preWidth, FilePath);
if (nRet != 0) {
bInitKernal = false;
Log.d("Status ", "相機開啟失敗");
} else {
bInitKernal = true;
}
}
private void onPreviewFrame(byte[] data) {
bIninKernal();
tackData = data;
Log.d("data length ", data.length + "");
resultStr = "";
if (!leaving && bInitKernal) {
byte[] result;
String res = "";
result = api.VideoRec(tackData, 1280, 400, 1);
try {
res = new String(result, "gb2312");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (res != null && !"".equals(res.trim())) {
resultStr = res.trim();
if (resultStr != "") {
leaving = true;
MediaActionSound sound = new MediaActionSound();
sound.play(MediaActionSound.SHUTTER_CLICK);
Log.d("Status ", "辨識成功");
Log.d("車牌號碼", resultStr);
Thread thread = new Thread(Image_update);
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent intent = new Intent(MainActivity2.this, MainActivity.class);
intent.putExtra("result", resultStr);
Log.d("result", resultStr);
setResult(1, intent);
finish();
}
} else {
Log.d("Status ", "未分辨車牌號碼,請重拍");
}
}
}
public void copyDataBase() throws IOException {
// Common common = new Common();
// 取得SK卡路徑/lpr.key
String dst = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
File file = new File(dst);
if (!file.exists()) {
// file.createNewFile();
} else {
file.delete();
}
Log.d("File Name", file.toString());
try {
InputStream myInput = getAssets().open("lpr.key");
OutputStream myOutput = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
System.out.println("lpr.key" + "is not found");
}
}
private Runnable Image_update = new Runnable() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://0d9dccd7eac8.ngrok.io/")
.addConverterFactory(GsonConverterFactory.create())
.build();
MyAPIService myAPIService = retrofit.create(MyAPIService.class);
#Override
public void run() {
Log.d("Status ", "run");
Log.d("resultStr ", resultStr);
String url = "D:\\Images\\license_plate\\";
String imgStr = bitmap2base64(toBitmap(image));
LicensePlate licensePlate = new LicensePlate();
licensePlate.setsPlate(resultStr);
licensePlate.setsPicPosition(url + resultStr);
licensePlate.setImgStr(imgStr);
Call<LicensePlate> call = myAPIService.uploadLicensePlate(licensePlate);
call.enqueue(new Callback<LicensePlate>() {
#Override
public void onResponse(Call<LicensePlate> call, Response<LicensePlate> response) {
if(response.isSuccessful()){
Log.d("Status ", "照片上傳成功");
}else{
Log.d("Status ", "照片上傳失敗");
Log.d("response code ", response.code() + "");
}
}
#Override
public void onFailure(Call<LicensePlate> call, Throwable t) {
Log.d("Status ", "onFailure");
Log.d("Message ", t.getMessage());
}
});
}
};
private String bitmap2base64(Bitmap bitmap){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
return Base64.encodeToString(outputStream.toByteArray(), Base64.DEFAULT).trim().replaceAll("\n", "").replaceAll("\r", "");
}
private Bitmap toBitmap(Image image) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer yBuffer = planes[0].getBuffer();
ByteBuffer uBuffer = planes[1].getBuffer();
ByteBuffer vBuffer = planes[2].getBuffer();
int ySize = yBuffer.remaining();
int uSize = uBuffer.remaining();
int vSize = vBuffer.remaining();
byte[] nv21 = new byte[ySize + uSize + vSize];
//U and V are swapped
yBuffer.get(nv21, 0, ySize);
vBuffer.get(nv21, ySize, vSize);
uBuffer.get(nv21, ySize + vSize, uSize);
YuvImage yuvImage = new YuvImage(nv21, ImageFormat.NV21, image.getWidth(), image.getHeight(), null);
ByteArrayOutputStream out = new ByteArrayOutputStream();
yuvImage.compressToJpeg(new Rect(0, 0, yuvImage.getWidth(), yuvImage.getHeight()), 75, out);
byte[] imageBytes = out.toByteArray();
return BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length);
}
}
Camera
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int metricwidth = metric.widthPixels; // 屏幕宽度(像素)
int metricheight = metric.heightPixels; // 屏幕高度(像素)
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);// 竖屏
Configuration cf= this.getResources().getConfiguration(); //获取设置的配置信息
int noriention=cf.orientation;
requestWindowFeature(Window.FEATURE_NO_TITLE);// 隐藏标题
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
// // 屏幕常亮
getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_lpr2);
findView();
}
private void findView() {
surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
re_c = (RelativeLayout) findViewById(R.id.re_c);
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
width = metric.widthPixels; // 屏幕宽度(像素)
height = metric.heightPixels; // 屏幕高度(像素)
if(myView==null)
{
if (isFatty)
{
myView = new LPRfinderView2(LPR2Activity.this, width, height, isFatty);
}
else
{
myView = new LPRfinderView2(LPR2Activity.this, width, height);
}
re_c.addView(myView);
}
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(LPR2Activity.this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceView.setFocusable(true);
//surfaceView.invali.date();
}
public void copyDataBase() throws IOException {
// Common common = new Common();
// 取得SK卡路徑/lpr.key
String dst = Environment.getExternalStorageDirectory().toString() + "/lpr.key";
File file = new File(dst);
if (!file.exists()) {
// file.createNewFile();
} else {
file.delete();
}
Log.d("File Name", file.toString());
try {
InputStream myInput = getAssets().open("lpr.key");
OutputStream myOutput = new FileOutputStream(dst);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
} catch (Exception e) {
System.out.println("lpr.key" + "is not found");
}
}
public void surfaceCreated(SurfaceHolder holder) {
if (mycamera == null) {
try {
mycamera = Camera.open();
} catch (Exception e) {
e.printStackTrace();
String mess = "打开摄像头失败";
Toast.makeText(getApplicationContext(), mess, Toast.LENGTH_LONG).show();
return;
}
}
if(mycamera!=null)
{
try {
mycamera.setPreviewDisplay(holder);
timer2 = new Timer();
if (timer == null)
{
timer = new TimerTask()
{
public void run()
{
if (mycamera != null)
{
try
{
mycamera.autoFocus(new AutoFocusCallback()
{
public void onAutoFocus(boolean success, Camera camera)
{
}
});
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
};
}
timer2.schedule(timer, 500, 2500);
initCamera();
//mycamera.startPreview();
//mycamera.autoFocus(null);
} catch (IOException e) {
e.printStackTrace();
}
}
if(api==null)
{
api= new LPR();
String FilePath =Environment.getExternalStorageDirectory().toString()+"/lpr.key";
int nRet = api.Init(this,m_ROI[0], m_ROI[1], m_ROI[2], m_ROI[3], preHeight, preWidth,FilePath);
if(nRet!=0)
{
Toast.makeText(getApplicationContext(), "啟動失敗,請調整時間", Toast.LENGTH_SHORT).show();
Log.d("nRet ", nRet + "");
bInitKernal =false;
}
else
{
bInitKernal=true;
}
}
if(alertDialog==null){
alertDialog = new AlertDialog.Builder(this).create();
alertDialoginfo = new AlertDialog.Builder(this).create();
}
}
#Override
public void surfaceChanged(final SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
try {
if (mycamera != null) {
mycamera.setPreviewCallback(null);
mycamera.stopPreview();
mycamera.release();
mycamera = null;
}
} catch (Exception e) {
}
if(bInitKernal){
bInitKernal=false;
api = null;
}
if(toast!=null){
toast.cancel();
toast = null;
}
if(timer2!=null){
timer2.cancel();
timer2=null;
}
if(alertDialog!=null)
{
alertDialog.dismiss();
alertDialog.cancel();
alertDialog=null;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
try {
if (mycamera != null) {
mycamera.setPreviewCallback(null);
mycamera.stopPreview();
mycamera.release();
mycamera = null;
}
} catch (Exception e) {
e.printStackTrace();
}
if(bInitKernal)
{
bInitKernal=false;
api = null;
}
finish();
if(toast!=null){
toast.cancel();
toast=null;
}
if(timer2!=null){
timer2.cancel();
timer2=null;
}
if(alertDialog!=null)
{
alertDialog.cancel();
alertDialog=null;
}
}
return super.onKeyDown(keyCode, event);
}
#TargetApi(14)
private void initCamera() {
Camera.Parameters parameters = mycamera.getParameters();
List<Camera.Size> list = parameters.getSupportedPreviewSizes();
preWidth = list.get(4).width;
preHeight = list.get(4).height;
parameters.setPictureFormat(PixelFormat.JPEG);
parameters.setPreviewSize(preWidth,preHeight);
if (!bROI) {
int l,t,r,b;
l = 100;
r = width-100;
int ntmpH =(r-l)*58/100;
t = (height-ntmpH)/2;
b = t+ntmpH;
double proportion = (double) width / (double) preHeight;
double hproportion=(double)height/(double) preWidth;
l = (int) (l /proportion);
t = (int) (t /hproportion);
r = (int) (r /proportion);
b = (int) (b / hproportion);
m_ROI[0]=l;
m_ROI[1]=t;
m_ROI[2]=r;
m_ROI[3]=b;
bROI = true;
}
if (parameters.getSupportedFocusModes().contains(
parameters.FOCUS_MODE_AUTO))
{
parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);// 1连续对焦
}
mycamera.setPreviewCallback(LPR2Activity.this);
mycamera.setParameters(parameters);
mycamera.setDisplayOrientation(90); //一般機種
mycamera.startPreview();
}
public void onPreviewFrame(byte[] data, Camera camera) {
tackData = data;
Log.d("data length ", data.length + "");
ByteArrayInputStream bis = new ByteArrayInputStream(data);
resultStr = "";
if (!leaving&& bInitKernal ) {
Log.d("Status ", "開始判斷");
byte result[];//[] = new byte[10];
String res="";
result = api.VideoRec(tackData, preWidth, preHeight, 1);
Log.d("preWidth ", preWidth + "");
Log.d("preHeight", preHeight + "");
Log.d("width ", width + "");
Log.d("height", height + "");
try {
res = new String(result,"gb2312");
Log.d("try ", res);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
Log.d("Exception ", e.getMessage());
e.printStackTrace();
}
Log.d("res ", res);
if(res!=null&&!"".equals(res.trim()))
{
Camera.Parameters parameters = mycamera.getParameters();
resultStr =res.trim();
if (resultStr != "") {
leaving = true;
//拍照音效
MediaActionSound sound = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
sound = new MediaActionSound();
sound.play(MediaActionSound.SHUTTER_CLICK);
}
Intent intent = new Intent();
intent.putExtra("strPltNo",resultStr);
setResult(2,intent);
finish();
}else{
Log.d("Status ", "未分配車牌號碼,請重拍");
}
}
}
}
#RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
public String pictureName() {
String str = "";
Time t = new Time();
t.setToNow(); // 取得系统时间。
int year = t.year;
int month = t.month + 1;
int date = t.monthDay;
int hour = t.hour; // 0-23
int minute = t.minute;
int second = t.second;
if (month < 10)
str = String.valueOf(year) + "0" + String.valueOf(month);
else {
str = String.valueOf(year) + String.valueOf(month);
}
if (date < 10)
str = str + "0" + String.valueOf(date + "_");
else {
str = str + String.valueOf(date + "_");
}
if (hour < 10)
str = str + "0" + String.valueOf(hour);
else {
str = str + String.valueOf(hour);
}
if (minute < 10)
str = str + "0" + String.valueOf(minute);
else {
str = str + String.valueOf(minute);
}
if (second < 10)
str = str + "0" + String.valueOf(second);
else {
str = str + String.valueOf(second);
}
return str;
}
public void Leave(View view) {
Intent intent = new Intent();
intent.putExtra("strPltNo","");
setResult(3,intent);
finish();
}
}
CameraX Log
Camera Log
With regards to the image analysis resolution, the documentation of ImageAnalysis.Builder.setTargetResolution() states that:
The maximum available resolution that could be selected for an
ImageAnalysis is limited to be under 1080p.
So setting a size of 2560x800 won't work as you expect. In return CameraX seems to be selecting the maximum ImageAnalysis resolution that has the same aspect ratio you requested (2560/800 = 1280/400).
Is there any posibility to show Google Maps if you are offline in your own App?
What about if I download an Area FROM Google Maps application for offline mode, could i visualize the map on the app that i develop if i don't have internet connection?
if not, What options do i have to make this possible? I just want to visualize the map when my app is offline...
The following its the code that this post provided TileProvider using local tiles
#Override
public Tile getTile(int x, int y, int zoom) {
byte[] image = readTileImage(x, y, zoom);
return image == null ? null : new Tile(TILE_WIDTH, TILE_HEIGHT,image);
}
private byte[] readTileImage(int x,int y, int zoom){
InputStream is= null;
ByteArrayOutputStream buffer= null;
try{
is= mAssets.open(getTileFileName(x,y,zoom));
buffer= new ByteArrayOutputStream();
int nRead;
byte[] data= new byte[BUFFER_SIZE];
while ((nRead= is.read(data,0,BUFFER_SIZE)) !=-1){
buffer.write(data,0,nRead);
}
buffer.flush();
return buffer.toByteArray();
}
catch(IOException ex){
Log.e("LINE 60 CustomMap", ex.getMessage());
return null;
}catch(OutOfMemoryError e){
Log.e("LINE 64 CustomMap", e.getMessage());
return null;
}finally{
if(is!=null){
try{
is.close();
} catch (IOException e) {}
}
if(buffer !=null){
try{
buffer.close();
}catch (Exception e){}
}
}
}
private String getTileFileName(int x, int y, int zoom){
return "map/"+ zoom +'/' +x+ '/'+y+".png";
}
I was looking for information, and My questions is, how can i download the tiles?
I was facing the same challenge, and none of the examples I found included a complete implementation of downloading the tiles, writing them to file and reading them from file.
This is my code, which reads the tile from file when it's available locally and downloads/saves the tile when not. This uses the OpenStreetMap.org tile server, but you could use any server you like by changing the URL.
private class OfflineTileProvider implements TileProvider {
private static final String TILES_DIR = "your_tiles_directory/";
private static final int TILE_WIDTH = 256;
private static final int TILE_HEIGHT = 256;
private static final int BUFFER_SIZE_FILE = 16384;
private static final int BUFFER_SIZE_NETWORK = 8192;
private ConnectivityManager connectivityManager;
#Override
public Tile getTile(int x, int y, int z) {
Log.d(TAG, "OfflineTileProvider.getTile(" + x + ", " + y + ", " + z + ")");
try {
byte[] data;
File file = new File(TILES_DIR + z, x + "_" + y + ".png");
if (file.exists()) {
data = readTile(new FileInputStream(file), BUFFER_SIZE_FILE);
} else {
if (connectivityManager == null) {
connectivityManager = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
}
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
Log.w(TAG, "No network");
return NO_TILE;
}
Log.d(TAG, "Downloading tile");
data = readTile(new URL("https://a.tile.openstreetmap.org/" +
z + "/" + x + "/" + y + ".png").openStream(),
BUFFER_SIZE_NETWORK);
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
out.write(data);
}
}
return new Tile(TILE_WIDTH, TILE_HEIGHT, data);
} catch (Exception ex) {
Log.e(TAG, "Error loading tile", ex);
return NO_TILE;
}
}
private byte[] readTile(InputStream in, int bufferSize) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try {
int i;
byte[] data = new byte[bufferSize];
while ((i = in.read(data, 0, bufferSize)) != -1) {
buffer.write(data, 0, i);
}
buffer.flush();
return buffer.toByteArray();
} finally {
in.close();
buffer.close();
}
}
}
Replace "your_tiles_directory" with the path to the directory where you want to store your tiles.
To use the TileProvider:
map.setMapType(GoogleMap.MAP_TYPE_NONE);
offlineTileOverlay = map.addTileOverlay(new TileOverlayOptions()
.tileProvider(new OfflineTileProvider()));
Edit: You may want to set the max zoom level, the default is 21 but OpenStreetMap for example seems to have a maximum of 19.
map.setMaxZoomPreference(19);
You can download tile image from a tile server and cache on your app. Check some server on this link. Or you can build a tile as this demo, then download tile image from it.
Good luck
I've read some things about this problem named in the title, but I can't fix it in my code.
Only the Debugger shows me that 'cant call set pixel on a recycled bitmap' and closes the app.
So It's clear, to get an mutable Bitmap and manage the bitmap right. But where is my mistake?
I hope you can help me.
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_localization);
this.bm = BitmapFactory.decodeResource(getResources(), R.drawable.raumstrukturapp);
this.picture = (ImageView) findViewById(R.id.picture);
this.picture.setImageResource(R.drawable.raumstrukturapp); calculatePositioniInPixel(infoccol.getBeaconRoomCollector().getBeaconRoom(0).getBeaconRoomeElements().get(0));
drawPosition(R.drawable.raumstrukturapp);
}
private void calculatePositioniInPixel(BeaconRoomElement bre) {
setKSUnit(9, 14);
this.coordInPixel[0][0] = bre.getElementcoordinates()[0][0] * this.xUnit;
Log.i("Beacons", "x links oben: " + this.coordInPixel[0][0]);
this.coordInPixel[0][1] = bre.getElementcoordinates()[0][1] * this.yUnit;
Log.i("Beacons", "y links oben: " + this.coordInPixel[0][1]);
this.coordInPixel[1][0] = bre.getElementcoordinates()[1][0] * this.xUnit;
Log.i("Beacons", "x rechts oben: " + this.coordInPixel[1][0]);
this.coordInPixel[1][1] = bre.getElementcoordinates()[1][1] * this.yUnit;
Log.i("Beacons", "y rechts oben: " + this.coordInPixel[1][1]);
this.coordInPixel[2][0] = bre.getElementcoordinates()[2][0] * this.xUnit;
Log.i("Beacons", "x rechts unten: " + this.coordInPixel[2][0]);
this.coordInPixel[2][1] = bre.getElementcoordinates()[2][1] * this.yUnit;
Log.i("Beacons", "y rechts unten: " + this.coordInPixel[2][1]);
this.coordInPixel[3][0] = bre.getElementcoordinates()[3][0] * this.xUnit;
Log.i("Beacons", "x links unten: " + this.coordInPixel[3][0]);
this.coordInPixel[3][1] = bre.getElementcoordinates()[3][1] + this.yUnit;
Log.i("Beacons", "y links unten: " + this.coordInPixel[3][1]);
}
...
private void drawPosition(int resID) {
bm = BitmapFactory.decodeResource(getResources(), R.drawable.raumstrukturapp);
mutableBm = convertToMutable(bm);
for(int i = (int) this.coordInPixel[0][0]; i <= this.coordInPixel[1][0]; i++) {
for(int j = (int)(this.coordInPixel[0][1]); j <= (this.coordInPixel[2][1]); j++) {
if(j > 0) {
mutableBm.setPixel(i, j, Color.rgb(255, 128, 0));
}
}
}
this.picture.setImageBitmap(mutableBm);
}
public static Bitmap convertToMutable(Bitmap imgIn) {
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "temp.tmp");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
int width = imgIn.getWidth();
int height = imgIn.getHeight();
Bitmap.Config type = imgIn.getConfig();
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, imgIn.getRowBytes()*height);
imgIn.copyPixelsToBuffer(map);
imgIn.recycle();
System.gc();
imgIn = Bitmap.createBitmap(width, height, type);
map.position(0);
imgIn.copyPixelsFromBuffer(map);
channel.close();
randomAccessFile.close();
file.delete();
...
return imgIn;
}
...
}
I want to write some text into a pdf. I have the data in "icrResultTxt". I am also writing the data to text.txt file before trying to write to a pdf. When I try to write to the pdf I get "No glyph for U+000A in font Helvetica-Bold". How to solve it? I dont have any fondness for "Helvetica-Bold". I am willing to change to any font.
#Override
protected Boolean doInBackground(Void... params) {
Boolean ret = false;
PDDocument document = new PDDocument();
try {
float scale = 0.8f; // alter this value to set the image size
formPreference = getSharedPreferences(SHARD_PREFERENCES,
MODE_PRIVATE);
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(
document, page, false, true);
PDFont pdfFont = PDType1Font.HELVETICA_BOLD;
float fontSize = 25;
float leading = 1.5f * fontSize;
PDRectangle mediabox = page.getMediaBox();
float margin = 72;
float width = mediabox.getWidth() - 2 * margin;
float startX = mediabox.getLowerLeftX() + margin;
float startY = mediabox.getUpperRightY() - margin;
// icrResultTxt;//
writeToFile(icrResultTxt);
String text = icrResultTxt; // "I am trying to create a PDF file with a lot of text contents in the document. I am using PDFBox";
List<String> lines = new ArrayList<String>();
int lastSpace = -1;
while (text.length() > 0) {
int spaceIndex = text.indexOf(' ', lastSpace + 1);
if (spaceIndex < 0) {
lines.add(text);
text = "";
} else {
String subString = text.substring(0, spaceIndex);
float size = fontSize
* pdfFont.getStringWidth(subString) / 1000;
if (size > width) {
if (lastSpace < 0) // So we have a word longer than
// the line... draw it anyways
lastSpace = spaceIndex;
subString = text.substring(0, lastSpace);
lines.add(subString);
text = text.substring(lastSpace).trim();
lastSpace = -1;
} else {
lastSpace = spaceIndex;
}
}
}
contentStream.beginText();
contentStream.setFont(pdfFont, fontSize);
contentStream.moveTextPositionByAmount(startX, startY);
for (String line : lines) {
contentStream.drawString(line);
contentStream.moveTextPositionByAmount(0, -leading);
}
contentStream.endText();
contentStream.close();
File fz = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + "hello.pdf");
if (!fz.exists()) {
fz.createNewFile();
} else {
fz.delete();
fz.createNewFile();
}
document.save(fz);
} catch (Exception e) {
Log.v("mango", e.getMessage());
}
private void writeToFile(String data) {
try {
File d = GetImageFile("test.txt");
if (d.exists()) {
d.delete();
d.createNewFile();
} else {
d.createNewFile();
}
FileOutputStream stream = new FileOutputStream(d);
try {
stream.write(data.getBytes());
} finally {
stream.close();
}
} catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
Use the following code instead "\r\n"
contentStream.moveTextPositionByAmount(100, 700);
contentStream.drawString("hello");
contentStream.endText();
contentStream.beginText();
contentStream.moveTextPositionByAmount(100, 690);//the second parameter mast between 800.0 and 0.0
I have an issue when I am trying to download a file from server using FTP. I need to display seek-bar status of downloading file and download speed of the Internet. I am able to display seek-bar status and speed of the Internet for HTTP, but for FTP I am not able to perform that same task. In the attached image below I need to display seek-bar and network speed for FTP and HTTP. Below is the source code I used for HTTP and FTP. I don't know where I missed it?
HTTP Code:
class DownloadFileAsync extends AsyncTask<String, String, String> { //see the summary of asyncTask
long duration, pk;
private boolean sleep = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//constructor
public DownloadFileAsync(HashMap<String, Object> map) {
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count = 0;
try {
updateUI(pp, R.drawable.pause);
updateUI(status, "Connecting");
URL url = new URL(map.get("url").toString());
URLConnection conexion = url.openConnection();
conexion.connect();
final int lenghtOfFile = conexion.getContentLength();
InputStream input = new BufferedInputStream(url.openStream());
updateUI(status, "Connected");
OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()
+ File.separator
+ Info.getInfo(con).HTTP_DOWNLOAD_FILE_NAME);
byte data[] = new byte[1024];
long total = 0;
final long started = System.currentTimeMillis();
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Downloading");
while ((count = input.read(data)) != -1) {
while (sleep) {
Thread.sleep(1000);
sleepingTime +=1000;
}
total += count;
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024 + " kbps");
if (pk <= (speed / duration) / 1024)
{
pk = (speed / duration) / 1024;
}
//peak.setText(pk + " kbps");
}
}
});
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
updateUI(status, "Success");
}
catch (final Exception e) {
e.printStackTrace();
updateUI(status, "Failed");
}
updateUI(pp, R.drawable.resume);
return null;
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep = val;
}
public boolean areYouSleeping() {
return sleep;
}
#Override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
/*System.out.println("Info.getInfo(con).data.indexOf(map) + 1 "+Info.getInfo(con).data.indexOf(map) + 1
+" Info.getInfo(con).data.size() "+Info.getInfo(con).data.size()+" testRunning "+testRunning);
System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);*/
System.out.println("asynclist "+asynclist.size());
asynclist.remove(0); //asynclist contains objects of (downloadAsync(map))
if(asynclist.size() > 0){
System.out.println("tlist in post execute+++"+tlist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
DownloadFileAsync dfa = (DownloadFileAsync) asynclist.get(0);
dfa.execute();
tlist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE && stopCount < asynclist.size() && testRunning) { //for parallel mode
System.out.println("stopCount before condition= " + stopCount);
if (stopCount == asynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + stopCount);
stopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
stopCount++;
System.out.println("stopCount after increment = " + stopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
}
}
For FTP:--
class FTPAsync extends AsyncTask<String, String, String> {
//private int mode = -1;
//added
long duration, pk;
private boolean sleep1 = false;
private HashMap<String, Object> map;
private ProgressBar bar;
private TextView real_time, test_avg, peak, status;
private ImageView pp;
//
public FTPAsync(int mode) {
// this.mode = mode;
}
//added
public FTPAsync(HashMap<String, Object> map) {
//Toast.makeText(con, "ftpAsync constructer is called" ,Toast.LENGTH_SHORT).show();
this.map = map;
bar = (ProgressBar) map.get("bar");
// trans = (TextView) map.get("trans");
//real_time = (TextView) map.get("real_time");
test_avg = (TextView) map.get("test_avg");
//peak = (TextView) map.get("peak");
status = (TextView) map.get("status");
pp = (ImageView) map.get("pp");
}
//
#Override
protected void onPreExecute() {
//Toast.makeText(con, "onPreExecute() is called" ,Toast.LENGTH_SHORT).show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
int count = 0;
FTPClient ObjFtpCon = new FTPClient();
//Toast.makeText(con, "FTPasync doInBackground() is called" ,Toast.LENGTH_SHORT).show();
try {
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(0);
//real_time.setText(0 + " secs");
//test_avg.setText(0+ " kbps");
//peak.setText(0+" kbps");
}
});
updateUI(pp, R.drawable.pause);
//ObjFtpCon.connect("ftp.customhdclips.com");
ObjFtpCon.connect("ftp."+map.get("url").toString());
updateUI(status, "Connecting");
//if (ObjFtpCon.login("fstech#customhdclips.com", "fstech123")) {
if (ObjFtpCon.login(map.get("username").toString(), map.get("password").toString())) {
updateUI(status, "Connected");
// toast("Connected to FTP Server : ftp.customhdclips.com");
ObjFtpCon.enterLocalPassiveMode(); // important!
ObjFtpCon.cwd("/");// to send the FTP CWD command to the server, receive the reply, and return the reply code.
//if (mode == 0) {
if(Integer.parseInt((map.get("oprn").toString()))== 0){
// Download
System.out.println("download test is called");
File objfile = new File(
Environment.getExternalStorageDirectory()
+ File.separator + "/logo.png");
objfile.createNewFile();
FileOutputStream objFos = new FileOutputStream(objfile);
boolean blnresult = ObjFtpCon.retrieveFile("/logo.png",
objFos);
objFos.close();
if (blnresult) {
// toast("Download succeeded");
// toast("Stored at : " +
// objfile.getAbsolutePath());
}
}
else {
// Upload
System.out.println("upload test is called");
//Toast.makeText(con, "upload FTP test is called", Toast.LENGTH_SHORT).show();
//ContextWrapper context = null;
//assetManager= context.getAssets();
assetManager = getResources().getAssets();
input1 = assetManager.open("hello.txt");
final long started = System.currentTimeMillis();
int size = input1.available();
//byte[] buffer = new byte[size];
byte dataByte[] = new byte[1024];
//input1.read(buffer);
//String data = "ZK DATA TESTER TEST DATA1sdfsdf";
String data = input1.toString();
System.out.println("dat value is........"+data);
final int lenghtOfFile = data.getBytes().length;
//final int lenghtOfFile = input1.getBytes().length;
System.out.println("length of file....."+lenghtOfFile);
ByteArrayInputStream in = new ByteArrayInputStream(
data.getBytes());
//toast("Uploading /test.txt");
//Toast.makeText(con,"File Size : " +data.getBytes().length + " bytes",Toast.LENGTH_SHORT).show();
//byte b[] = new byte[1024];
long total = 0;
long sleepingTime= 0;
System.out.println("started time --"+started);
updateUI(status, "Uploading");
while ((count = in.read(dataByte)) != -1)
{
System.out.println("read value is...."+in.read(dataByte));
while (sleep1) {
Thread.sleep(1000);
System.out.println("ftp upload is in sleeping mode");
sleepingTime +=1000;
}
System.out.println("Total count --"+count);
total += count;
System.out.println("Only Total --"+total);
final int progress = (int) ((total * 100) / lenghtOfFile);
final long speed = total;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
boolean result = ObjFtpCon.storeFile("/test.txt", input1);
//boolean result = ObjFtpCon.storeFile(map.get("file_address").toString()+"/test.txt", input1);
duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
//real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((((speed / duration)*1000)*0.0078125)
+ " kbps");
/*if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}*/
if (pk <= ((speed / duration)*1000)*0.0078125) {
pk = (long)(((speed / duration)*1000)*0.0078125);
}
//peak.setText(pk + " kbps");
}
}
});
//in.close();
if (result) {
updateUI(status, "Uploaded");
// toast("Uploading succeeded");
// toast("Uploaded at /test.txt");
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
System.out.println("curreent time..... "+System.currentTimeMillis());
System.out.println("started time --"+started);
System.out.println("sleep tome...."+sleepingTime);
System.out.println("duration is....."+duration);
/*runOnUiThread(new Runnable() {
public void run() {
bar.setProgress(progress);
// trans.setText("" + progress);
//duration = ((System.currentTimeMillis() - started)-sleepingTime) / 1000;
real_time.setText(duration + " secs");
if (duration != 0) {
test_avg.setText((speed / duration) / 1024
+ " kbps");
if (pk <= (speed / duration) / 1024) {
pk = (speed / duration) / 1024;
}
peak.setText(pk + " kbps");
}
}
});*/
}
/*while(!result){Thread.sleep(1000);}*/
}
in.close();
}
}
else{
System.out.println("password entered is incorrect");
//Toast.makeText(con, "Username or/and password is incorrect", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
try {
ObjFtpCon.logout();
ObjFtpCon.disconnect();
}
catch (IOException e) {
e.printStackTrace();
// toast(e.getLocalizedMessage());
}
return null;
}
#override
protected void onPostExecute(String unused) {
try {
//System.out.println("Info.getInfo(con).data.indexOf(map)==="+Info.getInfo(con).data.indexOf(map)+" map "+map);
if (!PARALLEL_MODE //for sequence mode
&& (Info.getInfo(con).data.indexOf(map) + 1) <= Info.getInfo(con).data.size()
&& testRunning) {
System.out.println("ftpasynclist "+ftpasynclist.size());
ftpasynclist.remove(0); //asynclist contains objects of (FTPAsync(map))
if(ftpasynclist.size() > 0){
System.out.println("tlist in post execute+++"+ftplist);
//DownloadFileAsync dfa = new DownloadFileAsync(tlist.get(0));
FTPAsync dfa = (FTPAsync)ftpasynclist.get(0);
dfa.execute();
ftplist.remove(0);
}
else{
startTests();
}
}
else if (PARALLEL_MODE //for parallel mode
&& ftpStopCount <ftpasynclist.size()
&& testRunning) {
System.out.println("stopCount before condition= " +ftpStopCount);
if (ftpStopCount == ftpasynclist.size() -1 && testRunning) {
System.out.println("stopCount inside 1st condition= " + ftpStopCount);
ftpStopCount = 0;
// stopTests(0);
startTests();
System.out.println("Tests Started");
}
else {
ftpStopCount++;
System.out.println("stopCount after increment = " + ftpStopCount);
;
}
}
}
catch (Exception ed) {
ed.printStackTrace();
go.setText(R.string.go);
//testRunning = false;
}
super.onPostExecute(unused);
}
private void updateUI(final TextView tv, final String str) {
runOnUiThread(new Runnable() {
public void run() {
tv.setText(str);
}
});
}
private void updateUI(final ImageView iv, final int id) { // may create problem
runOnUiThread(new Runnable() {
public void run() {
iv.setImageResource(id);
}
});
}
public void gotosleep(boolean val) {
sleep1 = val;
}
public boolean areYouSleeping() {
return sleep1;
}
}