从实现Runnable的外部类访问UI线程或主线程

时间:2018-08-28 07:55:23

标签: java android multithreading

我讨厌The application may be doing too much work on its main thread, skipped XXX frames ..警告,它也会降低用户UI交互体验。因此,以Android希望采用的正确方式进行尝试...


MainActivity:

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
    public Button StartBg;
    private static final String TAG = "TASK_FIRST";
    private Handler mainHandler = new Handler();

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

        StartBg = findViewById(R.id.StartBg);

        StartBg.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                ExampleRunner ExampleRunnerObj = new ExampleRunner(50000);
                new Thread(ExampleRunnerObj).start();
            }
        });
    }
}

当我在MainActivity的内部类中保持较低的级别时,它可以访问UI组件。


ExampleRunner:

public class ExampleRunner implements Runnable
{
    int count;

    public ExampleRunner(int count)
    {
        this.count = count;
    }

    @Override
    public void run()
    {
        Handler threadHandler = new Handler(Looper.getMainLooper());

        for(int i = 0; i < count; i++)
        {
            Log.d(TAG,"PERFORMING : "+i+"\n");

            if(i == 25000)
            {
                threadHandler.post(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        // StartBg.setText("50k");
                        // OR RETURN SOMETHING..
                    }
                });
            }
        }
    }
}

但是当我将ExampleRunner设为单独的外部类时,它说StartBg无法解析...

所以,我应该如何:

  1. 使外部Java类实现Runnable,Access Main Threads UI组件...?
  2. 或者至少将某些东西返回到我正在启动的mainActivity上,以便可以从mainActivity中访问它?

谢谢。

2 个答案:

答案 0 :(得分:1)

您需要通过外部类Button作为参考:

public class ExampleRunner implements Runnable
{
    int count;
    Button startBg;

    public ExampleRunner(int count, Button startBg) {
    this.count = count;
    this.startBg = startBg;
}

并使用它创建它:

ExampleRunner ExampleRunnerObj = new ExampleRunner(50000, StartBg);

然后它将可以在run()中使用它。

现在,ExampleRunner是一个匿名类,用于访问在本地声明的StargBg变量。

答案 1 :(得分:0)

如果我正确地理解了您,对于您的解决方案,AsyncTask是很好的解决方案。

检查文档https://developer.android.com/reference/android/os/AsyncTask