簡體   English   中英

錯誤:-服務類沒有零參數構造函數

[英]error:- service class has no zero argument constructor

我是Android新手。 我想在我的活動中使用service在一段時間后獲取JSON數據。 我的服務類是我的記錄類的內部類。 我為服務類制作了一個空的構造函數,並嘗試了不同的方法,但是每次遇到錯誤時,我都會嘗試。 有人可以指導我解決這個問題嗎?

record.class

public class record extends Activity{
.....
private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
......
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.record);
    ......

    Intent intent = new Intent(record.this,
            BackgroundService.class);

    startService(intent);

}


    class gro extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();
      ............
        }
    }

    protected String doInBackground(String... args) {
        java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url, "GET", pr);

        try {
            JSONArray code = json.getJSONArray("code");
            Log.d("list :",code.toString());
            for (int i = 0; i < code.length(); i++) {
                JSONObject c = code.getJSONObject(i);

                asd.add(c.getString("name"));

                // adding each child node to HashMap key => value

                // adding contact to contact list
                JSONArray p = null;
            }
            }catch(JSONException e){

            }
            return null;

    }

    protected void onPostExecute(String file_url) {

        pDialog.dismiss();
        ..........

        Collections.reverse(Arrays.asList(info));
        customList = new CustomList(record.this,info);
        listView = (ListView) findViewById(R.id.listView);
        listView.setAdapter(customList);


    }
}

//-----------------------------------------------------------------------------------------------------------------------
//
//
//-----------------------------------------------------------------------------------------------------------------------
public class BackgroundService extends Service
{
    public BackgroundService(){
        super();
    }

    private static final String TAG = "BackgroundService";
    private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");



    @Override
    public void onCreate() {
        super.onCreate();
        Log.v(TAG, "in onCreate()");

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        super.onStartCommand(intent, flags, startId);
        int counter = intent.getExtras().getInt("counter");



        Log.v(TAG, "in onStartCommand(), counter = " + counter +
                ", startId = " + startId);

        new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
                .start();


        return START_NOT_STICKY;
    }


    class ServiceWorker implements Runnable
    {
        private int counter = -1;

        public ServiceWorker(int counter) {
            this.counter = counter;
        }

        public void run() {

            final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
            // do background processing here...
            try {
                Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);

                while(true)
                {
                    Thread.sleep(5000);
                    Log.e("agdghdgdgdrgrdgrdg","dgdgd");
                    new gro().execute();
                }
            } catch (InterruptedException e) {
                Log.e(TAG2, "... sleep interrupted");
            }
        }
    }

    @Override
    public void onDestroy()
    {

    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.v(TAG, "in onBind()");
        return null;
    }


}



}

的manifest.xml

 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.grover.jsonp">
<uses-permission android:name="android.permission.INTERNET"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".record"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

logcat的

   E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.grover.jsonp, PID: 13046
              java.lang.RuntimeException: Unable to instantiate service com.grover.jsonp.record$BackgroundService: java.lang.InstantiationException: class com.grover.jsonp.record$BackgroundService has no zero argument constructor
                  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2721)
                  at android.app.ActivityThread.access$1800(ActivityThread.java:147)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5237)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)
               Caused by: java.lang.InstantiationException: class com.grover.jsonp.record$BackgroundService has no zero argument constructor
                  at java.lang.Class.newInstance(Class.java:1563)
                  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2718)
                  at android.app.ActivityThread.access$1800(ActivityThread.java:147) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:135) 
                  at android.app.ActivityThread.main(ActivityThread.java:5237) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at java.lang.reflect.Method.invoke(Method.java:372) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) 
               Caused by: java.lang.NoSuchMethodException: <init> []
                  at java.lang.Class.getConstructor(Class.java:531)
                  at java.lang.Class.getDeclaredConstructor(Class.java:510)
                  at java.lang.Class.newInstance(Class.java:1561)
                  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2718) 
                  at android.app.ActivityThread.access$1800(ActivityThread.java:147) 
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1368) 
                  at android.os.Handler.dispatchMessage(Handler.java:102) 
                  at android.os.Looper.loop(Looper.java:135) 
                  at android.app.ActivityThread.main(ActivityThread.java:5237) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at java.lang.reflect.Method.invoke(Method.java:372) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707) 

首先,您嘗試使用Intent啟動有Bounded Service 哪有錯 為此,您需要創建一個Intent Service

由於沒有將服務綁定到MainActivity,您將獲得零參數構造函數異常”,這是不正確的,因為構造函數的問題與使用startService()或bindService()無關。( 謝謝

要創建BoundService,您需要一個iBinder對象來綁定您的服務。 我知道這很奇怪,但這就是Android了解它的方式。 如您所讀,有兩種服務

 1. Intent Service
 2. Bound Service

Bound Service需要像這樣實例化。

使用此代碼編輯代碼,請確保使用我的代碼更新onBind()

public class BackgroundService extends Service
{
    public BackgroundService(){
        super();
    }
    private BackgroundService mBS;

    // This is the object that receives interactions from clients.  See
    // RemoteService for a more complete example.
    private final IBinder mBinder = new LocalBinder();

     /**
     * Class for clients to access.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with
     * IPC.
     */
    public class LocalBinder extends Binder {
        BackgroundService getService() {
            return BackgroundService.this;
        }
    }


    @Override
    public IBinder onBind(Intent intent) {
        Log.v(TAG, "in onBind()");
        return mBinder;
    }

}

在您的MainActivity中,您需要一個接口 -> ServiceConnection

在您的MainActivity.java添加以下內容

BackgroundService mBackgroundService;
boolean mServiceBound = false;

private ServiceConnection mServiceConnection = new ServiceConnection() {


@Override
public void onServiceDisconnected(ComponentName name) {
    mServiceBound = false;
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    LocalBinder  myBinder = (LocalBinder ) service;
    mBackgroundService = myBinder.getService();
    mServiceBound = true;
}
};
     //Start the service when the activity starts
     @Override
protected void onStart() {
    super.onStart();
    Intent intent = new Intent(this, BackgroundService.class);
    startService(intent);
    bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    if (mServiceBound) {
        unbindService(mServiceConnection);
        mServiceBound = false;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM