I'm new to AsyncTask and this is the first time I use it. What i am trying to achieve is the following: I would like to have an activity which has a button and a textview. When I press the button the app makes an ssh connection in the background and it connects to my raspberry pi. It runs a couple of python scripts and uploads them to dropbox.
When it's ready, the textview warns me that I can find my file in dropbox, as the upload was complete. If I'm right, I shouldn't write anything in the AsyncTask parameter list or should I?
Aside from the argument list, are there more to do on my code?
Thanks in advance!
public class Aszin extends AppCompatActivity {
String cmd = "python /home/pi/Desktop/get_db_pic.py";
private static String USERNAME = "piro"; // username for remote host
private static String PASSWORD = "password"; // password of the remote host
private static String host = "192.168.xx.xx"; // remote host address
private static int port = 22;
TextView tv1;
Button btn_ssh;
private AsyncTask<String, Integer, ???> asyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aszin);
tv1 = (TextView) findViewById(R.id.tv1);
tv1.setText("default");
btn_ssh = (Button) findViewById(R.id.btn1);
btn_ssh .setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
connect2pi(cmd);
}
});
}
public void connect2pi(final String cmd){
asyncTask = new AsyncTask<String, Integer, ??>() {
@Override
protected void doInBackground() {
List<String> result = new ArrayList<String>();
try {
JSch jsch = new JSch();
Session session = jsch.getSession(USERNAME, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(PASSWORD);
session.connect();
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
InputStream in = channelExec.getInputStream();
channelExec.setCommand(cmd);
channelExec.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
channelExec.getExitStatus();
channelExec.disconnect();
session.disconnect();
} catch (Exception e) {
System.err.println("Error: " + e);
}
}
@Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
tv1.setText("your file has been downloaded");
btn_ssh.setEnabled(true);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
tv1.setText("your file is getting downloaded");
btn_ssh.setEnabled(false);
}
};
asyncTask.execute(cmd);
}
}