【问题标题】:Executing Activity's AsyncTask from Application Class从应用程序类执行 Activity 的 AsyncTask
【发布时间】:2016-11-16 09:11:40
【问题描述】:

我正在尝试找到一种方法来自动执行 AsyncTask,目前它可以通过按下按钮来工作。

提供一些上下文 -

应用程序类

// 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 子类

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);
    }
}

我已经扩展了我的 Application 类,在这个类内部是一个处理程序,它读取从我的服务发送的消息,msg.arg1 在这个处理程序内部被读取并选择适当的情况。

在我的 message_read 案例中,msg.obj 保存为 byte[],然后保存为 String。

我目前的想法是在检查相关活动当前是否正在运行后,以某种方式从应用程序类处理程序执行我的活动中的 AsynTask。最初我让这个功能在一个循环中工作,但是在对我的应用程序进行巨大更改后,要求发生了变化,因为蓝牙连接服务在两个活动之间共享。

【问题讨论】:

  • 最好放一些你的代码,以便我们帮助你
  • 完成,省略了一些不相关的代码,尤其是在处理程序中

标签: android android-asynctask android-handler


【解决方案1】:

1.创建接口

2.在活动中实现该接口。

3.然后,将该接口从活动注册到应用程序类中

4.After than do 从应用类回调

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);
  }

}

【讨论】:

  • 你能给出一个简短的代码示例吗?
【解决方案2】:

是的,您可以从应用程序类运行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() {}

    }
  }
}

【讨论】:

  • AsyncTask 现在在我的活动中,而不是应用程序类,虽然它可能是另一种选择,但我必须找到一种方法从应用程序类的 AsyncTask 子类更新我的活动 UI。
  • 你可以从 AsyncTask 更新你的 UI 只是 ui 更新将封装在 mContext.runOnUiThread(new Runnable() { public void run() { //Do something on UiThread } });
猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
相关资源
最近更新 更多