Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/207.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 当应用程序在Android中运行时,如何检查互联网连接?_Java_Android - Fatal编程技术网

Java 当应用程序在Android中运行时,如何检查互联网连接?

Java 当应用程序在Android中运行时,如何检查互联网连接?,java,android,Java,Android,我是Android新手。这是一个我知道的基本问题,但我找不到任何合适的答案 这是我的密码 public class MainActivity extends ActionBarActivity { // Declare Variables JSONObject jsonobject; JSONArray jsonarray; ListView listview; ListViewAdapter adapter; ProgressDialog mProgressDialog; ArrayList&

我是Android新手。这是一个我知道的基本问题,但我找不到任何合适的答案

这是我的密码

public class MainActivity extends ActionBarActivity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String url = "https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA";

static String VIDEO_ID = "videoId";
static String TITLE = "title";
//static String DESCRIPTION = "description";
static String THUMBNAILS = "img";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from listview_main.xml
    setContentView(R.layout.listview_main);
    new DownloadJSON().execute();
    Object localObject = getIntent().getStringExtra("title");
    if (!isOnline())
    {
        localObject = new AlertDialog.Builder(this);
        ((AlertDialog.Builder)localObject).setTitle("Internet Alert");
        ((AlertDialog.Builder)localObject).setMessage("Please Check internet Conectivity and try again.");
        ((AlertDialog.Builder)localObject).setPositiveButton("OK", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
            {
                paramAnonymousDialogInterface.cancel();
            }
        });
        ((AlertDialog.Builder)localObject).create().show();
    }
    // Execute DownloadJSON AsyncTask





}
public boolean isOnline()
{
    NetworkInfo localNetworkInfo = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    boolean bool;
    if ((localNetworkInfo == null) || (!localNetworkInfo.isAvailable()) || (!localNetworkInfo.isConnectedOrConnecting())) {
        bool = false;
    } else {
        bool = true;
    }
    return bool;
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog title
        mProgressDialog.setTitle("Your Youtube Video is");
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();

        // Retrieve JSON Objects from the given URL address

        String query = "bangla natok 2015";
        query = query.replace(" ", "+");
        try {
            query = URLEncoder.encode(query, "utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
        }

        jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=natok+2015&maxResults=50&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA");

        try {
            // Locate the array name in JSON
            JSONArray jsonarray = jsonobject.getJSONArray("items");

            for (int i = 0; i < jsonarray.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                JSONObject jsonObjId = jsonobject.getJSONObject("id");
                map.put("videoId", jsonObjId.getString("videoId"));
                map.put ("img","http://img.youtube.com/vi/" + VIDEO_ID + "/hqdefault.jpg");

                JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
                map.put("title", jsonObjSnippet.getString("title"));

                //map.put("description", jsonObjSnippet.getString("description"));
                // map.put("flag", jsonobject.getString("flag"));




                // Set the JSON Objects into the array
                arraylist.add(map);
            }
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {
        // Locate the listview in listview_main.xml
        listview = (ListView) findViewById(R.id.listview);
        // Pass the results into ListViewAdapter.java
        adapter = new ListViewAdapter(MainActivity.this, arraylist);
        // Set the adapter to the ListView
        listview.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
    }
}
公共类MainActivity扩展了ActionBarActivity{
//声明变量
JSONObject JSONObject;
JSONArray JSONArray;
列表视图列表视图;
ListViewAdapter适配器;
进程对话框;
ArrayList ArrayList;
静态字符串url=”https://www.googleapis.com/youtube/v3/search?part=snippet&maxResult=30&q=natok+bangla+mosharrof+karim&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA”;
静态字符串VIDEO_ID=“videoId”;
静态字符串TITLE=“TITLE”;
//静态字符串DESCRIPTION=“DESCRIPTION”;
静态字符串缩略图=“img”;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//从listview_main.xml获取视图
setContentView(R.layout.listview_main);
新建下载JSON().execute();
对象localObject=getIntent().getStringExtra(“标题”);
如果(!isOnline())
{
localObject=new AlertDialog.Builder(此);
((AlertDialog.Builder)localObject).setTitle(“Internet警报”);
((AlertDialog.Builder)localObject).setMessage(“请检查internet连接并重试”);
((AlertDialog.Builder)localObject).setPositiveButton(“确定”,新的DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface,int paramAnonymousInt)
{
paramAnonymousDialogInterface.cancel();
}
});
((AlertDialog.Builder)localObject).create().show();
}
//执行下载JSON异步任务
}
公共布尔isOnline()
{
NetworkInfo localNetworkInfo=((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
布尔布尔;
如果((localNetworkInfo==null)| |(!localNetworkInfo.isAvailable())| |(!localNetworkInfo.isConnectedOrConnecting())){
布尔=假;
}否则{
布尔=真;
}
返回布尔;
}
//下载JSON异步任务
私有类下载JSON扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
//创建一个progressdialog
mProgressDialog=新建ProgressDialog(MainActivity.this);
//设置进程对话框标题
setTitle(“你的Youtube视频是”);
//设置进程对话框消息
设置消息(“加载…”);
mProgressDialog.setUndeterminate(false);
//显示进度对话框
mProgressDialog.show();
}
@凌驾
受保护的Void doInBackground(Void…参数){
//创建一个数组
arraylist=新的arraylist();
//从给定的URL地址检索JSON对象
字符串查询=“bangla natok 2015”;
query=query.replace(“,“+”);
试一试{
query=URLEncoder.encode(查询“utf-8”);
}捕获(不支持的编码异常e){
//TODO自动生成的捕捉块
//e、 printStackTrace();
}
jsonobject=JSONfunctions.getJSONfromURL(“https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=natok+2015年&maxResults=50&key=AIzaSyCR40QlsuX0aFfBV-wEPDsH_jxna1tDFRA”);
试一试{
//在JSON中找到数组名称
JSONArray JSONArray=jsonobject.getJSONArray(“项”);
for(int i=0;i
我检查了这个代码100次,但没有发现任何错误。但当它在设备上运行时,它会停止运行,而不打开我的主布局

我还在清单中添加了一些权限

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>

现在谁能找到这个问题

请把我放在这里。

试试这个

AndroidManifest.xml

  <?xml version="1.0" encoding="utf-8"?>
  <manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.example.detectinternetconnection"
      android:versionCode="1"
      android:versionName="1.0" >

      <uses-sdk android:minSdkVersion="8" />

      <application
          android:icon="@drawable/ic_launcher"
          android:label="@string/app_name" >
          <activity
              android:name=".AndroidDetectInternetConnectionActivity"
              android:label="@string/app_name" >
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />

                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>
      </application>

      <!-- Internet Permissions -->
      <uses-permission android:name="android.permission.INTERNET" />

      <!-- Network State Permissions -->
      <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

  </manifest>

你能从logcat窗口发布异常详细信息吗?logcat中没有任何视图logcat中没有任何内容,因为我的布局未打开。请再次检查你的logcat,没有任何堆栈跟踪,应用程序无法崩溃。我再次检查,但logcat每次都为空/空白?不工作…相同的问题我已更新答案我不需要任何更改按钮我只想在我的应用程序启动时检查我的Internet连接是否打开。如果Internet连接关闭,则会显示一个对话框。无论是启动我的主应用程序还是在我的应用程序主页上不需要任何类型的按钮
  import android.content.Context;
  import android.net.ConnectivityManager;
  import android.net.NetworkInfo;

  public class ConnectionDetector {

      private Context _context;

      public ConnectionDetector(Context context){
          this._context = context;
      }

      public boolean isConnectingToInternet(){
          ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) 
            {
                NetworkInfo[] info = connectivity.getAllNetworkInfo();
                if (info != null) 
                    for (int i = 0; i < info.length; i++) 
                        if (info[i].getState() == NetworkInfo.State.CONNECTED)
                        {
                            return true;
                        }

            }
            return false;
      }
  }
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AndroidDetectInternetConnectionActivity extends Activity {

    // flag for Internet connection status
    Boolean isInternetPresent = false;

    // Connection detector class
    ConnectionDetector cd;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button btnStatus = (Button) findViewById(R.id.btn_check);

        // creating connection detector class instance
        cd = new ConnectionDetector(getApplicationContext());

        /**
         * Check Internet status button click event
         * */

        // get Internet status
        isInternetPresent = cd.isConnectingToInternet();

        // check for Internet status
        if (isInternetPresent) {
            // Internet Connection is Present
            // make HTTP requests
            showAlertDialog(AndroidDetectInternetConnectionActivity.this, "Internet Connection",
                    "You have internet connection", true);
        } else {
            // Internet connection is not present
            // Ask user to connect to Internet
            showAlertDialog(AndroidDetectInternetConnectionActivity.this, "No Internet Connection",
                    "You don't have internet connection.", false);
        }
    }

    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     * */
    public void showAlertDialog(Context context, String title, String message, Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting alert dialog icon
        alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}