Windows 7 Windows上的多个实例
这是我在Windows7上发现的。windows上的tide sdk应用程序在双击快捷方式时会创建新实例,即使以前的实例已经存在。您可以在Tide SDK Developer(1.4.2)上观察到同样的情况,只需运行应用程序,如果再次单击快捷方式,它将启动一个新实例,而不只是显示已经存在的实例。有人知道如何解决这个问题吗?还是有人修复了这个Windows 7 Windows上的多个实例,windows-7,tidesdk,Windows 7,Tidesdk,这是我在Windows7上发现的。windows上的tide sdk应用程序在双击快捷方式时会创建新实例,即使以前的实例已经存在。您可以在Tide SDK Developer(1.4.2)上观察到同样的情况,只需运行应用程序,如果再次单击快捷方式,它将启动一个新实例,而不只是显示已经存在的实例。有人知道如何解决这个问题吗?还是有人修复了这个 OSX版本没有显示这样的问题,所以我找到了在windows中解决这个问题的方法。使用Ti.process创建一个进程,并让它运行以下命令 tasklist
OSX版本没有显示这样的问题,所以我找到了在windows中解决这个问题的方法。使用Ti.process创建一个进程,并让它运行以下命令
tasklist | find "YourAppName"
如果实例已经存在,则返回该字符串,否则返回空字符串。您可以在每次启动应用程序时检查此选项,以避免在后台运行多个实例任务列表依赖于平台,而且该解决方案只会阻止启动新实例-它不会关注已在运行的实例。还有另一种解决方案利用了
Ti.FileSystem.File.touch()
方法:此方法将尝试创建指定的文件,如果成功,将返回true
,如果文件已经存在,则返回false
。最重要的是,它是原子的,这意味着它不应该在应用程序中引入竞争条件
要聚焦已经运行的实例,您需要让它知道它应该(显示并)聚焦自身。一种可行的方法是,一旦应用程序知道它是唯一正在运行的实例,就运行HTTP服务器,并在收到请求时关注自身。如果应用程序在启动时发现另一个实例已在运行,则改为创建HTTP客户端,连接到另一个实例的HTTP服务器并向其发送请求;请求完成后,退出
示例实现(放在app.js文件的开头):
通过Ti.Network.TCPSocket
类连接这两个实例可能有一种更轻量级的方法(我现在正在研究)。要记住的另一件事是,应用程序可能会崩溃,无法自行清理,因此,随后根本无法运行。因此,在HTTPClient的onerror
事件处理程序中,比退出更为谨慎的方法是向用户提供一个对话,内容大致如下:“应用程序要么已经运行且没有响应,要么最近崩溃。是否要强制启动应用程序?”,服务器的端口可能已经被另一个应用程序使用,或者可能是来自上一次应用程序崩溃运行的僵尸-提供的代码没有考虑到这一点(只是说)
// enclose the logic in a closure, just to play it safe
(function(pidFile) {
// if creating the PID file fails, i.e. there is another instance
// of the app already running
if (!pidFile.touch()) {
// create a HTTP client
var client = Ti.Network.createHTTPClient({});
// add some event handlers
client.onload = function() {
Ti.App.exit();
};
client.onerror = function() {
Ti.App.exit();
};
// and dispatch
client.open('GET', 'http://localhost:9731/');
client.send();
} else {
// or, if creating the PID file succeeds,
// create a HTTP server and listen for incoming requests
var server = Ti.Network.createHTTPServer();
server.bind(9731, 'localhost', function(request, response) {
// this handler gets run when another instance of the app
// is launched; that's where you want to show the app window
// if it is hidden and focus it
if (!Ti.UI.getMainWindow().isVisible()) {
Ti.UI.getMainWindow().show();
}
Ti.UI.getMainWindow().focus();
// send some response back to the other instance
response.setContentType('text/plain');
response.setContentLength(2);
response.setStatusAndReason('200', 'OK');
response.write('OK');
});
// an important thing is to clean up on application exit
// - you want to remove the PID file once the application
// exits, or you wouldn't be able to run it again until you
// deleted the file manually, something you don't want the end user
// to deal with
Ti.API.addEventListener(Ti.EXIT, function() {
server.close();
pidFile.deleteFile();
});
}
// now call the closure passing in an instance of the Ti.Filesystem.File class
// wrapping the PID file in you app data directory
})(Ti.Filesystem.getFile(Ti.API.Application.getDataPath(), 'run.pid'));