Search Results

Search found 655 results on 27 pages for 'synchronized'.

Page 9/27 | < Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • LED 49-unit Quadcopter Formation Foreshadows The Robot Takeover

    - by Jason Fitzpatrick
    Perhaps there are a few more steps between 49 semi-autonomous quadcopters doing a little aerial dancing and Skynet, but we’re awed and apprehensive at the same time. Check out the video to see them in action. The video comes to us courtesy of a German art conference, Ars Electronica, and a colloboration between two design groups Futurelab and Ascending Technologies GmbH. The above video is just their warmup routine; according to YouTube comments they’ll be uploading even more videos of the quadcopters and their synchronized night flights in the coming days. [via Motherboard] HTG Explains: Is ReadyBoost Worth Using? HTG Explains: What The Windows Event Viewer Is and How You Can Use It HTG Explains: How Windows Uses The Task Scheduler for System Tasks

    Read the article

  • How to write a network game? [closed]

    - by Tom Wijsman
    Based on Why is so hard to develop a MMO?: Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise. I know the theory about sockets, servers, clients, protocols, connections and such things. Now I wonder how one can learn to write a network game: How to balance load problems? How to manage the game state? How to keep things synchronized? How to protect the communication and client from reverse engineering? How to work around latency problems? Which things should be computed local and which things on the server? ... Are there any good books, tutorials, sites, interesting articles or other questions regarding this? I'm looking for broad answers, but specific ones are fine too to learn the difference.

    Read the article

  • Is true multithreading really necessary?

    - by Jonathan Graef
    So yeah, I'm creating a programming language. And the language allows multiple threads. But, all threads are synchronized with a global interpreter lock, which means only one thread is allowed to execute at a time. The only way to get the threads to switch off is to explicitly tell the current thread to wait, which allows another thread to execute. Parallel processing is of course possible by spawning multiple processes, but the variables and objects in one process cannot be accessed from another. However the language does have a fairly efficient IPC interface for communicating between processes. My question is: Would there ever be a reason to have multiple, unsynchronized threads within a single process (thus circumventing the GIL)? Why not just put thread.wait() statements in key positions in the program logic (presuming thread.wait() isn't a CPU hog, of course)? I understand that certain other languages that use a GIL have processor scheduling issues (cough Python), but they have all been resolved.

    Read the article

  • Why should most logic be in the monitor objects and not in the thread objects when writing concurrent software in Java?

    - by refuser
    When I took the Realtime and Concurrent programming course our lecturer told us that when writing concurrent programs in Java and using monitors, most of the logic should be in the monitor and as little as possible in the threads that access it. I never really understood why and I really would like to. Let me clarify. In this particular case we had several classes. Lift extends Thread Person extends Thread LiftView Monitor, all methods synchronized. This is nothing we came up with, our task was to implement a lift simulation with persons waiting on different floors, and theses were the class skeletons that were given. Then our lecturer said to implement most of the logic in the monitor (he was talking about class Monitor as THE monitor) and as little as possible in the threads. Why would he make a statement like that?

    Read the article

  • How to Move Your Google Authenticator Credentials to a New Android Phone or Tablet

    - by Chris Hoffman
    Most of the app data on your Android is probably synced online will automatically sync to a new phone or tablet. However, your Google Authenticator credentials won’t — they aren’t synchronized for obvious security reasons. If you’re doing a factory reset, getting a new phone, or just want to copy your credentials to second device, these steps will help you move your authenticator data over so you won’t lose your access codes. How to Factory Reset Your Android Phone or Tablet When It Won’t Boot Our Geek Trivia App for Windows 8 is Now Available Everywhere How To Boot Your Android Phone or Tablet Into Safe Mode

    Read the article

  • Healthcare Mobile Database Synchronization Demonstration

    - by Jim Connors
    Like many of you, I learn best by getting my hands dirty.  When confronted with the task of understanding a new set of products and technologies and figuring out how they might apply to a vertical industry like healthcare, I set out to create a demonstration.  The video that follows aims to show how the Oracle embedded software portfolio can be applied to a healthcare application.  The demonstration utilizes among others, Java SE Embedded, Berkeley DB, Apache Tomcat, Oracle 11gR2 and Oracle Database Mobile Server. Eric Jensen gives a great critique and description of the demo here.  To sum it up, we aim to show how live medical data can be collected on a medical device, stored in a local database, synchronized to a master database and furthermore propagated to a mobile phone (Android) application.  Come take a look!

    Read the article

  • How to write a network game?

    - by TomWij
    Based on Why is so hard to develop a MMO?: Networked game development is not trivial; there are large obstacles to overcome in not only latency, but cheat prevention, state management and load balancing. If you're not experienced with writing a networked game, this is going to be a difficult learning exercise. I know the theory about sockets, servers, clients, protocols, connections and such things. Now I wonder how one can learn to write a network game: How to balance load problems? How to manage the game state? How to keep things synchronized? How to protect the communication and client from reverse engineering? How to work around latency problems? Which things should be computed local and which things on the server? ... Are there any good books, tutorials, sites, interesting articles or other questions regarding this? I'm looking for broad answers, but specific ones are fine too to learn the difference.

    Read the article

  • Scrum Board for a distributed team

    - by Falcon
    I am looking for recommendations on a digital Scrum Board which can be shared over the internet. I imagine something like a big tablet on which you can draw and which remote users can access, too. I dislike Scrum software because I think one major benefit of a Scrum Board is its physical presence. It should be hard to ignore. The best solution would be two big tablets on which you can draw and which can be synchronized. Has anyone got product recommendations for something like this? Or would you rather use a software? Kind regards, Falcon

    Read the article

  • Why Ubuntu One pretends to sychronize files, but it doesn't?

    - by Tom Brito
    I have my Ubuntu One account configured in both Ubuntu 11.10 and iOS (ipod-touch). The photos from the iOS were successfully uploaded, but in Ubuntu One, although it shows the "syncing" and "synchronized" marks over the icons, the files are not showing in the website (one.ubuntu.com). In short: My files are not showing in the Ubuntu One website, although the icons have the "uploaded" mark. Any idea what can be wrong here? obs1: Also, not sure if it's related, the icon-marks will show only when I open the Ubuntu One Control Panel. It shows the message "file was uploaded", but there's nothing online. obs2: The folder I'm trying to synchronize is 30mb size. And my connection is 8mbps.

    Read the article

  • What's the current best practice for C multithreading?

    - by Dexter
    I've been a Java (and PHP) developer for most of my life, but will need to use C for my next project. I remember some basic stuff we did back in school with fork, pthread, semaphores, etc. but I'm not sure if that's still the "way to go" here, or if there have been any recent developments/improvements etc. Google's results seem to be fairly dated. Or does that just mean that this is still the current "state of the art"? Or will I have to use a (system-independent) libary like glib if I want higher-level abstractions, like synchronized queues? What other libraries are there? (The programm will only have to run on Linux though)

    Read the article

  • How should I determine direction from a phone's orientation & accelerometer?

    - by Manoj Kumar
    I have an Android application which moves a ball based on the orientation of the phone. I've been using the following code to extract the data - but how do I use it to determine what direction the ball should actually travel in? public void onSensorChanged(int sensor, float[] values) { // TODO Auto-generated method stub synchronized (this) { Log.d("HIIIII :- ", "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]); if (sensor == SensorManager.SENSOR_ORIENTATION) { System.out.println("Orientation X: " + values[0]); System.out.println("Orientation Y: " + values[1]); System.out.println("Orientation Z: " + values[2]); } if (sensor == SensorManager.SENSOR_ACCELEROMETER) { System.out.println("Accel X: " + values[0]); System.out.println("Accel Y: " + values[1]); System.out.println("Accel Z: " + values[2]); } } }

    Read the article

  • Coherence Data Guarantees for Data Reads - Basic Terminology

    - by jpurdy
    When integrating Coherence into applications, each application has its own set of requirements with respect to data integrity guarantees. Developers often describe these requirements using expressions like "avoiding dirty reads" or "making sure that updates are transactional", but we often find that even in a small group of people, there may be a wide range of opinions as to what these terms mean. This may simply be due to a lack of familiarity, but given that Coherence sits at an intersection of several (mostly) unrelated fields, it may be a matter of conflicting vocabularies (e.g. "consistency" is similar but different in transaction processing versus multi-threaded programming). Since almost all data read consistency issues are related to the concept of concurrency, it is helpful to start with a definition of that, or rather what it means for two operations to be concurrent. Rather than implying that they occur "at the same time", concurrency is a slightly weaker statement -- it simply means that it can't be proven that one event precedes (or follows) the other. As an example, in a Coherence application, if two client members mutate two different cache entries sitting on two different cache servers at roughly the same time, it is likely that one update will precede the other by a significant amount of time (say 0.1ms). However, since there is no guarantee that all four members have their clocks perfectly synchronized, and there is no way to precisely measure the time it takes to send a given message between any two members (that have differing clocks), we consider these to be concurrent operations since we can not (easily) prove otherwise. So this leads to a question that we hear quite frequently: "Are the contents of the near cache always synchronized with the underlying distributed cache?". It's easy to see that if an update on a cache server results in a message being sent to each near cache, and then that near cache being updated that there is a window where the contents are different. However, this is irrelevant, since even if the application reads directly from the distributed cache, another thread update the cache before the read is returned to the application. Even if no other member modifies a cache entry prior to the local near cache entry being updated (and subsequently read), the purpose of reading a cache entry is to do something with the result, usually either displaying for consumption by a human, or by updating the entry based on the current state of the entry. In the former case, it's clear that if the data is updated faster than a human can perceive, then there is no problem (and in many cases this can be relaxed even further). For the latter case, the application must assume that the value might potentially be updated before it has a chance to update it. This almost aways the case with read-only caches, and the solution is the traditional optimistic transaction pattern, which requires the application to explicitly state what assumptions it made about the old value of the cache entry. If the application doesn't want to bother stating those assumptions, it is free to lock the cache entry prior to reading it, ensuring that no other threads will mutate the entry, a pessimistic approach. The optimistic approach relies on what is sometimes called a "fuzzy read". In other words, the application assumes that the read should be correct, but it also acknowledges that it might not be. (I use the qualifier "sometimes" because in some writings, "fuzzy read" indicates the situation where the application actually sees an original value and then later sees an updated value within the same transaction -- however, both definitions are roughly equivalent from an application design perspective). If the read is not correct it is called a "stale read". Going back to the definition of concurrency, it may seem difficult to precisely define a stale read, but the practical way of detecting a stale read is that is will cause the encompassing transaction to roll back if it tries to update that value. The pessimistic approach relies on a "coherent read", a guarantee that the value returned is not only the same as the primary copy of that value, but also that it will remain that way. In most cases this can be used interchangeably with "repeatable read" (though that term has additional implications when used in the context of a database system). In none of cases above is it possible for the application to perform a "dirty read". A dirty read occurs when the application reads a piece of data that was never committed. In practice the only way this can occur is with multi-phase updates such as transactions, where a value may be temporarily update but then withdrawn when a transaction is rolled back. If another thread sees that value prior to the rollback, it is a dirty read. If an application uses optimistic transactions, dirty reads will merely result in a lack of forward progress (this is actually one of the main risks of dirty reads -- they can be chained and potentially cause cascading rollbacks). The concepts of dirty reads, fuzzy reads, stale reads and coherent reads are able to describe the vast majority of requirements that we see in the field. However, the important thing is to define the terms used to define requirements. A quick web search for each of the terms in this article will show multiple meanings, so I've selected what are generally the most common variations, but it never hurts to state each definition explicitly if they are critical to the success of a project (many applications have sufficiently loose requirements that precise terminology can be avoided).

    Read the article

  • Ubuntu One pretends to sychronize files, but it doesn't

    - by Tom Brito
    I have my Ubuntu One account configured in both Ubuntu 11.10 and iOS (ipod-touch). The photos from the iOS were successfully uploaded, but in Ubuntu One, although it shows the "syncing" and "synchronized" marks over the icons, the files are not showing in the website (one.ubuntu.com). In short: My files are not showing in the Ubuntu One website, although the icons have the "uploaded" mark. Any idea what can be wrong here? obs1: Also, not sure if it's related, the icon-marks will show only when I open the Ubuntu One Control Panel. It shows the message "file was uploaded", but there's nothing online. obs2: The folder I'm trying to synchronize is 30mb size. And my connection is 8mbps.

    Read the article

  • Can a local multiplayer iOS game display differently for each device?

    - by Rahil627
    I've seen games which display different data for two devices, but not more than two. If possible, can it be accomplished using GameKit? EDIT: More specifically, I was thinking local multiplayer via bluetooth or wi-fi on an iOS device. Most games I've seen display the same screen synchronized across all of the devices. I understand games that network across the internet do this, often using a server, but I haven't seen any examples of a 3+ device local multiplayer iOS game. I just want to make sure it wasn't some kind of limitation.

    Read the article

  • Is there a way to develop desktop software using PHP?

    - by user1492018
    I have to develop a real estate marketing CRM software for my client - where the application is installed on desktop but can also be accessed from web. 2 reasons why they want the application to run from desktop : So that it can work with/without internet connection They don't want their complete data to be online They want to access few of the data like property listing & inquiries (managed from desktop application) from their website through secure login & password. The data that is entered in desktop application should be automatically synchronized with the website application. I was wondering if there is a way to develop this kind of software using PHP & MySQL. If yes, it will be great if anyone can provide me the referral link.Else please suggest, which language should I use.

    Read the article

  • What are general guidelines and advices to estimate how much you should charge for a project, being a novice freelancer?

    - by Dokkat
    I am an experienced programmer but completely new to the market. Someone wants me to do a project for them, but I do not know how much it is worth. What are general guidelines/advices for finding what a project is worth on the market? If I can ask here about this particular one, it is a HTML5 site with a login/register form and a video player that has to play a lecture video and powerpoint slides synchronized. They'll give me the video, the audio the powerpoints. I should also do some editting on the video before.

    Read the article

  • How do I disable auto-away for online presence?

    - by Will
    I am using Natty with with classic GNOME desktop. I use Empathy and sometimes Skype. Both these get the online state from the system itself somehow. If I don't touch my keyboard for a few minutes - even when watching a YouTube clip or something - the inactivity triggers an auto-away state on my messaging apps. It's synchronized so I imagine its coming coordinated from the system, and not the two apps making the same decision individually. How can I disable this? I want manual control - I'm only away when I set it to away in a messaging app.

    Read the article

  • Android: Using onStart() method in Bluetooth application

    - by Nii
    Hello, I am getting a nullpointer exception when my onStart() method is called. Here is the breakdown of my Android app: Opening the app brings a user to the homescreen: The user is then presented with the first 6 icons to choose from. When the user presses the "Sugar" icon it takes them to the SugarTabActivity. The SugarTabActivity is a Tabbed layout with two tabs. I'm concerned with the first tab. The first tab calls the getDefaultAdapter() method in its onCreate() method. Once it calls this, it checks if the bluetooth adapter is null on the phone, and if its null it shows a toast saying "Bluetooth is not available". This works just fine. Then I call the onStart() method. In the onStart() method I check if bluetooth is enabled, and if it isnt, then I start a new activity from the BluetoothAdapter enable bluetooth intent; otherwise, I start my bluetooth service. The exact error I'm getting is 04-19 00:44:45.674: ERROR/AndroidRuntime(225): Caused by: java.lang.NullPointerException 04-19 00:44:45.674: ERROR/AndroidRuntime(225): at com.nii.glucose.Glucose.onStart(Glucose.java:313). Heading Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if(D) Log.d(TAG, "+++ ON CREATE +++"); setContentView(R.layout.glucose_layout); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter==null){ Toast.makeText(this, "Bluetooth not available", Toast.LENGTH_LONG).show(); //finish(); return; } } Override public void onStart() { super.onStart(); if(D) Log.e(TAG, "++ ON START ++"); // If BT is not on, request that it be enabled. // setupChat() will then be called during onActivityResult if (!mBluetoothAdapter.isEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); // Otherwise, setup the chat session } else { if (mGlucoseService == null) mGlucoseService = new BluetoothService(this, mHandler); } } @Override public synchronized void onResume(){ super.onResume(); if(D) Log.e(TAG,"==== ON RESUME ======"); // Performing this check in onResume() covers the case in which BT was // not enabled during onStart(), so we were paused to enable it... // onResume() will be called when ACTION_REQUEST_ENABLE activity returns. if (mGlucoseService != null) { // Only if the state is STATE_NONE, do we know that we haven't started already if (mGlucoseService.getState() == BluetoothService.STATE_NONE) { // Start the Bluetooth chat services mGlucoseService.start(); } } } @Override public synchronized void onPause(){ super.onPause(); //isActive.set(false); if(D) Log.e(TAG,"==== ON PAUSE ======"); } @Override public void onDestroy() { super.onDestroy(); // Stop the Bluetooth chat services if (mGlucoseService != null) mGlucoseService.stop(); if(D) Log.e(TAG, "--- ON DESTROY ---"); }

    Read the article

  • Java Copy/Paste org.w3c.dom.Node between two running copies of the same program

    - by Jay
    I have a program that shows a tree representation of an XML file. Using a number of sources online I have Copy/Paste within a single instance of the program working. I am using the system Clipboard. What I need though is to be able to copy a node from one instance of the program and paste to a different instance of the same program. I have tried a number of different options, all resulting in the same behavior. When pasting from within the same application the clipboardContent contains a "transferable" object with the correct data along with an isLocal set to "true". When I perform the copy and then attempt the paste from another instance of the same program running the clipboardContent contains a "flavorsToData" HashMap and "flavors" values, the check for isDataFlavorSupported fails (never hits my custom class that represents the new flavor). I have tried using different values for the requestor object in the getContents() call. Likewise I have tried a few different ClipboardOwners for the setContent() call. Neither seem to change the behavior in any way. I am sorely tempted to convert the node that is being copied back into a textual XML format, and then on the paste convert back to the DOM model, but would rather not if possible. This class is used to define the DataFlavor and transferable object: import java.awt.datatransfer.*; import org.w3c.dom.Node; public class NodeCopyPaste implements Transferable { static public DataFlavor NodeFlavor; private DataFlavor [] supportedFlavors = {NodeFlavor}; public Node aNode; public NodeCopyPaste (Node paraNode) { aNode = paraNode; try { NodeFlavor = new DataFlavor (Class.forName ("org.w3c.dom.Node"), "Node"); } catch (ClassNotFoundException e) { e.printStackTrace (); } } public synchronized DataFlavor [] getTransferDataFlavors () { return (supportedFlavors); } public boolean isDataFlavorSupported (DataFlavor nodeFlavor) { return (nodeFlavor.equals (NodeFlavor)); } public synchronized Object getTransferData (DataFlavor nFlavor) throws UnsupportedFlavorException { if (nFlavor.equals (NodeFlavor)) return (this); else throw new UnsupportedFlavorException (nFlavor); } public void lostOwnership (Clipboard parClipboard, Transferable parTransferable) { } } I define a Clipboard object from the main application screen and then tie in copy and paste handlers for the mouse clicks: During initialization I assign the system clipboard: clippy = Toolkit.getDefaultToolkit().getSystemClipboard(); Copy Handler Node copyNode = ((CLIInfo) node.getUserObject()).DOMNode.cloneNode(true); NodeCopyPaste contents = new NodeCopyPaste(copyNode); clippy.setContents (contents, null); Paste Handler Transferable clipboardContent = clippy.getContents (null); Node clonedNode = null; if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported (NodeCopyPaste.NodeFlavor))) { try { NodeCopyPaste tempNCP = (NodeCopyPaste) clipboardContent.getTransferData (NodeCopyPaste.NodeFlavor); clonedNode = tempNCP.aNode.cloneNode(true); } catch (Exception e) { e.printStackTrace (); } Thanks!

    Read the article

  • How to run concurrency unit test?

    - by janetsmith
    Hi, How to use junit to run concurrency test? Let's say I have a class public class MessageBoard { public synchronized void postMessage(String message) { .... } public void updateMessage(Long id, String message) { .... } } I wan to test multiple access to this postMessage concurrently. Any advice on this? I wish to run this kind of concurrency test against all my setter functions (or any methodn that involves create/update/delete operation). Thanks

    Read the article

  • How to protect critical section in PHP?

    - by Morgan Cheng
    I did some search about this topic but found nothing valuable. If I don't use PHP default session handler, there is no session lock at request level. So, I have to protect critical section by myself. In Java, we have synchronized. In C#, we have lock. In PHP, how to do that?

    Read the article

  • Eclipse Plugin that Opens a Command Line in Eclipse

    - by Jonas Laufu
    I'm looking for an Eclipse plug-in that shows a system (independent) command line in a view that is ideally synchronized with the current project's local path. So basically a shell within Eclipse. The reason for this is to be able to execute custom build commands and script faster than specifying them as launch configurations or having to open a command prompt every time I start eclipse.

    Read the article

  • SQL Server: pulling and updating local data

    - by SDReyes
    Hi guys, I have two SQL Server 2008 databases called Anna and Bob. Bob has to pull and transform data from Anna to keep updated his tables. Ideally Bob will be always synchronized with Anna, but some delay would be acceptable. What is the best way to do this? Thanks in advance.

    Read the article

  • Thread safety in Singleton

    - by Robert
    I understand that double locking in Java is broken, so what are the best ways to make Singletons Thread Safe in Java? The first thing that springs to my mind is: class Singleton{ private static Singleton instance; private Singleton(){} public static synchronized Singleton getInstance(){ if(instance == null) instance = new Singleton(); return instance; } } Does this work? if so, is it the best way (I guess that depends on circumstances, so stating when a particular technique is best, would be useful)

    Read the article

  • Out of memory exception during scrolling of listview

    - by user1761316
    I am using facebook data like postedpicture,profile picture,name,message in my listview.I am getting an OOM error while doing fast scrolling of listview. I am also having scrollviewlistener in my application that loads more data when the scrollbar reaches the bottom of the screen.I just want to know whether I need to change anything in this class. imageLoader.DisplayImage(postimage.get(position).replace(" ", "%20"), postimg) ; I am using the above line to call the method in this imageloader class to set the bitmap to imageview. Here is my imageloader class import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.Collections; import java.util.Map; import java.util.Stack; import java.util.WeakHashMap; import com.stellent.beerbro.Wall; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.util.Log; import android.widget.ImageView; public class ImageLoader { MemoryCache memoryCache=new MemoryCache(); FileCache fileCache; private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>()); public ImageLoader(Context context){ //Make the background thead low priority. This way it will not affect the UI performance photoLoaderThread.setPriority(Thread.NORM_PRIORITY-1); fileCache=new FileCache(context); } // final int stub_id=R.drawable.stub; public void DisplayImage(String url,ImageView imageView) { imageViews.put(imageView, url); System.gc(); // Bitmap bitmap=createScaledBitmap(memoryCache.get(url), 100,100,0); Bitmap bitmap=memoryCache.get(url); // Bitmap bitmaps=bitmap.createScaledBitmap(bitmap, 0, 100, 100); if(bitmap!=null) { imageView.setBackgroundDrawable(new BitmapDrawable(bitmap)); // imageView.setImageBitmap(getRoundedCornerBitmap( bitmap, 10,70,70)); // imageView.setImageBitmap(bitmap); // Log.v("first", "first"); } else { queuePhoto(url, imageView); // Log.v("second", "second"); } } private Bitmap createScaledBitmap(Bitmap bitmap, int i, int j, int k) { // TODO Auto-generated method stub return null; } private void queuePhoto(String url, ImageView imageView) { //This ImageView may be used for other images before. So there may be some old tasks in the queue. We need to discard them. photosQueue.Clean(imageView); PhotoToLoad p=new PhotoToLoad(url, imageView); synchronized(photosQueue.photosToLoad){ photosQueue.photosToLoad.push(p); photosQueue.photosToLoad.notifyAll(); } //start thread if it's not started yet if(photoLoaderThread.getState()==Thread.State.NEW) photoLoaderThread.start(); } public Bitmap getBitmap(String url) { File f=fileCache.getFile(url); //from SD cache Bitmap b = decodeFile(f); if(b!=null) return b; //from web try { Bitmap bitmap=null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); InputStream is=conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); bitmap = decodeFile(f); return bitmap; } catch (Exception ex){ ex.printStackTrace(); return null; } }//Lalit //decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f){ try { //decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeStream(new FileInputStream(f),null,o); //Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE=Wall.width; final int REQUIRED_SIZE1=Wall.height; // final int REQUIRED_SIZE=250; // int width_tmp=o.outWidth, height_tmp=o.outHeight; int scale=1; // while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE) //// scale*=2; while(true){ if(width_tmp/2<REQUIRED_SIZE && height_tmp/2<REQUIRED_SIZE1) break; width_tmp/=2; height_tmp/=2; scale*=2; } //decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize=scale; // o2.inSampleSize=2; return BitmapFactory.decodeStream(new FileInputStream(f), null, o2); } catch (FileNotFoundException e) {} return null; } //Task for the queue private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i){ url=u; imageView=i; } } PhotosQueue photosQueue=new PhotosQueue(); public void stopThread() { photoLoaderThread.interrupt(); } //stores list of photos to download class PhotosQueue { private Stack<PhotoToLoad> photosToLoad=new Stack<PhotoToLoad>(); //removes all instances of this ImageView public void Clean(ImageView image) { for(int j=0 ;j<photosToLoad.size();){ if(photosToLoad.get(j).imageView==image) photosToLoad.remove(j); else ++j; } } } class PhotosLoader extends Thread { public void run() { try { while(true) { //thread waits until there are any images to load in the queue if(photosQueue.photosToLoad.size()==0) synchronized(photosQueue.photosToLoad){ photosQueue.photosToLoad.wait(); } if(photosQueue.photosToLoad.size()!=0) { PhotoToLoad photoToLoad; synchronized(photosQueue.photosToLoad){ photoToLoad=photosQueue.photosToLoad.pop(); } Bitmap bmp=getBitmap(photoToLoad.url); memoryCache.put(photoToLoad.url, bmp); String tag=imageViews.get(photoToLoad.imageView); if(tag!=null && tag.equals(photoToLoad.url)){ BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad.imageView); Activity a=(Activity)photoToLoad.imageView.getContext(); a.runOnUiThread(bd); } } if(Thread.interrupted()) break; } } catch (InterruptedException e) { //allow thread to exit } } } PhotosLoader photoLoaderThread=new PhotosLoader(); //Used to display bitmap in the UI thread class BitmapDisplayer implements Runnable { Bitmap bitmap; ImageView imageView; public BitmapDisplayer(Bitmap b, ImageView i){bitmap=b;imageView=i;} public void run() { if(bitmap!=null) imageView.setBackgroundDrawable(new BitmapDrawable(bitmap)); } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels,int width,int height) { Bitmap output = Bitmap.createBitmap(width,height, Config.ARGB_8888); Canvas canvas = new Canvas(output); final int color = 0xff424242; final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(rect); final float roundPx = pixels; paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13 14 15 16  | Next Page >