我正在阅读AsyncTask,我尝试了下面的简单程序.但它似乎没有用.我怎样才能使它工作?
public class AsyncTaskActivity extends Activity {
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener((OnClickListener) this);
}
public void onClick(View view){
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
for(int i=0;i<5;i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
TextView txt = (TextView) findViewById(R.id.output); …Run Code Online (Sandbox Code Playgroud) 我不明白为什么我会收到这个错误.我正在使用AsyncTask在后台运行一些进程.
我有:
protected void onPreExecute()
{
connectionProgressDialog = new ProgressDialog(SetPreference.this);
connectionProgressDialog.setCancelable(true);
connectionProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
connectionProgressDialog.setMessage("Connecting to site...");
connectionProgressDialog.show();
downloadSpinnerProgressDialog = new ProgressDialog(SetPreference.this);
downloadSpinnerProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downloadSpinnerProgressDialog.setMessage("Downloading wallpaper...");
}
Run Code Online (Sandbox Code Playgroud)
当我doInBackground()根据条件进入时我:
[...]
connectionProgressDialog.dismiss();
downloadSpinnerProgressDialog.show();
[...]
Run Code Online (Sandbox Code Playgroud)
每当我尝试downloadSpinnerProgressDialog.show()我收到错误.
有什么想法吗?
我在另一个线程中使用setText,即子线程.但对于以下代码,它给出了错误
只有创建视图层次结构的原始线程才能触及其视图.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
img = (ImageView)findViewById(R.id.img);
pb = (ProgressBar)findViewById(R.id.pb);
this.tv = (TextView)findViewById(R.id.perc);
tv.setText("30 %");
pb.setProgress(30);
pb.setMax(100);
}
public void set(int p)
{
tv.setText(p + " %");
}
protected void onStart()
{
super.onStart();
pb.setProgress(20);
Thread t = new Thread(new Runnable()
{
@Override
public void run()
{
try {
int i = pb.getProgress();
while(i <100)
{
while(pb.getProgress()<100)
{
pb.incrementProgressBy(5);
Thread.sleep(1000);
}
i+=10;
pb.setProgress(i);
Thread.interrupted();
set(i);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
} …Run Code Online (Sandbox Code Playgroud) 看,我有以下代码:
我的行动:
final Intent intent = new Intent(getApplicationContext(), MyService.class)
.putExtra(UploadService.EXTRA_RESULT_RECEIVER, new ResultReceiver(null) {
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
String result = resultData.getString(MyService.EXTRA_RESULT_SUCCESS);
...
imageView.setBackgroundDrawable(bitmap);// here my code fails
}
})
Run Code Online (Sandbox Code Playgroud)
为MyService:
Bundle b = new Bundle();
b.putString(EXTRA_RESULT_SUCCESS, response.toString());
resultReceiver.send(0, b);
Run Code Online (Sandbox Code Playgroud)
我的应用程序在"imageView.setBackgroundDrawable(bitmap)"行上失败,但有以下异常:
11-13 16:25:38.986: ERROR/AndroidRuntime(3586): FATAL EXCEPTION: IntentService[MyService]
android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Run Code Online (Sandbox Code Playgroud)
但是当我像这样定义接收器(带处理程序)时,这不会发生:
new ResultReceiver(new Handler()){.../*here goes the same code as in the first example. nothing …Run Code Online (Sandbox Code Playgroud) 我有一个进度对话框,我在程序中使用了一个部分,我在后台进行了时间密集型操作,但是当对话框显示时,UI或微调器图标冻结/慢/犹豫使程序看起来好像冻结了一样.在我onPostExecute的我AsyncTask解雇对话.
为什么会发生这种情况,因为我在后台完成所有工作?
这是我的代码
pDialog = ProgressDialog.show(FullGame.this,"Starting New Game","Please Wait...", true);
new StartNewGame().execute();
private class StartNewGame extends AsyncTask<Void,Void,Boolean>{
@Override
protected Boolean doInBackground(Void... params) {
try{
ContentValues values = new ContentValues();
Cursor c = getContentResolver().query(Games.PART1_URI,new String[] {Games.PART1_NUM},
Games.PART1_GAME_ID+"="+gameID+" AND "+Games.PART1_FRAME_NUM+"="+10,null,null);
c.moveToFirst();
String num = c.getString(0);
int part1 =0;
if(num.equals("-")){
part1=0;
}else{
part1=Integer.parseInt(num);
}
c = getContentResolver().query(Games.PART2_URI,new String[] {Games.PART2_NUM},
Games.PART2_GAME_ID+"="+gameID+" AND "+Games.PART2_FRAME_NUM+"="+10,null,null);
c.moveToFirst();
int part2 = 0;
if(num.equals("-")){
part2=0;
}else{
part2=Integer.parseInt(num);
}
c = getContentResolver().query(Games.PART3_URI,new String[] {Games.PART3_NUM},
Games.PART3_GAME_ID+"="+gameID,null,null);
c.moveToFirst(); …Run Code Online (Sandbox Code Playgroud) 标题可能有点误导,我的问题更多的是为什么它以这种奇怪的方式工作.
所以我有一个具有TextView和ListView的布局的活动.我有一个长期运行的异步方法,准备在列表中显示数据.所以初始代码是这样的:
protected async override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MyView);
await SetupData();
}
private async Task SetupData(){
Task.Run(async () => {
var data = await new SlowDataLoader().LoadDataAsync();
// For simplicity setting data on the adapter is omitted here
});
}
Run Code Online (Sandbox Code Playgroud)
它的工作原理在某种意义上说它没有错误地执行.但是,活动显示为空白屏幕,即使文本视图仅在一定延迟后呈现.因此看起来任务实际上并非异步运行.在"await"调用上设置ConfigureAwait(false)没有帮助.将SetupData()调用移动到OnPostCreate,OnResume和OnPostResume无效.唯一让TextView立即出现并在以后呈现列表的东西,当数据到达时是这样的:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MyView);
new Handler().PostDelayed(async ()=>{
await SetupData();
}, 100);
}
Run Code Online (Sandbox Code Playgroud)
所以问题是,为什么不呢
await SetupData().ConfigureAwait(false);
Run Code Online (Sandbox Code Playgroud)
解锁流量?为什么我们必须强制延迟异步操作的开始以让UI完成渲染,尽管如此(根据http://www.wintellect.com/devcenter/paulballard/tasks-are-still-not-threads-and -async-is-not-parallel)SetupData应该可以在这里作为一个单独的线程运行?
ps删除在适配器上设置数据的代码不会影响此行为 - 在呈现屏幕之前仍有延迟.所以我不在这里展示代码.
int delay = 1000; // delay for 1 sec.
int period = 10000; // repeat every 10 sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
displayData(); // display the data
}
}, delay, period);
Run Code Online (Sandbox Code Playgroud)
和别的:
while(needToDisplayData)
{
displayData(); // display the data
Thread.sleep(10000); // sleep for 10 seconds
}
Run Code Online (Sandbox Code Playgroud)
它们都不起作用(应用程序强制关闭).我还可以尝试其他什么选择?
我对Android应用程序上的活动和线程之间的区别感到困惑。那么活动是否像独立线程一样?如果可以,那么多个活动可以同时在多线程应用程序中运行吗?
谢谢
我是初学者Android,我有一些困惑Android UI Thread.现在,我知道除了创建UI的线程之外没有任何线程可以修改它.
大.
这是Activity我的第一个Android应用程序,有点让我感到困惑.
public class NasaDailyImage extends Activity{
public ProgressDialog modalDialog = null;
//------------------------------------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState){
//Instantiate progress dialog, skipping details.
Button b = //get reference to button
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
modalDialog.show(); // show modal
Toast.makeText(getApplicationContext(), "Getting feeds", 500).show();
new AsyncRetriever().execute(new IotdHandler()); // Get the feeds !!
}
});
}
//------------------------------------------------------------------------------
public synchronized void resetDisplay(boolean parseErrorOccured,
boolean imageErrorOccured,
IotdHandler newFeeds){
if(parseErrorOccured || imageErrorOccured){ …Run Code Online (Sandbox Code Playgroud) runOnUiThread(new Runnable(){
@Override
public void run() {
System.out.println("print out from runOnUIThread.");
}
});
System.out.println("print out in main thread.");
Run Code Online (Sandbox Code Playgroud)
**Output:**
print out from runOnUIThread.
print out in main thread.
Run Code Online (Sandbox Code Playgroud)
基本上runOnUiThread将在后台线程中使用,我这样做只是为了测试。
上面的代码在Activity onCreate方法中执行。
从输出来看,结果不是我所期望的。我在想,既然将块runOnUiThread发布runnable到主线程,并且当前执行上下文已经在主线程中,所以runOnUiThread应该安排在“在主线程中打印”之后,但为什么结果不这样显示?我解释错了吗?谁能好心解释一下吗?
编辑:
哦,我应该先阅读 API。无论如何,这让我感到困惑的原因是,在 iOS 中,类似的机制表现不同:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Main thread from Dispatch.");
});
NSLog(@"Main thread.");
Run Code Online (Sandbox Code Playgroud)
上面的输出是相反的。
android ×10
java ×3
asynchronous ×1
c# ×1
concurrency ×1
handler ×1
looper ×1
ui-thread ×1
xamarin ×1