首页 文章

Android:如何正确地为下面的类实现Asynctask?

提问于
浏览
-1

下面是一个登录活动,它与服务器连接以执行登录操作,因此要在后台线程中如何正确使用Asynctask的方法?

我是android的新手,之前没有使用过Asynctask,但是我看过教程仍然无法自己做

//公共类LoginActivity扩展AppCompatActivity扩展Asynctask显示一些错误

Edit: 错误在这里//公共类LoginActivity扩展AsyncTask扩展AppCompatActivity {({expected)

public class LoginActivity extends AppCompatActivity{


private TextView tvLFS, tvOr;
private Button btnLog;
private EditText etUn, etPw;
private static final String TAG = "LoginActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    //remove action bar
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.hide();
    }

    //change font of the heading
    tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
    Typeface typeface = 

    Typeface.createFromAsset(getAssets(),
    "fonts/futuramediumitalicbt.ttf");
    tvLFS.setTypeface(typeface);

    init();
}

private void init() {
    tvLFS = (TextView) findViewById(R.id.tvHeadingLFS);
    tvOr = (TextView) findViewById(R.id.tvOR_LOGIN_USING);
    btnLog = (Button) findViewById(R.id.btnLogin);
    etUn = (EditText) findViewById(R.id.etUName);
    etPw = (EditText) findViewById(R.id.etPass);


    /* SharedPreferences pref = getSharedPreferences("ActivityPREF", 
    Context.MODE_PRIVATE);
    SharedPreferences.Editor edt = pref.edit();
    edt.putBoolean("activity_executed", true);
    edt.commit();*/


    btnLog.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {

                final String usname = etUn.getText().toString();
                final String uspass = etPw.getText().toString();


                final LoginRequest loginRequest = new LoginRequest();
                loginRequest.setClientType("mobile");
                loginRequest.setMsService("login");
                loginRequest.setMsServiceType("user-management");
                List<LoginRequest.MsDataLogin> msDataLogList = new 
     ArrayList<>();
                LoginRequest.MsDataLogin msData = 
     loginRequest.getMsDAtaLoginInstance();
                msData.setUserName(usname);
                msData.setUserPass(uspass);
                msDataLogList.add(msData);
                loginRequest.setMsData(msDataLogList);


     RestClient.getApiInterface().postData(loginRequest).enqueue(new 
     ResponseResolver<LoginResponse>(LoginActivity.this) {
                    @Override
                    public void success(LoginResponse loginResponse) {

                        if (loginResponse.getErrorCode().equals("0")) 
    {
                            Toast.makeText(LoginActivity.this, 
    "Logged-in successfully!!", Toast.LENGTH_SHORT).show();
                            Intent in = new 
    Intent(getApplicationContext(), MainActivity.class);
                            startActivity(in);
                            finish();
                        } else 
    if(loginResponse.getErrorCode().equals("1")){
                            Toast.makeText(LoginActivity.this, "No 
    account found!! Please register", Toast.LENGTH_LONG).show();
                        }

                    }


                    @Override
                    public void failure(APIError error) {

                        Log.d(TAG, "failure: error-- 
    "+error.getMessage());

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
               }
          }
      });
    }


  }

1 回答

  • 2

    根据你编辑,你试图扩展两个类?那么,(我认为)在Java中是不可能的......

    回到你关于AsyncTask的问题 . 对于某些场景,AsynTask用于在主线程/ UI线程之外创建任务(例如:基本,在执行某些工作时不锁定UI),因此您无法与AsyncTask中的UI进行交互甚至混合两种东西(在某些情况下是可能的,但不推荐) .

    因此,您需要在除您的视图/活动(另一个Class.java或嵌套/内部类)之外的其他类中扩展AsyncTask,如下所示:

    public class MyAsyncTask extends AsyncTask<ParameterType, ProgressType, ReturnType> {
    
        //Example to demonstrate UI interation
        private IView view;
    
        public MyAsyncTask(IView view) {
            this.view = view;
        }
    
        @Override
        protected ReturnType doInBackground(ParameterType... params) {
            // do and update the work
            return new ReturnType(); // work is done, return the result
        }
    
        // Override this method if you need to do something after the AsyncTask has finished (based on the return). Here you can interact with the UI too.
        @Override
        protected void onPostExecute(ReturnType o) {
            // Example of UI interaction
            view.updateUI(o);
        }
    }
    

    如果您不需要参数,返回或更新AsyncTask的进度,您可以使用'Void'类型就位ParameterType,ProgressType或ReturnType .

    然后,您可以在其他类(例如:您的活动)中创建一个MyAsyncTask的intance,调用'execute()'方法来启动AsyncTask .

    public class Foobar extends AppCompatActivity implements IView {
        ... code ...
        MyAsyncTask fooTask = new MyAsyncTask(this); // Foobar class needs to implement IView interface
        fooTask.execute(parameters); // execute AsyncTask with 'parameters'
        ... code ...
    }
    

    根据您的代码,您尝试拨打网络电话 . 因此,您需要将网络调用迁移到'doInBackground'方法内,并在'onPostExecute'中调用下一个活动(或显示错误) .

    我不太熟悉您的实现(RestClient,ResponseResolver),但我认为您可以使用Retrofit / Jackson库来获得更加可靠的解决方案 . 它们不是很难理解,使网络呼叫更容易 .

    在下面的参考中,您可以使用其他替代方法而不是AsyncTask .

    这是一些参考:

    https://developer.android.com/reference/android/os/AsyncTask.html https://developer.android.com/guide/components/processes-and-threads.html

    好编码 .

相关问题