检查是否连接

时间:2014-01-30 11:55:55

标签: android android-intent

logcat输出是这个..

 01-30 06:34:43.633: D/AndroidRuntime(1228): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
    01-30 06:34:43.643: D/AndroidRuntime(1228): CheckJNI is ON
    01-30 06:34:43.703: D/dalvikvm(1228): Trying to load lib libjavacore.so 0x0
    01-30 06:34:43.713: D/dalvikvm(1228): Added shared lib libjavacore.so 0x0
    01-30 06:34:43.733: D/dalvikvm(1228): Trying to load lib libnativehelper.so 0x0
    01-30 06:34:43.743: D/dalvikvm(1228): Added shared lib libnativehelper.so 0x0
    01-30 06:34:43.743: D/dalvikvm(1228): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
    01-30 06:34:43.933: D/dalvikvm(1228): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
    01-30 06:34:44.463: E/memtrack(1228): Couldn't load memtrack module (No such file or directory)
    01-30 06:34:44.463: E/android.os.Debug(1228): failed to load memtrack module: -2
    01-30 06:34:44.743: D/AndroidRuntime(1228): Calling main entry com.android.commands.pm.Pm
    01-30 06:34:44.783: D/AndroidRuntime(1228): Shutting down VM
    01-30 06:34:44.783: D/dalvikvm(1228): Debugger has detached; object registry had 1 entries
    01-30 06:34:45.503: D/AndroidRuntime(1239): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
    01-30 06:34:45.503: D/AndroidRuntime(1239): CheckJNI is ON
    01-30 06:34:45.563: D/dalvikvm(1239): Trying to load lib libjavacore.so 0x0
    01-30 06:34:45.573: D/dalvikvm(1239): Added shared lib libjavacore.so 0x0
    01-30 06:34:45.593: D/dalvikvm(1239): Trying to load lib libnativehelper.so 0x0
    01-30 06:34:45.593: D/dalvikvm(1239): Added shared lib libnativehelper.so 0x0
    01-30 06:34:45.603: D/dalvikvm(1239): No JNI_OnLoad found in libnativehelper.so 0x0, skipping init
    01-30 06:34:45.863: D/dalvikvm(1239): Note: class Landroid/app/ActivityManagerNative; has 179 unimplemented (abstract) methods
    01-30 06:34:46.373: E/memtrack(1239): Couldn't load memtrack module (No such file or directory)
    01-30 06:34:46.373: E/android.os.Debug(1239): failed to load memtrack module: -2
    01-30 06:34:46.653: D/AndroidRuntime(1239): Calling main entry com.android.commands.am.Am
    01-30 06:34:46.723: I/ActivityManager(379): START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.ptuxiaki.stockpredictions/.MainActivity} from pid 1239
    01-30 06:34:46.763: E/gralloc_goldfish(50): gralloc_alloc: Mismatched usage flags: 328 x 583, usage 333
    01-30 06:34:46.763: W/GraphicBufferAllocator(50): alloc(328, 583, 1, 00000333, ...) failed -22 (Invalid argument)
    01-30 06:34:46.763: E/(50): GraphicBufferAlloc::createGraphicBuffer(w=328, h=583) failed (Invalid argument), handle=0x0
    01-30 06:34:46.763: E/BufferQueue(379): [ScreenshotClient] dequeueBuffer: SurfaceComposer::createGraphicBuffer failed
    01-30 06:34:46.763: W/WindowManager(379): Screenshot failure taking screenshot for (328x583) to layer 21005
    01-30 06:34:46.783: D/AndroidRuntime(1239): Shutting down VM
    01-30 06:34:46.803: D/jdwp(1239): Got wake-up signal, bailing out of select
    01-30 06:34:46.803: D/dalvikvm(1239): Debugger has detached; object registry had 1 entries
    01-30 06:34:46.833: D/dalvikvm(1250): Not late-enabling CheckJNI (already on)
    01-30 06:34:46.833: I/ActivityManager(379): Start proc com.ptuxiaki.stockpredictions for activity com.ptuxiaki.stockpredictions/.MainActivity: pid=1250 uid=10054 gids={50054, 3003}
    01-30 06:34:47.513: D/dalvikvm(1250): GC_FOR_ALLOC freed 47K, 4% free 3137K/3256K, paused 57ms, total 59ms
    01-30 06:34:47.533: I/dalvikvm-heap(1250): Grow heap (frag case) to 4.202MB for 1127536-byte allocation
    01-30 06:34:47.603: D/dalvikvm(1250): GC_FOR_ALLOC freed 2K, 3% free 4235K/4360K, paused 71ms, total 71ms
    01-30 06:34:47.813: D/AndroidRuntime(1250): Shutting down VM
    01-30 06:34:47.813: W/dalvikvm(1250): threadid=1: thread exiting with uncaught exception (group=0xb1b06ba8)
    01-30 06:34:47.823: E/AndroidRuntime(1250): FATAL EXCEPTION: main
    01-30 06:34:47.823: E/AndroidRuntime(1250): Process: com.ptuxiaki.stockpredictions, PID: 1250
    01-30 06:34:47.823: E/AndroidRuntime(1250): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ptuxiaki.stockpredictions/com.ptuxiaki.stockpredictions.MainActivity}: java.lang.NullPointerException
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.os.Handler.dispatchMessage(Handler.java:102)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.os.Looper.loop(Looper.java:136)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread.main(ActivityThread.java:5017)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at java.lang.reflect.Method.invokeNative(Native Method)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at java.lang.reflect.Method.invoke(Method.java:515)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at dalvik.system.NativeStart.main(Native Method)
    01-30 06:34:47.823: E/AndroidRuntime(1250): Caused by: java.lang.NullPointerException
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at com.ptuxiaki.stockpredictions.MainActivity.onCreate(MainActivity.java:55)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.Activity.performCreate(Activity.java:5231)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    01-30 06:34:47.823: E/AndroidRuntime(1250):     ... 11 more
    01-30 06:34:47.823: W/ActivityManager(379):   Force finishing activity com.ptuxiaki.stockpredictions/.MainActivity
    01-30 06:34:48.013: D/dalvikvm(1250): GC_FOR_ALLOC freed 217K, 6% free 4532K/4816K, paused 22ms, total 22ms
    01-30 06:34:48.243: I/WindowManager(379): Screenshot max retries 4 of Token{b215f238 ActivityRecord{b2373780 u0 com.ptuxiaki.stockpredictions/.MainActivity t6 f}} appWin=Window{b22ec3a8 u0 Starting com.ptuxiaki.stockpredictions} drawState=4
    01-30 06:34:48.243: W/WindowManager(379): Screenshot failure taking screenshot for (720x1280) to layer 21010
    01-30 06:34:48.773: W/ActivityManager(379): Activity pause timeout for ActivityRecord{b2373780 u0 com.ptuxiaki.stockpredictions/.MainActivity t6 f}
    01-30 06:34:48.883: W/EGL_emulation(540): eglSurfaceAttrib not implemented
    01-30 06:34:49.933: D/LightsService(379): Excessive delay setting light: 218ms
    01-30 06:34:50.033: E/SoundPool(379): error loading /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.033: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.033: E/SoundPool(379): error loading /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.033: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.033: E/SoundPool(379): error loading /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.033: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.053: E/SoundPool(379): error loading /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.053: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.053: E/SoundPool(379): error loading /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.053: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg
    01-30 06:34:50.053: E/SoundPool(379): error loading /system/media/audio/ui/KeypressStandard.ogg
    01-30 06:34:50.053: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg
    01-30 06:34:50.063: W/InputMethodManagerService(379): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@b2385490 attribute=null, token = android.os.BinderProxy@b20c9ac8
    01-30 06:34:50.073: E/SoundPool(379): error loading /system/media/audio/ui/KeypressSpacebar.ogg
    01-30 06:34:50.073: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg
    01-30 06:34:50.073: E/SoundPool(379): error loading /system/media/audio/ui/KeypressDelete.ogg
    01-30 06:34:50.073: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg
    01-30 06:34:50.073: E/SoundPool(379): error loading /system/media/audio/ui/KeypressReturn.ogg
    01-30 06:34:50.073: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg
    01-30 06:34:50.083: E/SoundPool(379): error loading /system/media/audio/ui/KeypressInvalid.ogg
    01-30 06:34:50.083: W/AudioService(379): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg
    01-30 06:34:50.083: W/AudioService(379): onLoadSoundEffects(), Error -1 while loading samples
    01-30 06:34:50.083: I/Process(1250): Sending signal. PID: 1250 SIG: 9
    01-30 06:34:50.103: D/LightsService(379): Excessive delay setting light: 124ms
    01-30 06:34:50.113: I/ActivityManager(379): Process com.ptuxiaki.stockpredictions (pid 1250) has died.
    01-30 06:34:50.113: I/WindowState(379): WIN DEATH: Window{b23292d0 u0 com.ptuxiaki.stockpredictions/com.ptuxiaki.stockpredictions.MainActivity}
    01-30 06:34:50.203: D/LightsService(379): Excessive delay setting light: 109ms

