简体   繁体   English

从应用程序类执行Activity的AsyncTask

[英]Executing Activity's AsyncTask from Application Class

I'm trying to find a way to automate the execution of an AsyncTask, currently it's working from a button press. 我正在尝试寻找一种自动执行AsyncTask的方法,当前它是通过按下按钮来工作的。

To give some context - 给一些背景-

Application Class 应用类别

// The Handler that gets information back from the BluetoothService
public final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {                
            case MESSAGE_READ:
                Log.d(TAG, "MESSAGE_READ");
                byte[] readBuf = (byte[]) msg.obj;
                readMessage = new String(readBuf);
                break;
        }
    }
};

Activity - AsyncTask Subclass 活动-AsyncTask子类

private class PostTask extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        readBuf = ((MyApplication) getApplication()).getReadBuf();
        speedcur1 = speedometer.getCurrentSpeed();
        speedcur2 = speedometer1.getCurrentSpeed();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if (readBuf.startsWith("V")) {
            readBuf = readBuf.replace("V", "");
            String[] parts = readBuf.split(",");
            String part1 = parts[0];
            String part2 = parts[1];
            speed1 = Float.parseFloat(part1);
            speed2 = Float.parseFloat(part2);
            finalspeed1 = ((speed1 * 102) / 100);
            finalspeed2 = ((speed2 * 602) / 100);
        }
        return null;
    }

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

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        speedometer.onSpeedChanged(speedometer.getCurrentSpeed() - speedcur1);
        speedometer.onSpeedChanged(speedometer.getCurrentSpeed() + finalspeed1);
        speedometer1.onSpeedChanged(speedometer1.getCurrentSpeed() - speedcur2);
        speedometer1.onSpeedChanged(speedometer1.getCurrentSpeed() + finalspeed2);
        myLabel.setText(readBuf);
    }
}

I have extended my Application class, inside this class is a handler which reads messages sent from my service, msg.arg1 is read inside this handler and selects the appropriate case. 我扩展了Application类,在该类内部是一个处理程序,该处理程序读取从我的服务发送的消息,在该处理程序中读取msg.arg1并选择适当的大小写。

Inside my message_read case the msg.obj is saved as a byte[], then saved as a String. 在我的message_read案例中, msg.obj保存为byte [],然后保存为String。

My current idea is to somehow execute the AsynTask inside my activity from the application class handler after checking if the activity in question is currently running. 我当前的想法是在检查相关活动当前是否正在运行之后,通过应用程序类处理程序以某种方式在我的活动中执行AsynTask。 Originally I had this functionality working inside a loop however after making huge changes to my app the requirements have changed as a Bluetooth connection service is shared between two activities. 最初,我具有在循环中运行此功能的功能,但是在对我的应用程序进行了很大的更改之后,由于蓝牙连接服务在两个活动之间共享,因此要求已发生了变化。

Yes you can run AsyncTask from application class and check according to your logic to run or not? 是的,您可以从应用程序类运行AsyncTask并根据您的逻辑检查是否运行?

    public class BaseJuiceApplication extends Application  {

        public static BaseJuiceApplication instance = null;

        public static Context getInstance() {
            if (null == instance) {
                instance = new BaseJuiceApplication();
            }
            return instance;
        }

        @Override
        public void onCreate() {
            super.onCreate();

            if(getPrefs.getBoolean("MyKKey")){
              // any of your logic 
                 new LongOperation().execute("");
                }

        }

    private class LongOperation extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {}

    }
  }
}

1.create an interface 1.创建接口

2.Implement that interface in activity. 2.在活动中实现该界面。

3.Then, register that interface from activity into the application class 3.然后,将该接口从活动注册到应用程序类中

4.After than do callback from application class 4.之后从应用程序类回调

5.Make sure to unregister from activity in onDestroy or onStop 5,确保在onDestroy或onStop中注销活动

public class ApplicationClass extends Appliation{

    private static ApplicationClass instance;
    private TestInterface mCallBack;

    public final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {                
            case MESSAGE_READ:
                if(mCallBack!=null){
                  mCallBack.doSomething();
                }
                break;
        }
    }
};


    public void onCreate(){
       instance = this;
    }


    public ApplicationClass getInstance(){
        return instance;
    }

    public void register(TestInterface callBack){
      mCallBack = callBack;
    }

    public void unRegister(){
      mCallBack = null;
    }



}

public interface TestInterface{

    void doSomething();

}

public class MainActivity extends Activity implements TestInterface{

  @Override 
  public void doSomething(){

  }

  @Override 
  public void onStop(){
   ApplicationClass.getInstance().unRegister();
  }

  @Override
  public void onStart(){
   ApplicationClass.getInstance().register(this);
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM