如何在Asynctask类中使用intent?

Sab*_*hik 6 android android-intent android-asynctask

请分享如何在doinbackground()或onpostexecute()方法中使用intent Asynctask类.当我尝试使用这些代码时,它会显示错误.

Intent intent = new Intent(asynctask.this, home.class);
startActivity(intent);
finish();

private Class<Home> clazz;
        public asynctask(Class<Home> clazz){
            this.clazz = clazz;
        }
Run Code Online (Sandbox Code Playgroud)

Asynctask doInBackground()方法:

  protected Void doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this, clazz);
        startActivity(intent);
        finish();
        Toast.makeText(cxt, "welcome", Toast.LENGTH_SHORT).show();
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

Har*_*ana 10

Try this way,hope this will help you to solve your problem.

How to asynctask class :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new MyCustomAsyncTask(this).execute();
 }
Run Code Online (Sandbox Code Playgroud)

MyCustomAsyncTask.java

public class MyCustomAsyncTask extends AsyncTask<Void,Void,Void> {
    private Context context;

    public MyCustomAsyncTask(Context context){
        this.context=context;
    }
    @Override
    protected void onPreExecute() {
        // write show progress Dialog code here
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // write service code here
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        Toast.makeText(context, "welcome", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(context, home.class);
        context.startActivity(intent);
        ((Activity)context).finish();
    }
}
Run Code Online (Sandbox Code Playgroud)


M D*_*M D 5

在方法中移动此Intent部分onPostExecute(...)AsynckTask