我的代码是......当我尝试运行它时说已停止工作......我在清单中拥有权限access_network_state。任何人都可以指出我做错了什么?我想做的是当应用程序开始检测是否有网络连接,如果它是我在onCreate做我做的,如果它不是创建一个警告对话框,当用户按下确定启动设置wifi页面,以便能够打开wifi ..请帮助我...

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class MainActivity extends Activity {
 private String jsonResult;
 private String url = "http://spinner.bl.ee/getstocks.php";
 private ListView listView;
 ProgressDialog pDialog;
private Activity context;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  listView = (ListView) findViewById(R.id.listView1);
  accessWebService();
  onDetectConnected();
  registerCallClickBack();
 }

 public void onDetectConnected(){
     ConnectivityManager cm = (ConnectivityManager) context
             .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean network_connected = activeNetwork != null
             && activeNetwork.isAvailable();
        if(!network_connected){
            onDetectNetworkState().show();
        }
 }

public AlertDialog onDetectNetworkState(){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Εντοπίστηκε πρόβλημμα με τη σύνδεση στο διαδύκτιο. Παρακαλώ συνδεθήτε στο διαδύκτιο.")
.setTitle("Χωρίς σύνδεση δικτύου")
.setNegativeButton("Άκυρο",new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        MainActivity.this.finish();
    }
})       
.setPositiveButton("Οκ",new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
    }
});
    return builder1.create();
}

 @Override
