我讨厌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
无法解析...
所以,我应该如何:
谢谢。
答案 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