在asynytask中完成活动意图

时间:2018-10-08 13:59:04

标签: android android-intent android-asynctask activity-finish

您好,我目前在我的libary移动应用程序的android mysql上工作,但是我登录后如何关闭登录活动,context .finish();这不是我的代码。我通常都知道它唯一的finish(); 但是我该怎么做呢?

我的异步任务:

public class backgroundWorker extends AsyncTask<String,Void,String> {

    Context context;
    AlertDialog alertDialog;

    String result;

    backgroundWorker(Context ctx) {
        context = ctx;
    }

    ProgressDialog progressDialog;

    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://192.168.254.120/LibrayAPI/Signin.php";

        if (type.equals("login")) {


            String user_name = params[1];
            String password = params[2];


            try {

                String data = URLEncoder.encode("user_name", "UTF-8") + "=" +
                        URLEncoder.encode(user_name, "UTF-8");
                data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
                        URLEncoder.encode(password, "UTF-8");
                URL url = new URL(login_url);
                URLConnection conn = url.openConnection();

                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter((conn.getOutputStream()));

                wr.write(data);
                wr.flush();

                BufferedReader reader = new BufferedReader(new
                        InputStreamReader(conn.getInputStream()));

                StringBuilder sb = new StringBuilder();
                String line;
                //Read server response
                while ((line = reader.readLine()) != null) {

                    sb.append(line);
                    break;
                }
                return sb.toString();

            } catch (Exception e) {
                return new String("Exeption" + e.getMessage());
            }
        }

        return null;
    }

    @Override
    protected void onPreExecute() {
        alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle("Log in Status");
        progressDialog = new ProgressDialog(context);
        progressDialog.setMessage("\tLoading");
        progressDialog.show();
    }

    @Override
    protected void onPostExecute(String result) {
         progressDialog.dismiss();
        alertDialog.setMessage(result);
        alertDialog.show();

        if (result.equals("Log in sucessful")) {
            alertDialog.dismiss();
            Intent todash = new Intent(context, DashBoard.class);
            context.startActivity(todash);

        } else {
        }

    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

登录活动:

public class Login extends AppCompatActivity {

    EditText username,password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        username = findViewById(R.id.edtUsername);
        password = findViewById(R.id.edtPassword);
    }

    public void onLogin(View view) {

        String Username = username.getText().toString();
        String Password = password.getText().toString();
        //notif call
//call notif for overdue tommorow
        backWorkerNotifTom backWorkerNotifTom = new backWorkerNotifTom(this);
        //get datetime tom
        Calendar calendar =  Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR,1);
        Date dateTom = calendar.getTime();
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyy-MM-dd");
        String dateTomString = sf1.format(dateTom);
        Toast.makeText(this, dateTomString, Toast.LENGTH_SHORT).show();
        backWorkerNotifTom.execute("SelectNotifTom",dateTomString,Username);

        backWorkerNotif backWorkerNotif = new backWorkerNotif(this);
        Date date = Calendar.getInstance().getTime();
        SimpleDateFormat SF = new SimpleDateFormat("yyyy-MM-dd");
        String DateNow = SF.format(date);
        backWorkerNotif.execute("Notif", DateNow, Username);

        String Type = "login";
        GlobalVariable.BorrowerID = Username;
        GlobalVariable.Password = Password;
        backgroundWorker _backgroundWorker = new backgroundWorker(this);
        _backgroundWorker.execute(Type, Username, Password);


    }
}

PS:看起来像是Android新手。

6 个答案:

答案 0 :(得分:1)

尝试使用“活动”而不是“上下文”

Activity context;
AlertDialog alertDialog;

String result;

backgroundWorker(Activity ctx) {
    context = ctx;
}

在调用backgroundWorker时,请给Login.this上下文上下文

backgroundWorker _backgroundWorker = new backgroundWorker(Login.this);

答案 1 :(得分:0)

从AsyncTask完成活动的最简单方法是更改​​上下文类型:

public class backgroundWorker extends AsyncTask<String,Void,String> {

    Login context;
    AlertDialog alertDialog;

    String result;

    backgroundWorker(Login ctx) {
        context = ctx;
    }

    //...
}

然后,在您的onPostExecute()中,您可以致电:

context.finish();

您正在从登录活动中将this传递给构造函数,因此您无需更改构造Task的方式。这意味着只能从该Activity构造您的AsyncTask,但这可能就是您所需要的。

答案 2 :(得分:0)

如果您想从AsyncTask中完成Activity,则需要在AsyncTask构造函数中传递一个Activity引用。

public class backgroundWorker extends AsyncTask<String,Void,String> {

    private Activity mActivity;
    Context context;
    AlertDialog alertDialog;

    String result;

    backgroundWorker(Activity activity) {
        context = activity.getApplicationContext();
        mActivity = activity;
    }

    ......

    protected void onPostExecute(String result) {
        //do your job
        mActivity.finish();
        ....
    }
}

答案 3 :(得分:0)

只需添加一行即可完成登录活动.....

 @Override
     protected void onPostExecute(String result) {
          progressDialog.dismiss();
          alertDialog.setMessage(result);
          alertDialog.show();
          if (result.equals("Log in sucessful")) {
               alertDialog.dismiss();
               ((Activity)context).finish();//just add this line of code
               Intent todash = new Intent(context, DashBoard.class);
               context.startActivity(todash);

          } else {
              //do your work
          }

     }

答案 4 :(得分:0)

您可以在AsyncTask中传递WeakReference,这样可以避免可能的上下文泄漏。您可以这样实现:

public class MyAsynctask extends AsyncTask<Void, Void, Void> {

    private WeakReference<Activity> mWeakContext;

    public MyAsynctask(WeakReference<Activity> reference) {
        mWeakContext = reference;
    }

    @Override
    protected String doInBackground(String... params) {
        // Do your work
    }

    @Override
    protected void onPostExecute(String result) {
        Activity activity = mWeakContext.get();
        if (activity != null) {
            activity.finish();
        }
    }
}

答案 5 :(得分:0)

另一种处理方式是创建一个接口,并在异步完成其任务后通知调用方。

  public interface asyncTaskStatusListener {
        void onfinishTask();
    }

//进行登录活动以实现界面

  public class Login extends AppCompatActivity implements asyncTaskStatusListener {

    @Override
     public void onfinishTask() {
      finish();
   }
 }

   //Create your background class constructor which takes interface reference.
   backgrounderWorker = new backgroundworker(asyncTaskStatusListener callback);

    //In post execute method call 
    callback.onfinishTask();