Android Studio – 当没有网络连接时禁用下载按钮/活动

huangapple go评论74阅读模式
英文:

Android studio- disable donwload button/Activity when internet not availabe

问题

我在我的应用程序中配置了一个下载按钮当我在没有互联网连接的情况下点击下载按钮时按钮会被点击当有互联网连接时下载活动开始并且文件被下载了我在断网时点击的次数

是否有任何方法可以在没有互联网连接时禁用下载活动并显示一个消息检查您的互联网连接”。

MainActivity
public class Download_Activity extends AppCompatActivity {

    FirebaseFirestore downdb;
    RecyclerView downRecyclerView;
    ArrayList<Downloadsmodel> downloadsmodelArrayList = new ArrayList<>();
    DownloadsAdapter downloadsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download_);

        setUpRV();
        setUpFB();
        dataFromFirebase();
    }

    private void dataFromFirebase() {
        downdb.collection("Downloads").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for (DocumentSnapshot documentSnapshot : task.getResult()) {

                    Downloadsmodel downloadsmodel = new Downloadsmodel(documentSnapshot.getString("name"),
                            documentSnapshot.getString("link"), documentSnapshot.getString("fileextension"),
                            documentSnapshot.getString("uploaddate"), documentSnapshot.getString("icon"));
                    downloadsmodelArrayList.add(downloadsmodel);
                }
                downloadsAdapter = new DownloadsAdapter(Download_Activity.this, downloadsmodelArrayList);
                downRecyclerView.setAdapter(downloadsAdapter);
            }
        })

        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(Download_Activity.this, "Error", Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void setUpFB() {
        downdb = FirebaseFirestore.getInstance();
    }

    private void setUpRV() {
        downRecyclerView = findViewById(R.id.drecyclerdownloads);
        downRecyclerView.setHasFixedSize(true);
        downRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
}

Download Adapter

public class DownloadsAdapter extends RecyclerView.Adapter<Downloadsviewholder> {

    Download_Activity download_activity;
    ArrayList<Downloadsmodel> downloadsmodels;

    public DownloadsAdapter(Download_Activity download_activity, ArrayList<Downloadsmodel> downloadsmodels) {
        this.download_activity = download_activity;
        this.downloadsmodels = downloadsmodels;
    }

    @NonNull
    @Override
    public Downloadsviewholder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
        LayoutInflater layoutInflater = LayoutInflater.from(download_activity.getBaseContext());
        View view = layoutInflater.inflate(R.layout.downloads_elements, null, false);
        return new Downloadsviewholder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull final Downloadsviewholder downloadsviewholder, final int i) {
        downloadsviewholder.dName.setText(downloadsmodels.get(i).getName());
        downloadsviewholder.dUploaddate.setText(downloadsmodels.get(i).getUploaddate());
        downloadsviewholder.dExtension.setText(downloadsmodels.get(i).getFileextension());
        Picasso.get().load(downloadsmodels.get(i).getIcon()).into(downloadsviewholder.dIcon);
        downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dowloadFile(downloadsviewholder.dName.getContext(), downloadsmodels.get(i).getName(),
                        downloadsmodels.get(i).getFileextension(), DIRECTORY_DOWNLOADS, downloadsmodels.get(i).getLink());
            }
        });
    }

    public void dowloadFile(Context context, String filename, String fileextension,
                            String destinationdirectory, String url) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(url);
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        request.setDestinationInExternalFilesDir(context, destinationdirectory, filename + fileextension);
        downloadManager.enqueue(request);
    }

    @Override
    public int getItemCount() {
        return downloadsmodels.size();
    }
}
英文:

I have a download button configured in my app. When I click the download button when the internet is not available, the button is getting clicked. When the internet is available, this download activity begins and the file is downloaded no of the times I clicked when the internet was offline.

Is there any way I can disable by download activity when internet is unavailable by giving a message check your internet connection'.

MainActivity


