我一直试图从另一个类调用Async方法,但是当我这样做时,应用程序似乎总是崩溃。当我从类中调用它时,Async方法可以工作。我相信我已经将它缩小到试图在UI线程(toast / message box)上显示消息的时候。但是,我尝试过的每一个解决方案都没有成功。下面你可以看到我的两个班级。任何帮助将非常感谢谢谢。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button mBtLaunchActivity;
private ListView listView1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoList videoList_data[] = new VideoList[]
{
//new VideoList(R.drawable.weather_cloudy, "Cloudy"),
new VideoList(R.drawable.air_squat_icon, "Air Squat Tutorial"),
new VideoList(R.drawable.deadlift_icon, "Deadlift Tutorial"),
new VideoList(R.drawable.front_squat_icon, "Front Squat Tutorial"),
new VideoList(R.drawable.bicep_curl_icon, "Bicep Curl Tutorial")
};
VideoListAdapter adapter = new VideoListAdapter(this,
R.layout.listview_item_row, videoList_data);
listView1 = (ListView) findViewById(R.id.listView1);
/*View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);*/
listView1.setAdapter(adapter);
//textView userText = (textView) findViewById(R.id.txtTitle);
//final String user = userText toString();
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
switch (position){
case 0:
System.out.println("omxplayer air_squat.mp4");
sendCommand("ls");
break;
case 1:
System.out.println("omxplayer deadlift.mp4");
break;
case 2:
System.out.println("omxplayer front_squat.mp4");
break;
case 3:
System.out.println("omxplayer bicep_curl.mp4");
break;
}
//Intent intent = new Intent(MainActivity.this, SSHConnectionDetails.class);
//Bundle bundle = new Bundle();
//bundle.putString("vidoedetails", filedetails);
//bundle.putString("videoname", filename);
//intent.putExtras(bundle);
//intent.putExtra("videofilename", filename);
//intent.putExtra("vidoefiledetails", filedetails);
//startActivity(intent);
//System.out.println("Clicked pos " + position); // your code is here on item click
//System.out.println("Clicked id " + id);
//System.out.println(position);
}
});
}
private void sendCommand(String cmd){
//String sshCommand = command;
//SSHConnectionDetails scd = new SSHConnectionDetails();
//scd.host = "";
//SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
//SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("MyPref", 0);
//String defaultValue = "Nothing";
//System.out.println(getString(R.string.username));
//String highScore = sharedPref.getString(getString(R.string.username), defaultValue);
//String host = sharedPref.getString("host", "");
//String user = sharedPref.getString("username", "");
//String pass = sharedPref.getString("password", "");
//int port = sharedPref.getInt("port", 22);
//Sending over the connection details & command to be executed
System.out.println("AT SEND COMMAND 1");
SSHConnectionDetails scd = new SSHConnectionDetails();
scd.sendCommand("host","user","pass",22,cmd);
//Send host,user,pass,port,command to be executed in a method
//Toast.makeText(getApplicationContext(), host + user + pass + port, Toast.LENGTH_SHORT).show();
}
private void launchActivity() {
//launching the SSHConnectionDetails activity
Intent intent = new Intent(this, SSHConnectionDetails.class);
startActivity(intent);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.SSH) {
launchActivity();
//return true;
}
return super.onOptionsItemSelected(item);
}
}
SSHConnectionDetails.java
public class SSHConnectionDetails extends AppCompatActivity {
private String host;
private String user;
private String pass;
private int port;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sshconnection_details);
SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("MyPref", 0);
String host = sharedPref.getString("host", "");
String user = sharedPref.getString("username", "");
String pass = sharedPref.getString("password", "");
int port = sharedPref.getInt("port", 22);
EditText hostText = (EditText)findViewById(R.id.Host);
EditText userText = (EditText)findViewById(R.id.User);
EditText passText = (EditText)findViewById(R.id.Pass);
EditText portText = (EditText)findViewById(R.id.Port);
hostText.setText(host, TextView.BufferType.EDITABLE);
userText.setText(user, TextView.BufferType.EDITABLE);
passText.setText(pass, TextView.BufferType.EDITABLE);
portText.setText(String.valueOf(port), TextView.BufferType.EDITABLE);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Toast.makeText(getApplicationContext(),host, Toast.LENGTH_SHORT).show();
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void navigateUp(View view){
NavUtils.navigateUpFromSameTask(this);
}
public void testInput2(View view){
//Collecting the inputted connection details and assigning them to variables
EditText userText = (EditText) findViewById(R.id.User);
user = userText.getText().toString();
System.out.println(user);
EditText passText = (EditText) findViewById(R.id.Pass);
pass = passText.getText().toString();
System.out.println(pass);
EditText hostText = (EditText) findViewById(R.id.Host);
host = hostText.getText().toString();
System.out.println(host);
EditText portText = (EditText) findViewById(R.id.Port);
port = Integer.parseInt(portText.getText().toString());
System.out.println(port);
sendCommand(host,user,pass,port,"ls");
}
public void sendCommand(final String hst, final String uname, final String pword, final int prt, final String cmd){
System.out.println("AT SEND COMMAND 2");
ExecuteSSHConnectionTask esct = new ExecuteSSHConnectionTask(SSHConnectionDetails.this);
esct.execute();
}
}
ExecuteSSHConnectionTask.Java
public class ExecuteSSHConnectionTask extends AsyncTask<Integer, Void, String>{
private Context mContext;
String uname = "user";
String pword = "pass";
int prt = 22;
String hst = "host";
String cmd = "ls";
public ExecuteSSHConnectionTask(Context context){
mContext = context;
}
ExecuteRemoteCommand erc = new ExecuteRemoteCommand(mContext);
protected String doInBackground(Integer... params) {
try {
erc.executeRemoteCommand(uname, pword, hst, prt, cmd);
} catch (Exception e) {
//displayMessage("Connection Unsuccessful: " + e.toString());
e.printStackTrace();
}
return "Test";
}
protected void onPostExecute(String result) {
//Toast.makeText(mContext, "Test" + result, Toast.LENGTH_SHORT).show();
//finish();
erc.displayMessage(result);
}
}
class ExecuteRemoteCommand{
private Context mContext;
public ExecuteRemoteCommand(Context context) {
mContext = context;
}
public void executeRemoteCommand(
String username,
String password,
String hostname,
int port,
String command) {
try {
// Setting up the session with the details provided
JSch jsch = new JSch();
Session session = jsch.getSession(username, hostname, port);
session.setPassword(password);
// Avoid asking for key confirmation
Properties prop = new Properties();
prop.put("StrictHostKeyChecking", "no");
session.setConfig(prop);
session.connect();
// SSH Channel
ChannelExec channelssh = (ChannelExec) session.openChannel("exec");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
channelssh.setOutputStream(baos);
// Executing the command
//channelssh.setCommand("ls");
channelssh.setCommand(command);
channelssh.connect();
channelssh.disconnect();
// Letting the user know that a successful connection has been made to the remote computer
//displayMessage("Connection Successful");
} catch (JSchException e) {
//displayMessage("Connection Unsuccessful: " + e.toString());
}
}
public void displayMessage(final String in){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
mContext);
// set title
alertDialogBuilder.setTitle("Your Title");
// set dialog message
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
//mContext.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}