2014-10-29 1 views
-1

Использование java, как найти приложение, не используется какое-то время?Использование java, как найти приложение, не используется какое-то время?

У меня есть стороннее приложение, например, мы можем взять «Skype». Если нет действия (ввод мыши/клавиатуры), дается skype в течение 5 минут, тогда мой код через некоторое всплывающее окно пользователю. Итак, как проверить, поступает ли приложение от пользователя? Я прошел через интернет, я нашел ниже код, который дает вывод, если весь рабочий стол не работает. но я нуждаюсь в конкретном приложении, таком как skype. как это сделать?

import java.text.DateFormat; 
 
import java.text.SimpleDateFormat; 
 
import java.util.Date; 
 

 
import com.sun.jna.*; 
 
import com.sun.jna.win32.*; 
 

 
/** 
 
* Utility method to retrieve the idle time on Windows and sample code to test it. 
 
* JNA shall be present in your classpath for this to work (and compile). 
 
* @author ochafik 
 
*/ 
 
public class Win32IdleTime { 
 

 
public interface Kernel32 extends StdCallLibrary { 
 
Kernel32 INSTANCE = (Kernel32)Native.loadLibrary("kernel32", Kernel32.class); 
 

 
/** 
 
* Retrieves the number of milliseconds that have elapsed since the system was started. 
 
* @see http://msdn2.microsoft.com/en-us/library/ms724408.aspx 
 
* @return number of milliseconds that have elapsed since the system was started. 
 
*/ 
 
public int GetTickCount(); 
 
}; 
 

 
public interface User32 extends StdCallLibrary { 
 
User32 INSTANCE = (User32)Native.loadLibrary("user32", User32.class); 
 

 
/** 
 
* Contains the time of the last input. 
 
* @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputstructures/lastinputinfo.asp 
 
*/ 
 
public static class LASTINPUTINFO extends Structure { 
 
public int cbSize = 8; 
 

 
/// Tick count of when the last input event was received. 
 
public int dwTime; 
 
} 
 

 
/** 
 
* Retrieves the time of the last input event. 
 
* @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/userinput/keyboardinput/keyboardinputreference/keyboardinputfunctions/getlastinputinfo.asp 
 
* @return time of the last input event, in milliseconds 
 
*/ 
 
public boolean GetLastInputInfo(LASTINPUTINFO result); 
 
}; 
 

 
/** 
 
* Get the amount of milliseconds that have elapsed since the last input event 
 
* (mouse or keyboard) 
 
* @return idle time in milliseconds 
 
*/ 
 
public static int getIdleTimeMillisWin32() { 
 
User32.LASTINPUTINFO lastInputInfo = new User32.LASTINPUTINFO(); 
 
User32.INSTANCE.GetLastInputInfo(lastInputInfo); 
 
return Kernel32.INSTANCE.GetTickCount() - lastInputInfo.dwTime; 
 
} 
 

 
enum State { 
 
UNKNOWN, ONLINE, IDLE, AWAY 
 
}; 
 

 
public static void main(String[] args) { 
 
if (!System.getProperty("os.name").contains("Windows")) { 
 
System.err.println("ERROR: Only implemented on Windows"); 
 
System.exit(1); 
 
} 
 
State state = State.UNKNOWN; 
 
DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss"); 
 

 
for (;;) { 
 
int idleSec = getIdleTimeMillisWin32()/1000; 
 

 
State newState = 
 
idleSec < 30 ? State.ONLINE : 
 
idleSec > 5 * 60 ? State.AWAY : State.IDLE; 
 

 
if (newState != state) { 
 
state = newState; 
 
System.out.println(dateFormat.format(new Date()) + " # " + state); 
 
} 
 
try { Thread.sleep(1000); } catch (Exception ex) {} 
 
} 
 
} 
 

 
}

+0

Что вы подразумеваете под словом "not used"? Не получать ввод клавиатуры или мыши? Не работает ли нить в фоновом режиме? Вы должны быть более конкретными. –

+0

Это звучит как очень специфичная для платформы функция, которую вы ищете, а Java поддерживает только функции, которые могут быть реализованы кросс-платформенными. Если эта функция возможна в Windows, вам, вероятно, придется написать обертку с интерфейсом нативного интерфейса или вызвать внешнюю команду. –

+1

Вы можете просто сохранить дату где-нибудь, когда ваше приложение что-то делает. После этого вам просто нужно вычесть текущую дату с последней датой использования. –

ответ

1

Вы можете реализовать MouseListner и KeyListener в приложении, а затем вы можете проверить его. Но если ваше приложение обрабатывает то, что нам также нужно подумать. Пожалуйста, объясните, что делает ваша заявка?

+0

@Frozn, отличный ответ! Не нужно реализовывать MouseListener и KeyListener. Супер, как! –

+0

Но ваш способ также это сделать. – Frozn

+0

@Frozn, Да, но ваш путь проще и прямо вперед, мне понравилось! –

2

Я думаю, что, если вы не используете, вы имеете в виду, что вы, как пользователь, не используете его активно. Чем вы можете использовать WindowListener. Вот пример рабочего кода (надеюсь, это то, что вы хотели):

public class AwayTimer { 
    private JFrame mainframe; // the mainframe in which everything will we 
    private JLabel timeLabel; // our label which stores the time when were leaving the window 

    private long leaveTime = 0; // that time is set to zero, to prevent it later saying strange numbers 

    public static void main(String[] args) { 
     new AwayTimer(); // create new AwayTimer object 
    } 

    public AwayTimer() { 
     mainframe = new JFrame("Away Timer"); // create new Frame with name Away Timer 

     timeLabel = new JLabel ("You were 0 seconds away.", SwingConstants.CENTER); // create new label which shows the time we were away 

     WindowListener listener = new WindowListener() { 
      @Override 
      public void windowDeactivated(WindowEvent e) { // called on leaving focus 
       leaveTime = System.currentTimeMillis(); // get the time when leaving the window and save it leaveTime 
      } 

      @Override 
      public void windowActivated(WindowEvent e) { // called on switching to Frame 
       // That also gets activated when we open the program. It shows you were <ahugenumber> seconds away. To set it 0, we check if leaveTime is 0 as we initialized it 
       if (leaveTime == 0) return; // we dont need to calculate anything and leave the text as it is 
       long difference = (System.currentTimeMillis() - leaveTime)/1000; // calculate the difference between the leave time and now and divide it by 1000 to get the time in seconds 
       timeLabel.setText("You were " + difference + " seconds away."); // change the displayed text 
      } 

      // Other listeners, which arent important for that 
      @Override 
      public void windowOpened(WindowEvent e) {/* do something here*/} 

      @Override 
      public void windowIconified(WindowEvent e) {/* do something here*/} 

      @Override 
      public void windowDeiconified(WindowEvent e) {/* do something here*/} 

      @Override 
      public void windowClosing(WindowEvent e) {/* do something here*/} 

      @Override 
      public void windowClosed(WindowEvent e) {/* do something here*/} 
     }; 

     mainframe.addWindowListener(listener); // add the previously created listener to the window 

     // add the label to the frame 
     mainframe.add(timeLabel); 
     mainframe.pack(); // resize the frame, so it fits the contents 
     mainframe.setVisible(true);  // make it visible 
    } 
} 

Надеюсь, что смогу помочь.

+1

Благодарим за помощь. – Manikandan

 Смежные вопросы

  • Нет связанных вопросов^_^