我有一个图像视图,我写了滑动,在滑动的时候,图像是从互联网下载的,所以我想我必须在滑动之前在后台下载图像,对于我需要使用 asynctask 或服务或IntentService,所有这些都将有助于下载和存储在 data/data/mypackages 中,但在我的情况下仍然刷卡会变慢任何想法,也告诉我哪个是最好的,我是否以正确的方式调用
1.异步任务
2. 服务
3. Intent Service如下图,
我很困惑哪一个是正确的方法,因为我的问题还没有解决
这是 asynctask 代码示例片段
public class Demo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new FirstTask().execute(); // calling Asynctask here
}
}
异步任务代码
private class FirstTask extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(Catalogue.this);
int temp = 0;
// can use UI thread here
protected void onPreExecute() {
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(false);
//this.dialog.show();
System.gc();
Toast.makeText(Catalogue.this, "My Async Created",
Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... params) {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e) {
Util.trace("Error in Async"+e.getMessage());
}
Looper.loop();
return null;
}
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
Toast.makeText(Catalogue.this, "My Async destroyed",
Toast.LENGTH_LONG).show();
Toast.makeText(Catalogue.this, "count" + temp,
Toast.LENGTH_LONG).show();
this.dialog.dismiss();
}
}
}
这是我的服务
public class MyService extends Service implements Runnable
{ @Override
public void onCreate() {
super.onCreate();
Thread mythread = new Thread(this);
mythread.start();
}
public void run() {
Looper.prepare();
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Looper.loop();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Invoking Service
public class ServicesDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this, MyService.class));
}
}
这是 IntentService 代码
public class Downloader extends IntentService {
public Downloader() {
super("Downloader");
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onHandleIntent(Intent i) {
try {
myddownloadmethod();// calling my download method
} catch (Exception e1) {
// TODO Auto-generated catch block
Log.d("Error",e1.getMessage());
}
}
}
从 MyActivity 调用 IntentService
public class ServicesDemo extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent i1=new Intent(this, Downloader.class);
startService(i1);
}
}