我创建了一个DownloadManager,从RecyclerView适配器中下载两个文件,从项目中获取链接,
下载后将文件保存在外部存储器上,将其复制到内部,然后从外部删除,
然后我保存SQLite数据库上的文件的路径,然后在另一个RecyclerView上显示它。
到目前为止一切正常
唯一的一点就是它在db上多次保存了行,好像代码是在一个循环上,我说是因为,我为db ops和下载完成时设置了一个toast,并且那些toast出现多次,如以及在db上保存的条目。
在另一个recyclerview上,有多个项目出现,都是一样的
我设置了一个onclick监听器,我在Click上执行此代码
holder.downloadBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (CheckIsDataAlreadyInDBorNot(ctx, DBConstants.SavedItemsEntry.TABLE_NAME, DBConstants.SavedItemsEntry.COLUMN_TITLE, Title)) {
Toast.makeText(ctx, "Item ja Existente", Toast.LENGTH_SHORT).show();
}else {
DownloadClick(pdfurl, image, Title, Title);
BroadCReciever(Title, desc);
}
}catch (Exception e){
}
}
});
似乎循环的代码在BroadCast接收器上
这是广播接收器的代码:
private void BroadCReciever(final String filename, final String desc){
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
//IMAGE REQUEST QUERY SOLVER
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queue_id_img);
final Cursor c = dm.query(req_query);
if (c.moveToFirst()) checkStatus(c,"image");
{
int columnindex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnindex))
{
//DATA OBJECT
String UriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final Uri i = Uri.parse(UriString);
final File f = new File(i.getPath());
try {
Bitmap im;
im = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(),i);
// Initializing a new file
// The bellow line return a directory in internal storage
File fileimg = ctx.getDir("Images",MODE_PRIVATE);
// Create a file to save the image
fileimg = new File(fileimg, filename+".jpg");
try {
OutputStream stream = null;
stream = new FileOutputStream(fileimg);
im.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
//checking is image file exists in Internal Storage
if(fileimg.exists()) {
String internal_uri = fileimg.getAbsolutePath();
img_internal_uri = internal_uri;
} else {
Toast.makeText(ctx, "doesnt exist image", Toast.LENGTH_SHORT).show();
}
//deleting file from external storage
if (f.exists()){
Boolean deleted = f.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//IMAGE REQUEST QUERY SOLVER END
//PDF REQUEST QUERY SOLVER
DownloadManager.Query req_query2 = new DownloadManager.Query();
req_query2.setFilterById(queue_id_pdf);
final Cursor c2 = dm.query(req_query2);
if (c2.moveToFirst()) checkStatus(c2,"pdf");
{
int columnindex2 = c2.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c2.getInt(columnindex2))
{
//DATA OBJECT
String UriString = c2.getString(c2.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final Uri i = Uri.parse(UriString);
final File f = new File(i.getPath());
if (f.exists()){
// Initializing a new file
// The bellow line return a directory in internal storage
File file = ctx.getDir("PDF",MODE_PRIVATE);
// Create a file to save the pdf
file = new File(file,filename+".pdf");
try {
OutputStream outstream = new FileOutputStream(file);
InputStream instream = new FileInputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
outstream.flush();
outstream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
if (file.exists()) {
String internal_uri = file.getAbsolutePath();
pdf_internal_uri = internal_uri;
} else {
Toast.makeText(ctx, "doesnt exist pdf", Toast.LENGTH_SHORT).show();
}
Boolean deleted = f.delete();
}
}
}
//PDF REQUEST QUERY SOLVER END
checkifDOne(c,c2,filename,desc,img_internal_uri,pdf_internal_uri);
}
}
};
ctx.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
checkifDOne方法是保存数据的方法:
public void checkifDOne(Cursor c, Cursor c2, String Title, String desc, String img, String pdf){
int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status = c.getInt(columnIndex);
int columnIndex2 = c2.getColumnIndex(DownloadManager.COLUMN_STATUS);
int status2 = c2.getInt(columnIndex);
if (status == DownloadManager.STATUS_SUCCESSFUL && status2 == DownloadManager.STATUS_SUCCESSFUL){
saveToDB(ctx,Title,desc,img,pdf);
}
}
在那种方法中我们有:
public void saveToDB(Context c,String title, String desc, String img, String pdf){
DBAdapter db = new DBAdapter(c);
db.openDB();
long result = db.add(title,desc,img,pdf);
if (result == 1){
Toast.makeText(c, "item salvo para leitura offline", Toast.LENGTH_LONG).show();
Toast.makeText(c, img, Toast.LENGTH_SHORT).show();
Toast.makeText(c, pdf, Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(c, "Erro", Toast.LENGTH_SHORT).show();
}
db.CloseDB();
}
问题是你错过了使用BroadcastReceiver。就像现在一样,每当你打电话给你BroadCReceiver功能时,你就会创建并注册一个新的接收器。所以,如果你打电话十次,那么你将完成十次工作。
你需要做的是摆脱BroadCReceiver函数,只留下receiver
声明作为你的类中的一个字段,只需离开:
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)){
//IMAGE REQUEST QUERY SOLVER
DownloadManager.Query req_query = new DownloadManager.Query();
req_query.setFilterById(queue_id_img);
final Cursor c = dm.query(req_query);
if (c.moveToFirst()) checkStatus(c,"image");
{
int columnindex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c.getInt(columnindex))
{
//DATA OBJECT
String UriString = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final Uri i = Uri.parse(UriString);
final File f = new File(i.getPath());
try {
Bitmap im;
im = MediaStore.Images.Media.getBitmap(ctx.getContentResolver(),i);
// Initializing a new file
// The bellow line return a directory in internal storage
File fileimg = ctx.getDir("Images",MODE_PRIVATE);
// Create a file to save the image
fileimg = new File(fileimg, filename+".jpg");
try {
OutputStream stream = null;
stream = new FileOutputStream(fileimg);
im.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
//checking is image file exists in Internal Storage
if(fileimg.exists()) {
String internal_uri = fileimg.getAbsolutePath();
img_internal_uri = internal_uri;
} else {
Toast.makeText(ctx, "doesnt exist image", Toast.LENGTH_SHORT).show();
}
//deleting file from external storage
if (f.exists()){
Boolean deleted = f.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//IMAGE REQUEST QUERY SOLVER END
//PDF REQUEST QUERY SOLVER
DownloadManager.Query req_query2 = new DownloadManager.Query();
req_query2.setFilterById(queue_id_pdf);
final Cursor c2 = dm.query(req_query2);
if (c2.moveToFirst()) checkStatus(c2,"pdf");
{
int columnindex2 = c2.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL==c2.getInt(columnindex2))
{
//DATA OBJECT
String UriString = c2.getString(c2.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
final Uri i = Uri.parse(UriString);
final File f = new File(i.getPath());
if (f.exists()){
// Initializing a new file
// The bellow line return a directory in internal storage
File file = ctx.getDir("PDF",MODE_PRIVATE);
// Create a file to save the pdf
file = new File(file,filename+".pdf");
try {
OutputStream outstream = new FileOutputStream(file);
InputStream instream = new FileInputStream(f);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
outstream.flush();
outstream.close();
}catch (IOException e) // Catch the exception
{
e.printStackTrace();
}
if (file.exists()) {
String internal_uri = file.getAbsolutePath();
pdf_internal_uri = internal_uri;
} else {
Toast.makeText(ctx, "doesnt exist pdf", Toast.LENGTH_SHORT).show();
}
Boolean deleted = f.delete();
}
}
}
//PDF REQUEST QUERY SOLVER END
checkifDOne(c,c2,filename,desc,img_internal_uri,pdf_internal_uri);
}
}
};
所以现在receiver
在你的课堂上是独一无二的。
然后你需要注册它并根据你在Activity中的需要取消注册它? (或者你正在使用的其他主要类)生命周期。例如,您可以在onStart中注册它并在onStop中取消注册它,如:
@Override
public void onStart() {
super.onStart();
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
@Override
public void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
最后,当您想要发送广播事件(您在downloadBTN上的点击事件)时,只需执行以下操作:
Intent intent = new Intent();
intent.setAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
context.sendBroadcast(intent);
这样,您只需要一个已注册/未注册的接收器,并且每次点击只能正确处理您的任务一次。
或者,您可以在清单中注册接收器。如果你需要我,我可以解释如何做到这一点