Java 下载和安装APK
我编写了从ftp下载APK的代码,我正在尝试在下载后安装它。我是为蜂巢写的,所以在每个连接中我都要使用线程。如何在类中在线程内使用startActivity,或等待线程完成Java 下载和安装APK,java,pthreads,android,Java,Pthreads,Android,我编写了从ftp下载APK的代码,我正在尝试在下载后安装它。我是为蜂巢写的,所以在每个连接中我都要使用线程。如何在类中在线程内使用startActivity,或等待线程完成 public class FTPapkDowload { protected static final String TAG = "Tablet Development"; public FTPClient mFTPClient = null; public FTPClient mFtp = null; public vo
public class FTPapkDowload {
protected static final String TAG = "Tablet Development";
public FTPClient mFTPClient = null;
public FTPClient mFtp = null;
public void Start() {
Thread apkdowload = new Thread(new Runnable() {
@Override
public void run() {
ftpConnect("mysite", "username", "password",21);
Log.d(TAG, "Connected");
ftpDownload("/httpdocs/Shamir/app.apk", "sdcard/Download/app.apk");
ftpDisconnect();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/Download/" + "app.apk")), "application/vnd.android.package-archive");
startActivity(intent); //Here is the problem
}
//Connection
public boolean ftpConnect(String host, String username,
String password, int port) {
try {
mFTPClient = new FTPClient();
mFTPClient.connect(host, port);
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
boolean status = mFTPClient.login(username, password);
mFTPClient.setFileType(FTP.BINARY_FILE_TYPE);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
Log.d(TAG, "Error: could not connect to host " + host);
}
return false;
}
//Downloading
public boolean ftpDownload(String srcFilePath, String desFilePath) {
boolean status = false;
try {
FileOutputStream desFileStream = new FileOutputStream(
desFilePath);
status = mFTPClient
.retrieveFile(srcFilePath, desFileStream);
desFileStream.close();
return status;
} catch (Exception e) {
Log.d(TAG, "download failed");
}
return status;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
Log.d(TAG, "Disconected from FTP on apk Download");
return true;
} catch (Exception e) {
Log.d(TAG,"Error occurred while disconnecting from ftp server on apk download.");
}
return false;
}
});
apkdowload.start();
}
}最干净的方法是让FTP下载代码通知主线程它已经完成,并让主(UI)线程调用startActivity。您可以使用任意数量的线程间通信方法来实现这一点,例如处理程序: 或者只需Activity.runOnUiThread: ) “无痛穿线”博文是一篇很好的读物: 您可以使用处理程序:
private Handler handler = new Handler(){
public void handleMessage(Message msg)
{
}
};
线程运行完需要调用的代码后:handler.sendEmptyMessage(0)代码>
更多信息:我想您需要将活动的上下文传递给要在其中使用活动方法的类 要执行UI方法,请在UI线程上运行以下命令:
将其放入普通线程的run()方法中:
请赞扬人们为帮助您和回答您之前的问题所做的努力。你还没有接受一个答案!或者您可以在UI线程上创建处理程序,然后在工作线程内调用handler.post(new Runnable(){…})代码>。我喜欢这样做。
YourClass.this.runOnUiThread(new Runnable() {
@Override
public void run() {
startyourActivity();
}
});