Search Results

Search found 514 results on 21 pages for 'runnable'.

Page 7/21 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • How to apply a filter to the screen of a running program?

    - by Shahbaz
    The idea is to take old games without modifying them, but have the graphics card apply a series of filters to their output before sending them to the monitor. A very crude example would be to take a game that has a resolution of 640x480 and do: Increase the resolution to 1280x960 Apply a blur (low pass filter) Apply a sharpen (1 + high pass filter) These steps may not necessarily be the best to improve the visuals of an old game, but there are a lot of techniques that are well-known in image processing for this purpose. The question is, do the (NVidia) graphics cards give the ability to load a program that modifies the screen before sending it to the monitor? If so, how are they called and what terminology should I use to search? I would be comfortable with doing the programming myself if this ability is part of a library. Also, would the solution be different between Windows and Linux? If so, either is fine, since most of the games are probably runnable by wine.

    Read the article

  • Invoking JavaScript from Java

    - by Geertjan
    Here's an Action class defined in Java. The Action class executes a script via the JavaFX WebEngine: @NbBundle.Messages("CTL_AddBananasAction=Add Banana") private class AddBananasAction extends AbstractAction { public AddBananasAction() { super(Bundle.CTL_AddBananasAction()); } @Override public void actionPerformed(ActionEvent e) { Platform.runLater(new Runnable() { @Override public void run() { webengine.executeScript("addBanana(' " + newBanana + " ') "); } }); } }How does the 'executescript' call know where to find the JavaScript file? Well, earlier in the code, the WebEngine loaded an HTML file, where the JavaScript file was registered: WebView view = new WebView(); view.setMinSize(widthDouble, heightDouble); view.setPrefSize(widthDouble, heightDouble); webengine = view.getEngine(); URL url = getClass().getResource("home.html"); webengine.load(url.toExternalForm()); Finally, here's a skeleton 'addBanana' method, which is invoked via the Action class shown above: function addBanana(user){ statustext.text(user); } By the way, if you have your JavaScript and CSS embedded within your HTML file, the code navigator combines all three into the same window, which is kind of cool:

    Read the article

  • Image rotation algorithm

    - by Stefano Driussi
    I'm looking for an algorithm that rotates an image by some degrees (input). public Image rotateImage(Image image, int degrees) (Image instances could be replaced with int[] containing each pixel RGB values, My problem is that i need to implement it for a JavaME MIDP 2.0 project so i must use code runnable on JVM prior to version 1.5 Can anyone help me out with this ? EDIT: I forgot to mention that i don't have SVG APIs available and that i need a method to rotate by arbitrary degree other than 90 - 180- 270 Also, no java.awt.* packages are available on MIDP 2.0

    Read the article

  • Where to stop/destroy threads in Android Service class?

    - by niko
    Hi, I have created a threaded service the following way: public class TCPClientService extends Service{ ... @Override public void onCreate() { ... Measurements = new LinkedList<String>(); enableDataSending(); } @Override public IBinder onBind(Intent intent) { //TODO: Replace with service binding implementation return null; } @Override public void onLowMemory() { Measurements.clear(); super.onLowMemory(); }; @Override public void onDestroy() { Measurements.clear(); super.onDestroy(); try { SendDataThread.stop(); } catch(Exception e) { } }; private Runnable backgrounSendData = new Runnable() { public void run() { doSendData(); } }; private void enableDataSending() { SendDataThread = new Thread(null, backgrounSendData, "send_data"); SendDataThread.start(); } private void addMeasurementToQueue() { if(Measurements.size() <= 100) { String measurement = packData(); Measurements.add(measurement); } } private void doSendData() { while(true) { try { if(Measurements.isEmpty()) { Thread.sleep(1000); continue; } //Log.d("TCP", "C: Connecting..."); Socket socket = new Socket(); socket.setTcpNoDelay(true); socket.connect(new InetSocketAddress(serverAddress, portNumber), 3000); //socket.connect(new InetSocketAddress(serverAddress, portNumber)); if(!socket.isConnected()) { throw new Exception("Server Unavailable!"); } try { //Log.d("TCP", "C: Sending: '" + message + "'"); PrintWriter out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); String message = Measurements.remove(); out.println(message); Thread.sleep(200); Log.d("TCP", "C: Sent."); Log.d("TCP", "C: Done."); connectionAvailable = true; } catch(Exception e) { Log.e("TCP", "S: Error", e); connectionAvailable = false; } finally { socket.close(); announceNetworkAvailability(connectionAvailable); } } catch (Exception e) { Log.e("TCP", "C: Error", e); connectionAvailable = false; announceNetworkAvailability(connectionAvailable); } } } } After I close the application the phone works really slow and I guess it is due to thread termination failure. Does anyone know what is the best way to terminate all threads before terminating the application?

    Read the article

  • Android - openOptionsMenu doesn't work in onCreate

    - by kape123
    Is there any other way to call openOptionsMenu after activity is displayed without using something like this: new Handler().postDelayed(new Runnable() { public void run() { openOptionsMenu(); } }, 1000); Reference: http://groups.google.com/group/android-beginners/browse_frm/thread/b10a8ea840c07725/1ce48bb147a3ed1a?#1ce48bb147a3ed1a

    Read the article

  • Run bat file in Java and wait 2

    - by Savvas Dalkitsis
    This is a followup question to my other question : http://stackoverflow.com/questions/2434125/run-bat-file-in-java-and-wait The reason i am posting this as a separate question is that the one i already asked was answered correctly. From some research i did my problem is unique to my case so i decided to create a new question. Please go read that question before continuing with this one as they are closely related. Running the proposed code blocks the program at the waitFor invocation. After some research i found that the waitFor method blocks if your process has output that needs to be proccessed so you should first empty the output stream and the error stream. I did those things but my method still blocks. I then found a suggestion to simply loop while waiting the exitValue method to return the exit value of the process and handle the exception thrown if it is not, pausing for a brief moment as well so as not to consume all the CPU. I did this: import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Test { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec( "cmd /k start SQLScriptsToRun.bat" + " -UuserName -Ppassword" + " projectName"); final BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); final BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream())); new Thread(new Runnable() { @Override public void run() { try { while (input.readLine()!=null) {} } catch (IOException e) { e.printStackTrace(); } } }).start(); new Thread(new Runnable() { @Override public void run() { try { while (error.readLine()!=null) {} } catch (IOException e) { e.printStackTrace(); } } }).start(); int i = 0; boolean finished = false; while (!finished) { try { i = p.exitValue(); finished = true; } catch (IllegalThreadStateException e) { e.printStackTrace(); try { Thread.sleep(500); } catch (InterruptedException e1) { e1.printStackTrace(); } } } System.out.println(i); } catch (IOException e) { e.printStackTrace(); } } } but my process will not end! I keep getting this error: java.lang.IllegalThreadStateException: process has not exited Any ideas as to why my process will not exit? Or do you have any libraries to suggest that handle executing batch files properly and wait until the execution is finished?

    Read the article

  • Java ExecutorService java heap space ptoblems

    - by Sergey Aganezov jr
    I have a little bit of a problem in a multitasking java department. I have a class, called public class ThreadWorker implements Runnable { //some code in here public void run(){ // invokes some recursion method in the ThreadWorker itself, // which will stop eventually { } all in all, pretty simple "worker" that can work on it's on. To work with threads I'm using public static int THREAD_NUMBER = 4; public static ExecutorServide es = Executors.newFixedThreadPool(THREAD_NUMBER); adding instances of ThreadWroker class happens here: public void recursiveMethod(Arraylist<Integers> elements, MyClass data){ if (elements.size() == 0 && data.qualifies()){ ThreadWorker tw = new ThreadWorker(data); es.execute(tw); return; } for (int i=0; i< elements.size(); i++){ // some code to prevent my problem MyClass data1 = new MyClass(data); MyClass data2 = new MyClass(data); ArrayList<Integer> newElements = (ArrayList<Integer>)elements.clone(); data1.update(elements.get(i)); data2.update(-1 * elements.get(i)); newElements.remove(i); recursiveMethod(newElements, data1); recursiveMethod(newElements, data2); { } and the problem is that the depth of the recursion tree is quite big, so as it's width, so a lot of ThreadWorkers are added to the ExecutorService, so after some time on the big input a get Exception in thread "pool-1-thread-2" java.lang.OutOfMemoryError: Java heap space which is caused, as I think because of a ginormous number of ThreadWorkers i'm adding to ExecutorSirvice to be executed, so it runs out of memory. Every ThreadWorker takes about 40 Mb of RAM for all it needs. Is there a method to get how many threads (instances of classes implementing runnable interface) have been added to ExecutorService? So I can add it in the shown above code (int the " // some code to prevent my problem"), as while ("number of threads in the ExecutorService" > 10){ Thread.sleep(10000); } so I won't go to deep or to broad with my recursion and prevent those exception-throwing situations. Sincerely, Sergey Aganezov jr.

    Read the article

  • Java JFrame EventQueue

    - by asmo
    In Java, to create and show a new JFrame, I simply do this: public static void main(String[] args) { new JFrame().setVisible(true); } However, I saw many people doing it like this: public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { new JFrame().setVisible(true); } }); } Why? Are there any advantages?

    Read the article

  • Strange groovy behavior when dealing with threads

    - by Misha Koshelev
    Dear All: I have an interesting dilemma. If I define my class as: class Browser { def swtException protected Object evaluate(script) throws SWTException { swtException=null display.syncExec() { try { result=swtBrowser.evaluate(script) } catch (SWTException swtException) { Browser.swtException=swtException } } } I get this rather interesting error: Exception in thread "Thread-5" org.eclipse.swt.SWTException: Failed to execute runnable (groovy.lang.MissingPropertyException: No such property: swtException for class : com.mksoft.fbautomate.browser.Browser Possible solutions: swtException) Any ideas??? Thank you! Misha

    Read the article

  • Rsync: pure Ruby implementation?

    - by peter
    I have a Rsync program Deltacopy with an executable as client and server but would like to replace this if possible with a pure Ruby implementation of Rsync. I found gems like six-rsync and rsync-update but they seem to be no general implementations. I'm looking for a pure Ruby solution, so no executables involved and preferably runnable on multiple OS. If possible a simple sample would be great. I only look for Rsync, no other transfer or backup solutions please.

    Read the article

  • Need help with Java Producer Consumer Problem, NullPointerException

    - by absk
    This is my code: package test; import java.util.logging.Level; import java.util.logging.Logger; class Data{ int ar[]=new int[50]; int ptr; Data() { for(int i=0;i<50;i++) ar[i]=0; ptr=0; } public int produce() { if(this.ptr<50) { this.ar[this.ptr]=1; this.ptr++; return this.ptr; } else return -1; } public int consume() { if(this.ptr>0) { this.ar[this.ptr]=0; this.ptr--; return this.ptr; } else return -1; } } class Prod implements Runnable{ private Main m; Prod(Main mm) { m=mm; } public void run() { int r = m.d.produce(); if (r != -1) { System.out.println("Produced, total elements: " + r); } else { try { wait(); } catch (InterruptedException ex) { Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex); } } } } class Cons implements Runnable{ private Main m; Cons(Main mm) { m=mm; } public void run() { int r=m.d.consume(); if(r!=-1) System.out.println("Consumed, total elements: " + r); else { try { wait(); } catch (InterruptedException ex) { Logger.getLogger(Prod.class.getName()).log(Level.SEVERE, null, ex); } } notify(); } } public class Main{ Data d; public static void main(String s[]) throws InterruptedException{ Main m = new Main(); Prod p = new Prod(m); Cons c = new Cons(m); new Thread(p).start(); new Thread(c).start(); } } It is giving following errors: Exception in thread "Thread-0" Exception in thread "Thread-1" java.lang.NullPointerException at test.Cons.run(Main.java:84) at java.lang.Thread.run(Thread.java:619) java.lang.NullPointerException at test.Prod.run(Main.java:58) at java.lang.Thread.run(Thread.java:619) I am new to Java. Any help will be appreciated.

    Read the article

  • java.util.concurrent.ThreadPoolExecutor strange logic

    - by rodrigoap
    Look ath this method of ThreadPoolExcecutor: public void execute(Runnable command) { ... if (runState == RUNNING && workQueue.offer(command)) { if (runState != RUNNING || poolSize == 0) ensureQueuedTaskHandled(command); } ... } It check that runState is RUNNING and then the oposite. As I'm trying to do some tuning on a SEDA like model I wanted to understand the internals of the thread pool. Do you think this code is correct?

    Read the article

  • Scala on the CLR

    - by Michal Bendowski
    The Scala homepage says that Scala 1.4 was runnable on the .NET framework - what is the status of Scala on the CLR now? Is anyone working on it? I think it would make a great GUI tool combined with GTK# and Mono...

    Read the article

  • How can I make this client as a multithread client?

    - by Johanna
    Hi, I have read a lot about multithread client but for this one,I can not make it multithread! would you please help me? public class MainClient implements Runnable{ private static InformationClass info = new InformationClass(); private static Socket c; private static String text; public static String getText() { return text; } public static void setText(String text) { MainClient.text = text; } private static PrintWriter os; private static BufferedReader is; static boolean closed = false; /** * @param args the command line arguments */ public static void main(String[] args) { MainFrame farme = new MainFrame(); farme.setVisible(true); try { c = new Socket("localhost", 5050); os = new PrintWriter(c.getOutputStream(), true); is = new BufferedReader(new InputStreamReader(c.getInputStream())); } catch (UnknownHostException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } } public static void active() { String teXt = MainClient.getText(); System.out.println(teXt); os.println(teXt); try { String line = is.readLine(); System.out.println("Text received: " + line); os.flush(); is.close(); is.close(); c.close(); } catch (IOException ex) { Logger.getLogger(MainClient.class.getName()).log(Level.SEVERE, null, ex); } } } also active method will be called when the client write something on the text area and then clicks on the send button. 2) also i have a question that: in the other class I have this action performed for my send button,does it mean that client is multithread?? private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { new Thread(new Runnable() { @Override public void run() { // This gets run in a background thread String text = jTextArea1.getText(); jTextArea2.append(client.getCurrentName() + " : " + text + "\n"); MainClient.setText(client.getCurrentName() + " : " + text + "\n"); clear(); MainClient.active(); } }).start(); } Last EDIT: this is my active method: public static void active() { String teXt = MainClient.getText(); os.println(teXt); String line = is.readLine(); System.out.println("Text received: " + line); os.flush(); is.close(); is.close(); c.close(); }

    Read the article

  • How does the event dispatch thread work?

    - by Roman
    With the help of people on stackoverflow I was able to get the following working code of the simples GUI countdown (it just displays a window counting down seconds). My main problem with this code is the invokeLater stuff. As far as I understand the invokeLater send a task to the event dispatching thread (EDT) and then the EDT execute this task whenever it "can" (whatever it means). Is it right? To my understanding the code works like that: In the main method we use invokeLater to show the window (showGUI method). In other words, the code displaying the window will be executed in the EDT. In the main method we also start the counter and the counter (by construction) is executed in another thread (so it is not in the event dispatching thread). Right? The counter is executed in a separate thread and periodically it calls updateGUI. The updateGUI is supposed to update GUI. And GUI is working in the EDT. So, updateGUI should also be executed in the EDT. It is why the code for the updateGUI is inclosed in the invokeLater. Is it right? What is not clear to me is why we call the counter from the EDT. Anyway it is not executed in the EDT. It starts immediately a new thread and the counter is executed there. So, why we cannot call the counter in the main method after the invokeLater block? import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.SwingUtilities; public class CountdownNew { static JLabel label; // Method which defines the appearance of the window. public static void showGUI() { JFrame frame = new JFrame("Simple Countdown"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); label = new JLabel("Some Text"); frame.add(label); frame.pack(); frame.setVisible(true); } // Define a new thread in which the countdown is counting down. public static Thread counter = new Thread() { public void run() { for (int i=10; i>0; i=i-1) { updateGUI(i,label); try {Thread.sleep(1000);} catch(InterruptedException e) {}; } } }; // A method which updates GUI (sets a new value of JLabel). private static void updateGUI(final int i, final JLabel label) { SwingUtilities.invokeLater( new Runnable() { public void run() { label.setText("You have " + i + " seconds."); } } ); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { showGUI(); counter.start(); } }); } }

    Read the article

  • difference between thread.start() and executor.submit(thread)

    - by Mrityunjay
    hi, i am facing a problem regarding the thread. I am having a class which implements runnable, and i can use thread.start() method on that class. My question is i have one more class java.util.concurrent.ExecutorService in which i can call executor.submit(thread).. can anyone please tell me what is the difference between thread.start() and executor.submit(thread)...

    Read the article

  • Java Swing: JWindow appears behind all other process windows, and will not disappear

    - by Kim Jong Woo
    I am using JWindow to display my splash screen during the application start up. however it will not appear in front of all windows as it should, and it will not disappear as well. import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JWindow; public class MySplash { public static MySplash INSTANCE; private static JWindow jw; public MySplash(){ createSplash(); } private void createSplash() { jw = new JWindow(); JPanel content = (JPanel) jw.getContentPane(); content.setBackground(Color.white); // Set the window's bounds, centering the window int width = 328; int height = 131; Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screen.width - width) / 2; int y = (screen.height - height) / 2; jw.setBounds(x, y, width, height); // Build the splash screen JLabel label = new JLabel(new ImageIcon("splash.jpg")); JLabel copyrt = new JLabel("SplashScreen Test", JLabel.CENTER); copyrt.setFont(new Font("Sans-Serif", Font.BOLD, 12)); content.add(label, BorderLayout.CENTER); content.add(copyrt, BorderLayout.SOUTH); Color oraRed = new Color(156, 20, 20, 255); content.setBorder(BorderFactory.createLineBorder(oraRed, 0)); } public synchronized static MySplash getInstance(){ if(INSTANCE==null){ INSTANCE = new MySplash(); } return INSTANCE; } public void showSplash(){ jw.setAlwaysOnTop(true); jw.toFront(); jw.setVisible(true); return; } public void hideSplash(){ jw.setAlwaysOnTop(false); jw.toBack(); jw.setVisible(false); return; } } So in my main class which extends JFrame, I call my splash screen by SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { MySplash.getInstance().showSplash(); } }); However, the JWindow appears behind the all open instances of windows on my computer. Hiding the JWindow also doesn't work. SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { MySplash.getInstance().hideSplash(); } });

    Read the article

  • How can i test microphone related application in iPhone?

    - by Ajay Pandey
    i am developing an application in which two users can do voice chat on iPhone via bluetooth.Now that i have initiated the voice chat in my code,i found that iPhone 3 does not have microphone builtin.Does anybody has any idea on how can i test my application.Because if i use external microphone then i'll not be able to connect it to my system and so not be able to test unless my code is completly runnable..... Need quick help.. Thanks in advance....

    Read the article

  • Database Schema Versioning Strategies

    - by Jack Ryan
    I work on a project that uses a reasonably large database, the live version weighing in at somewhere around 60-80GB. The live database is the only real definitive source of our schema, and because of its size duplicating this database is too slow to be done often. This means we have ended up developing our database schema in a pretty ad hoc way, using sql compare to migrate changes from dev dbs to the live system, and only wiping our dev dbs every month or two. I am hoping to get some pointers on how to improve our database development work flow so that we have a little more control. Some things to think about: Currently nobody is really in charge of the database schema, all developers can change it if they need to, though generally these decisions are talked about before they are done. There are stored procedures, functions, and views in the database. These should probably be dumped to files so they can be reloaded on every build. Schema changes should probably be checked in as scripts. We have started to do this recently. However all our scripts must then be numbered (because there may be dependencies between them), and must be re runnable (because our build script currently runs them all in order). This makes them hard to read because they are full of conditionals that check whether tables or columns already exist. This is a step that is often forgotten by developers. Getting a new database should be quick and easy. This is currently a big problem, it takes several hours to get a copy of last nights backup and restore it onto a dev machine. Some mechanism needs to be in place to allow developers to update static data. We have tables that contain data that is never updated through the application, but does potentially need to be changed when we do a new release (often this drives dropdowns). The whole thing needs to be runnable as part of a build script. Are there any tools that can be used to help to do this? Eventually I would like to be at a point where a new DB can be built from scratch without copying any data from the live system. I don't mind writing some scripts to glue all the steps together but each part should be easily editable so that we continue to use it rather than make changes directly on DBs.

    Read the article

  • Swing: How do I run a job from AWT thread, but after a window was layed out?

    - by java.is.for.desktop
    My complete GUI runs inside the AWT thread, because I start the main window using SwingUtilities.invokeAndWait(...). Now I have a JDialog which has just to display a JLabel, which indicates that a certain job is in progress, and close that dialog after the job was finished. The problem is: the label is not displayed. That job seems to be started before JDialog was fully layed-out. When I just let the dialog open without waiting for a job and closing, the label is displayed. The last thing the dialog does in its ctor is setVisible(true). Things such as revalidate(), repaint(), ... don't help either. Even when I start a thread for the monitored job, and wait for it using someThread.join() it doesn't help, because the current thread (which is the AWT thread) is blocked by join, I guess. Replacing JDialog with JFrame doesn't help either. So, is the concept wrong in general? Or can I manage it to do certain job after it is ensured that a JDialog (or JFrame) is fully layed-out? Simplified algorithm of what I'm trying to achieve: Create a subclass of JDialog Ensure that it and its contents are fully layed-out Start a process and wait for it to finish (threaded or not, doesn't matter) Close the dialog I managed to write a reproducible test case: EDIT Problem from an answer is now addressed: This use case does display the label, but it fails to close after the "simulated process", because of dialog's modality. import java.awt.*; import javax.swing.*; public class _DialogTest2 { public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(new Runnable() { final JLabel jLabel = new JLabel("Please wait..."); @Override public void run() { JFrame myFrame = new JFrame("Main frame"); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(750, 500); myFrame.setLocationRelativeTo(null); myFrame.setVisible(true); JDialog d = new JDialog(myFrame, "I'm waiting"); d.setModalityType(Dialog.ModalityType.APPLICATION_MODAL); d.add(jLabel); d.setSize(300, 200); d.setLocationRelativeTo(null); d.setVisible(true); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { Thread.sleep(3000); // simulate process jLabel.setText("Done"); } catch (InterruptedException ex) { } } }); d.setVisible(false); d.dispose(); myFrame.setVisible(false); myFrame.dispose(); } }); } }

    Read the article

  • STL container to pop() by priority?

    - by Pirate for Profit
    I'm writing a thread-pool for Qt as QRunnable doesn't handle event loops in new threads. Not too familiar with STL, what would be the best way to pop() something by priority? Priority should probably be a property of MyRunnable imo, but I can always give that info to an STL container when adding the runnable to the queue.

    Read the article

  • Unlock device, display a text, then lock again

    - by Waza_Be
    For the need of my application, I need to display a message on the screen even if the lockscreen is enabled, then wait 3 seconds, than I have to lock again the phone as I don't want it to make unwanted phone calls in your pockets. First part is easy: if (PreferenceManager.getDefaultSharedPreferences( getBaseContext()).getBoolean("wake", false)) { KeyguardManager kgm = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); boolean isKeyguardUp = kgm.inKeyguardRestrictedInputMode(); WakeLocker.acquire(ProtoBenService.this); Intent myIntent = new Intent(ProtoBenService.this,LockActivity.class); myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (isKeyguardUp) { ProtoBenService.this.startActivity(myIntent); } else Toast.makeText(ProtoBenService.this.getBaseContext(), intention, Toast.LENGTH_LONG).show(); WakeLocker.release(); } With this class: public abstract class WakeLocker { private static PowerManager.WakeLock wakeLock; public static void acquire(Context ctx) { if (wakeLock != null) wakeLock.release(); PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "CobeIm"); wakeLock.acquire(); } public static void release() { if (wakeLock != null) wakeLock.release(); wakeLock = null; } } And the Activity: public class LockActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON); window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); TextView tv = new TextView(this); tv.setText("This is working!"); tv.setTextSize(45); setContentView(tv); Runnable mRunnable; Handler mHandler = new Handler(); mRunnable = new Runnable() { @Override public void run() { LockActivity.this.finish(); } }; mHandler.postDelayed(mRunnable, 3 * 1000); } } So, this is nice, the phone can display my text! The only problem comes when I want to lock again the phone, it seems that locking the phone is protected by the system... Programmatically turning off the screen and locking the phone how to lock the android programatically I think that my users won't understand the Device Admin and won't be able to activate it. Is there any workaround to lock the screen without the Device Admin stuff?

    Read the article

  • How solve consumer/producer task using semaphores

    - by user1074896
    I have SimpleProducerConsumer class that illustrate consumer/producer problem (I am not sure that it's correct). public class SimpleProducerConsumer { private Stack<Object> stack = new Stack<Object>(); private static final int STACK_MAX_SIZE = 10; public static void main(String[] args) { SimpleProducerConsumer pc = new SimpleProducerConsumer(); new Thread(pc.new Producer(), "p1").start(); new Thread(pc.new Producer(), "p2").start(); new Thread(pc.new Consumer(), "c1").start(); new Thread(pc.new Consumer(), "c2").start(); new Thread(pc.new Consumer(), "c3").start(); } public synchronized void push(Object d) { while (stack.size() >= STACK_MAX_SIZE) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } stack.push(new Object()); System.out.println("push " + Thread.currentThread().getName() + " " + stack.size()); notify(); } public synchronized Object pop() { while (stack.size() == 0) try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } stack.pop(); System.out.println("pop " + Thread.currentThread().getName() + " " + stack.size()); notify(); return null; } class Consumer implements Runnable { @Override public void run() { while (true) { pop(); } } } class Producer implements Runnable { @Override public void run() { while (true) { push(new Object()); } } } } I found simple realization of semaphore(here:http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html I know that there is concurrency package) How I need to change code to exchange java objects monitors to my custom semaphore. (To illustrate C/P problem using semaphores) Semaphore: class Semaphore { private int counter; public Semaphore() { this(0); } public Semaphore(int i) { if (i < 0) throw new IllegalArgumentException(i + " < 0"); counter = i; } public synchronized void release() { if (counter == 0) { notify(); } counter++; } public synchronized void acquire() throws InterruptedException { while (counter == 0) { wait(); } counter--; } }

    Read the article

  • Why do people run Java GUI's on the Event Queue

    - by asmo
    In Java, to create and show a new JFrame, I simply do this: public static void main(String[] args) { new JFrame().setVisible(true); } However, I have seen many people doing it like this: public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { new JFrame().setVisible(true); } }); } Why? Are there any advantages?

    Read the article

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