public void onBackPressed() {
    // TODO Auto-generated method stub
     onCreateDialogBack().show();
}
public AlertDialog onCreateDialogBack(){
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.exit)
                .setMessage(R.string.exit_message)
                .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        MainActivity.this.finish();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();
                    }
                });
        return builder.create();
}
private void registerCallClickBack() {
    // TODO Auto-generated method stub
    ListView list = (ListView)findViewById(R.id.listView1);
    list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                long id) {
            // TODO Auto-generated method stub
            String message = "Έχετε επιλέξει την " + id + "η μετοχή";
            Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
        }
    });
}

@Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

 // Async Task to access the web
 private class JsonReadTask extends AsyncTask<String, Void, String> {
     @Override
     protected void onPreExecute() {
         super.onPreExecute();
         pDialog = new ProgressDialog(MainActivity.this);
         pDialog.setMessage("Γίνεται Λήψη μετοχών...");
         pDialog.setCancelable(false);
         pDialog.show();

     }
  @Override
  protected String doInBackground(String... params) {
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(params[0]);
   try {
    HttpResponse response = httpclient.execute(httppost);
    jsonResult = inputStreamToString(
      response.getEntity().getContent()).toString();
   }

   catch (ClientProtocolException e) {
    e.printStackTrace();
   } catch (IOException e) {
    e.printStackTrace();
   }
   return null;
  }

  private StringBuilder inputStreamToString(InputStream is) {
   String rLine = "";
   StringBuilder answer = new StringBuilder();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   try {
    while ((rLine = rd.readLine()) != null) {
     answer.append(rLine);
    }
   }

   catch (IOException e) {
    // e.printStackTrace();
    Toast.makeText(getApplicationContext(),
      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
   }
   return answer;
  }

  @Override
  protected void onPostExecute(String result) {

   ListDrwaer();
   pDialog.dismiss();
  }

 }// end async task

 public void accessWebService() {
  JsonReadTask task = new JsonReadTask();
  // passes values for the urls string array
  task.execute(new String[] { url });
 }

 // build hash set for list view
 public void ListDrwaer() {
  List<Map<String, String>> stocksList = new ArrayList<Map<String, String>>();

  try {
   JSONObject jsonResponse = new JSONObject(jsonResult);
   JSONArray jsonMainNode = jsonResponse.optJSONArray("metoxes");

   for (int i = 0; i < jsonMainNode.length(); i++) {
    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
    String name = jsonChildNode.optString("name");
    String number = jsonChildNode.optString("price");
    String id = jsonChildNode.optString("id");
    String outPut =id + ") " + name + " - " + number;
    stocksList.add(createStockList("metoxes", outPut));
   }

  } catch (JSONException e) {
   Toast.makeText(getApplicationContext(), "Error" + e.toString(),
     Toast.LENGTH_SHORT).show();
  }

  SimpleAdapter simpleAdapter = new SimpleAdapter(this, stocksList,
    android.R.layout.simple_list_item_1,
    new String[] { "metoxes" }, new int[] { android.R.id.text1 });
  listView.setAdapter(simpleAdapter);
 }

 private HashMap<String, String> createStockList(String name, String number) {
  HashMap<String, String> employeeNameNo = new HashMap<String, String>();
  employeeNameNo.put(name, number);

  return employeeNameNo;
 }
}

我的清单文件就是这个......

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher_stock"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.ptuxiaki.stockpredictions.MainActivity"
            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>

</manifest>

从我看来我有问题

01-30 07:10:19.463: E/AndroidRuntime(1720):     at com.ptuxiaki.stockpredictions.MainActivity.onDetectConnected(MainActivity.java:58)
01-30 07:10:19.463: E/AndroidRuntime(1720):     at com.ptuxiaki.stockpredictions.MainActivity.onCreate(MainActivity.java:53)

第53行是:

onDetectConnected();

第58行是:

ConnectivityManager cm = (ConnectivityManager) context
             .getSystemService(Context.CONNECTIVITY_SERVICE);

2 个答案:

答案 0 :(得分:2)

删除

 private Activity context;

在您使用它的任何地方,也删除它。例如改变

 context.getSystemService(...

  getSystemService(...

您的MainActivity已经是一个Context,这就是您所需要的。 您创建了上下文字段,但是为null,并且无论如何由于您需要系统创建的上下文而无法工作。这就是你的活动。

答案 1 :(得分:0)

添加互联网权限...

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

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