java - 无法实例化服务 - Java.NullPointerException

标签 java android service nullpointerexception

所以基本上我对 Android 开发相当陌生,我想创建一个在后台运行的应用程序。我决定使用服务,因为只要应用程序本身中的切换按钮保持打开状态,我就需要应用程序不断获取有关 Wifi 的信息。如果切换按钮关闭,该服务将被关闭。

但是,我在让服务运行时遇到了很多麻烦,出现的错误就是标题中指定的错误。

谁能帮我解决这个问题吗?

这是我的 list 。您在这里看到其他 Activity 的原因是因为我正在尝试将以前不在后台运行的程序迁移到在后台运行的服务中。所以现在我使用的唯一 Activity 是具有切换按钮和服务类的主 Activity 。

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

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-     permission>
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
    <uses-feature android:name="android.hardware.wifi" />
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <!--
            Because android:exported is set to "false",
            the service is only available to this app.
        -->
        <service
        android:name=".WifiPullService"
        android:label="Wifi Pull Service" >
    </service>


        <activity
            android:name="com.example.wifianalysis.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>

        <activity
            android:name="com.example.wifianalysis.Checkwifi"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.CHECK" />

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

        <activity
            android:name="com.example.wifianalysis.wifi_on"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.WIFION" />

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


        <activity
            android:name="com.example.wifianalysis.wifi_off"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.WIFIOFF" />

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


        <receiver android:name=".WiFiScanReceiver">
          <intent-filter>
            <action android:name="com.rdc" />
          </intent-filter>
        </receiver>

    </application>

</manifest>

我的服务类代码:

这里曾经编写过处理信息的代码,但我决定首先尝试该服务的基本功能,以找出问题所在。

package com.example.wifianalysis;

    import java.util.List;
    import java.util.concurrent.ScheduledExecutorService;

    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.net.wifi.ScanResult;
    import android.net.wifi.WifiManager;
    import android.os.Binder;
    import android.os.Handler;
    import android.os.IBinder;
    import android.widget.Toast;


    public class WifiPullService extends Service {

    ScheduledExecutorService scheduleTaskExecutor;
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    int count =0;
    private Runnable mScanInfo;
    private final Handler mHandler = new Handler();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    public class LocalBinder extends Binder {
        WifiPullService getService() {
            return WifiPullService.this;
        }
    }







    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub

        return super.onStartCommand(intent, flags, startId);





    }



    @Override
    public void onCreate() {

        super.onCreate();
        Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
        // TODO Auto-generated method stub




        //super.onCreate();
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
        super.onDestroy();
    }

    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
    }


}

我的主要 Activity :

 package com.example.wifianalysis;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.net.ConnectivityManager;
    import android.net.NetworkInfo;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.ToggleButton;
    //import android.net.wifi.WifiManager;

    public class MainActivity extends Activity {

        public void onToggleClicked(View view) { //when backbutton is pressed go back to main
            // Do something in response to button
            boolean on = ((ToggleButton) view).isChecked();

            try{

                if (on) {
                    //Intent backIntent = new Intent("android.intent.action.CHECK");
                    Intent i = new Intent(this, WifiPullService.class);
                    startService(i); //if checked, start service
                }
                else{
                    stopService(new Intent(this, WifiPullService.class)); //if unchecked, stop service
                }
            }
            catch (Exception e){
                System.err.println("Could not start/stop service: " + e.getMessage());
            }
        }


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



        }


        @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;
        }

LogCat 错误:

12-06 10:38:39.440: W/dalvikvm(7458): threadid=1: thread exiting with uncaught exception (group=0x416ed450)

12-06 10:38:39.460: E/AndroidRuntime(7458): FATAL EXCEPTION: main

12-06 10:38:39.460: E/AndroidRuntime(7458): java.lang.RuntimeException: Unable to instantiate service com.example.wifianalysis.WifiPullService: java.lang.NullPointerException
12-06 10:38:39.460: E/AndroidRuntime(7458): java.lang.RuntimeException: Unable to instantiate service com.example.wifianalysis.WifiPullService: java.lang.NullPointerException
12-06 10:38:39.460: E/AndroidRuntime(7458):     at android.app.ActivityThread.handleCreateService(ActivityThread.java:2368)

最佳答案

这里

WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

您试图在创建之前获取服务上下文,因此将wifi实例的初始化移至WifiPullService<的onStartCommandonCreate方法内 服务:

@Override
public void onCreate() {
    super.onCreate();
    // initialize wifi instace here
    wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    //....your code here...    
}

关于java - 无法实例化服务 - Java.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20428810/

相关文章:

java - 扩展 JMeter 还是编写复杂的场景?

android - minifyEnabled true 生成许多警告

java - 如果正在运行,Android 服务会与 Activity 对话吗?

javascript - angularjs 和 $http 请求

java - 如何动态更改 JFrame 内的 JPanel?

java - 如何在 Android 中创建 JSON?

android - 此消息无法回收,因为它仍在使用中

service - 为什么我们需要一个接口(interface)来定义 aem 中的每个服务?

java - 使用Pool来回收和重用 Sprite

android - 不要在 android 9 pie 上使用代理