gpt4 book ai didi

android - 在 Android 中下载背景图片时需要帮助吗?

转载 作者:可可西里 更新时间:2023-11-01 19:01:18 27 4
gpt4 key购买 nike

我有一个 ImageView ,我写了刷卡,在刷卡的时候,图片是从互联网上下载的,所以我想我必须在刷卡之前在后台下载图片,为此我需要使用 asynctask或 Service 或 IntentService,所有这些都将有助于下载和存储在 data/data/mypackages 中,但在我的情况下滑动仍然变慢任何想法,也告诉我哪个是最好的,我是否以正确的方式调用

<强>1。异步任务

<强>2。服务

<强>3。 Intent Service如下图,

我很困惑哪一个是正确的方法,因为我的问题还没有解决

这是异步任务代码示例 fragment

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



}

}

最佳答案

使用服务下载它的最佳方式就像我从服务器下载文件并放入 SD 卡一样,也使用它的通知。 这是相当长的代码,但我认为是完美的代码,如果有任何不明白的地方,请访问 android 开发者博客获取服务。

public class DownloadService extends Service{

SharedPreferences preferences;

private static final String DOCUMENT_VIEW_STATE_PREFERENCES = "DjvuDocumentViewState";

private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private NotificationManager mNM;
String downloadUrl;
public static boolean serviceState=false;

// Handler that receives messages from the thread
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
downloadFile();
showNotification(getResources().getString(R.string.notification_catalog_downloaded),"VVS");
stopSelf(msg.arg1);
}
}


@Override
public void onCreate() {
serviceState=true;
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
HandlerThread thread = new HandlerThread("ServiceStartArguments",1);
thread.start();

// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);

}



@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("SERVICE-ONCOMMAND","onStartCommand");

Bundle extra = intent.getExtras();
if(extra != null){
String downloadUrl = extra.getString("downloadUrl");
Log.d("URL",downloadUrl);

this.downloadUrl=downloadUrl;
}

Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);

// If we get killed, after returning from here, restart
return START_STICKY;
}



@Override
public void onDestroy() {

Log.d("SERVICE-DESTROY","DESTORY");
serviceState=false;
//Toast.makeText(this, "service done", Toast.LENGTH_SHORT).show();
}


@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}


public void downloadFile(){

downloadFile(this.downloadUrl,fileName);


}



void showNotification(String message,String title) {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = message;

// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.icon, "vvs",
System.currentTimeMillis());
notification.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this, HomeScreenActivity.class);
intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
//The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this.getBaseContext(), 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);

// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title,
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.app_name, notification);
}

public void downloadFile(String fileURL, String fileName) {

StatFs stat_fs = new StatFs(Environment.getExternalStorageDirectory().getPath());
double avail_sd_space = (double)stat_fs.getAvailableBlocks() *(double)stat_fs.getBlockSize();
//double GB_Available = (avail_sd_space / 1073741824);
double MB_Available = (avail_sd_space / 10485783);
//System.out.println("Available MB : " + MB_Available);
Log.d("MB",""+MB_Available);
try {
File root =new File(Environment.getExternalStorageDirectory()+"/vvveksperten");
if(root.exists() && root.isDirectory()) {

}else{
root.mkdir();
}
Log.d("CURRENT PATH",root.getPath());
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
int fileSize = c.getContentLength()/1048576;
Log.d("FILESIZE",""+fileSize);
if(MB_Available <= fileSize ){
this.showNotification(getResources().getString(R.string.notification_no_memory),getResources().getString(R.string.notification_error));
c.disconnect();
return;
}

FileOutputStream f = new FileOutputStream(new File(root.getPath(), fileName));

InputStream in = c.getInputStream();


byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
File file = new File(root.getAbsolutePath() + "/" + "some.pdf");
if(file.exists()){
file.delete();
Log.d("FILE-DELETE","YES");
}else{
Log.d("FILE-DELETE","NO");
}
File from =new File(root.getAbsolutePath() + "/" + fileName);
File to = new File(root.getAbsolutePath() + "/" + "some.pdf");


} catch (Exception e) {
Log.d("Downloader", e.getMessage());

}

关于android - 在 Android 中下载背景图片时需要帮助吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6303365/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com