public class Download_Activity extends AppCompatActivity {
FirebaseFirestore downdb;
RecyclerView downRecyclerView;
ArrayList&lt;Downloadsmodel&gt; downloadsmodelArrayList=new ArrayList&lt;&gt;();
DownloadsAdapter downloadsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_);
setUpRV();
setUpFB();
dataFromFirebase();
}
private void dataFromFirebase() {
downdb.collection(&quot;Downloads&quot;).get().addOnCompleteListener(new OnCompleteListener&lt;QuerySnapshot&gt;() {
@Override
public void onComplete(@NonNull Task&lt;QuerySnapshot&gt; task) {
for(DocumentSnapshot documentSnapshot: task.getResult()){
Downloadsmodel downloadsmodel= new Downloadsmodel(documentSnapshot.getString(&quot;name&quot;)
,documentSnapshot.getString(&quot;link&quot;),documentSnapshot.getString(&quot;fileextension&quot;),documentSnapshot.getString(&quot;uploaddate&quot;),documentSnapshot.getString(&quot;icon&quot;));
downloadsmodelArrayList.add(downloadsmodel);
}
downloadsAdapter= new DownloadsAdapter(Download_Activity.this,downloadsmodelArrayList);
downRecyclerView.setAdapter(downloadsAdapter);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(Download_Activity.this,&quot;Error&quot;,  Toast.LENGTH_SHORT).show();
}
});
}
private void setUpFB() {
downdb=FirebaseFirestore.getInstance();
}
private void setUpRV() {
downRecyclerView=findViewById(R.id.drecyclerdownloads);
downRecyclerView.setHasFixedSize(true);
downRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}
}

Download Adapter


public class DownloadsAdapter extends RecyclerView.Adapter&lt;Downloadsviewholder&gt; {
Download_Activity download_activity;
ArrayList&lt;Downloadsmodel&gt; downloadsmodels;
public DownloadsAdapter(Download_Activity download_activity, ArrayList&lt;Downloadsmodel&gt; downloadsmodels) {
this.download_activity = download_activity;
this.downloadsmodels = downloadsmodels;
}
@NonNull
@Override
public Downloadsviewholder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
LayoutInflater layoutInflater = LayoutInflater.from(download_activity.getBaseContext());
View view = layoutInflater.inflate(R.layout.downloads_elements,null,false);
return new Downloadsviewholder(view);
}
@Override
public void onBindViewHolder(@NonNull final Downloadsviewholder downloadsviewholder, final int i) {
downloadsviewholder.dName.setText(downloadsmodels.get(i).getName());
downloadsviewholder.dUploaddate.setText(downloadsmodels.get(i).getUploaddate());
downloadsviewholder.dExtension.setText(downloadsmodels.get(i).getFileextension());
Picasso.get().load(downloadsmodels.get(i).getIcon()).into(downloadsviewholder.dIcon);
downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());
}
});
}
public void dowloadFile (Context context,String filename, String fileextension, String destinationdirectory, String url){
DownloadManager downloadManager=(DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
Uri uri=Uri.parse(url);
DownloadManager.Request request=new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(context, destinationdirectory, filename+fileextension);
downloadManager.enqueue(request);
}
@Override
public int getItemCount() {
return downloadsmodels.size();
}
}

答案1

得分: 1

使用此函数检查互联网连接:

protected boolean isInternetConnected() {
    ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    } else {
        return false;
    }
}

在你的 BindViewHolder 中使用如下方式:

downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if (isInternetConnected()) {
            dowloadFile(
                downloadsviewholder.dName.getContext(),
                downloadsmodels.get(i).getName(),
                downloadsmodels.get(i).getFileextension(),
                DIRECTORY_DOWNLOADS,
                downloadsmodels.get(i).getLink()
            );
        } else {
            // 如果需要,更改按钮颜色,使其看起来像是禁用的
        }
    }
});
英文:

Use this function to check the internet connectivity

   protected boolean isInternetConnected() {
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null &amp;&amp; netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}

Inside your BindViewHolder use like this:

   downloadsviewholder.dButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isInternetConnected()){
dowloadFile(downloadsviewholder.dName.getContext(),downloadsmodels.get(i).getName(),downloadsmodels.get(i).getFileextension()
,DIRECTORY_DOWNLOADS,downloadsmodels.get(i).getLink());
} else {
//Change your button color so it looks like disable if you want 
}
}
});
</details>

huangapple
  • 本文由 发表于 2020年5月29日 20:39:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/62086247.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定