Java 打开internet连接时打开Android应用程序,否则显示无internet连接消息
我刚刚创建了一个android应用程序,用于从网站获取数据。我想检查设备是否连接了internet。如果设备有internet连接,请运行“我的代码”并获取数据并显示它,否则,如果设备没有internet连接,则显示“没有internet连接”消息。我已尝试使用此代码检查internet连接。当有internet连接时,如何调用代码 我的Java代码:Java 打开internet连接时打开Android应用程序,否则显示无internet连接消息,java,android,android-listview,connection,Java,Android,Android Listview,Connection,我刚刚创建了一个android应用程序,用于从网站获取数据。我想检查设备是否连接了internet。如果设备有internet连接,请运行“我的代码”并获取数据并显示它,否则,如果设备没有internet连接,则显示“没有internet连接”消息。我已尝试使用此代码检查internet连接。当有internet连接时,如何调用代码 我的Java代码: @Override public void onCreate(Bundle savedInstanceState) {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
new FetchWebsiteData().execute();
}
});
}
private class FetchWebsiteData extends AsyncTask<Void, Void, String[]> {
String websiteTitle, websiteDescription,websiteDescription1,websiteDescription2,websiteDescription3,listValue,listValue1;
ProgressDialog progress;
private Context context;
//check Internet connection.
private void checkInternetConnection(){
ConnectivityManager check = (ConnectivityManager) this.context.
getSystemService(Context.CONNECTIVITY_SERVICE);
if (check != null)
{
NetworkInfo[] info = check.getAllNetworkInfo();
if (info != null)
for (int i = 0; i <info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
Toast.makeText(context, "Internet is connected",
Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(context, "not conencted to internet",
Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
//some code here
}
@Override
protected String[] doInBackground(Void... params) {
ArrayList<String> hrefs=new ArrayList<String>();
try {
}
} catch (IOException e) {
e.printStackTrace();
}
//get the array list values
for(String s:hrefs)
{
//some code
}
//parsing first URL
String [] resultArray=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
//parsing second URL
String [] resultArray1=null;
try {
} catch (IOException e) {
e.printStackTrace();
}
try{
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String[] result) {
ListView list=(ListView)findViewById(R.id.listShow);
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,result);
list.setAdapter(arrayAdapter);
mProgressDialog.dismiss();
}
}
}
@覆盖
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_primary);
新建FetchWebsiteData().execute();
}
});
}
私有类FetchWebsiteData扩展异步任务{
字符串websiteTitle、websiteDescription、websiteDescription1、websiteDescription2、websiteDescription3、listValue、listValue1;
进程对话进程;
私人语境;
//检查互联网连接。
私有void checkInternetConnection(){
ConnectivityManager check=(ConnectivityManager)this.context。
getSystemService(Context.CONNECTIVITY\u服务);
如果(检查!=null)
{
NetworkInfo[]info=check.getAllNetworkInfo();
如果(信息!=null)
for(int i=0;i告诉您如何检查网络连接,然后将消息放在代码的“else”部分,创建一个类NetworkInformation.java
public static boolean hasInternetAccess(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection)
(new URL("http://clients3.google.com/generate_204")
.openConnection());
urlc.setRequestProperty("User-Agent", "Android");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 204 &&
urlc.getContentLength() == 0);
} catch (IOException e) {
Log.e(TAG, "Error checking internet connection", e);
}
} else {
Log.d(TAG, "No network available!");
}
return false;
}
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class NetworkInformation {
private static NetworkInfo networkInfo;
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
try{
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
} catch (Exception e) {
e.printStackTrace();
}
// test for connection for WIFI
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
networkInfo = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// test for connection for Mobile
if (networkInfo != null
&& networkInfo.isAvailable()
&& networkInfo.isConnected()) {
return true;
}
return false;
}
}
在调用异步任务之前,请检查网络是否可用,如下所示:
if(NetworkInformation.isConnected(YourClassName.this))
{
new FetchWebsiteData().execute();
}else{
Toast.makeText(NewsAndEvents.this,R.string.no_connection,Toast.LENGTH_LONG).show();
}
不要忘记在AndroidManifest.xml中包含以下权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
使用此方法检查网络可用性
public static boolean isNetworkAvailable(Context context) {
try{
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
boolean s= activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting();
return s;
}
catch(Exception e){
System.out.println("exception network"+e);
return false;
}
}
如果返回true,则可以继续进行网络调用,否则将发出网络不可用的消息。使用下面的代码并创建一个类,如networkavailability.java
public class NetworkAvailablity {
public static boolean checkNetworkStatus(Context context) {
boolean HaveConnectedWifi = false;
boolean HaveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
HaveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
HaveConnectedMobile = true;
}
return HaveConnectedWifi || HaveConnectedMobile;
}
}
在您的代码中,使用以下几行检查互联网是否可用
if (NetworkAvailablity.checkNetworkStatus(getActivity())) {
//code here
}
else
{
// give message here by Toast or create the alert dilog
Toast.makeText(context, "No network is available",Toast.LENGTH_LONG).show();
}
//在MainActivity中实现此代码,并检查是否已连接到Internet(),然后允许显示“无Internet连接”消息。
公共布尔值未连接到Internet(){
ConnectionManager连接=(ConnectionManager)\u上下文
.getSystemService(Context.CONNECTIVITY\u服务);
if(连接性!=null){
NetworkInfo[]info=connectivity.getAllNetworkInfo();
如果(信息!=null)
对于(int i=0;i
检查用户是否连接到wifi或任何接入点
最好先检查这个方法,看看用户是否有任何连接
若返回true,你们可以检查他是否和下一个方法有真正的联系
public static boolean isOnline(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
检查用户是否具有通过网络发送请求的真实流量
请注意,不应在主线程中调用hasTraffic()方法(可以使用AsyncTask)
检查internet连接
new AsyncTask<Void, Void, Boolean>() {
@Override
protected void onPostExecute(Boolean flag) {
if(flag == true){
// do whatever you want
}else{
cantAccessToService();
}
}
@Override
protected Boolean doInBackground(Void... voids) {
if(isOnline(SplashActivity.this) && hasTraffic() ){
return true ;
}else{
return false ;
}
}
}.execute();
newasynctask(){
@凌驾
受保护的void onPostExecute(布尔标志){
如果(标志==真){
//你想干什么就干什么
}否则{
cantAccessToService();
}
}
@凌驾
受保护的布尔doInBackground(Void…voids){
if(isOnline(SplashActivity.this)和&hasTraffic(){
返回true;
}否则{
返回false;
}
}
}.execute();
试试这个
//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
{
return netInfos.isConnected();
}
}
return false;
}
方法返回值后,必须进行检查
//detect internet and show the data
if(isNetworkStatusAvialable (getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
new FetchWebsiteData().execute();
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}
这是一节获取有关您的internet连接信息的课程
只需复制并粘贴代码并使用其方法即可
//check internet connection
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
{
return netInfos.isConnected();
}
}
return false;
}
//detect internet and show the data
if(isNetworkStatusAvialable (getApplicationContext())) {
Toast.makeText(getApplicationContext(), "Internet detected", Toast.LENGTH_SHORT).show();
new FetchWebsiteData().execute();
} else {
Toast.makeText(getApplicationContext(), "Please check your Internet Connection", Toast.LENGTH_SHORT).show();
}