错误:
错误: - 服务类没有零参数构造函数(error:- service class has no zero argument constructor)我是android新手。 我想在我的活动中使用服务来获取时间间隔后的JSON数据。 我的服务类是我的记录类的内部类。 我在我的服务类中创建了一个空的构造函数,并尝试了不同的方法,但每次出现错误时都会尝试。 任何人都可以请指导我解决这个问题?
record.class
public class record extends Activity{.....private static String url =".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=""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)I am new to android. I want to use service inside my activity for fetching the JSON data after interval of time. My service class is a inner class of my record class. I made an empty constructor of my service class and tried different approaches but every time I get into an error. Can anyone please guide me on this problem?
record.class
public class record extends Activity{.....private static String url =".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=""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 ServiceBound 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() {@Overridepublic void onServiceDisconnected(ComponentName name) { mServiceBound = false;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) { LocalBinder myBinder = (LocalBinder ) service; mBackgroundService = myBinder.getService(); mServiceBound = true;}}; //Start the service when the activity starts @Overrideprotected void onStart() { super.onStart(); Intent intent = new Intent(this, BackgroundService.class); startService(intent); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);}@Overrideprotected void onStop() { super.onStop(); if (mServiceBound) { unbindService(mServiceConnection); mServiceBound = false; }}First of all, you are trying to launch a Bounded Service using an Intent. Which is wrong. In order to do that you need to create an Intent Service
You are getting a zero argument constructor exception because of you didn't bind your service to your MainActivity" is incorrect, as the problem with the constructor has nothing to with whether startService() or bindService() is used. (Thanks)
To create a BoundService, you need an iBinder object to bind your service. I know it's quite weird but this is how Android get's to know it. As you would have read, there are two kinds of services
1. Intent Service 2. Bound ServiceThe Bound Service needs to be instantiated like this.
edit your code with this, make sure you update your onBind() with mine.
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; }}in your MainActivity you need an interface --> ServiceConnection
Add the following in your MainActivity.java
BackgroundService mBackgroundService;boolean mServiceBound = false;private ServiceConnection mServiceConnection = new ServiceConnection() {@Overridepublic void onServiceDisconnected(ComponentName name) { mServiceBound = false;}@Overridepublic void onServiceConnected(ComponentName name, IBinder service) { LocalBinder myBinder = (LocalBinder ) service; mBackgroundService = myBinder.getService(); mServiceBound = true;}}; //Start the service when the activity starts @Overrideprotected void onStart() { super.onStart(); Intent intent = new Intent(this, BackgroundService.class); startService(intent); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);}@Overrideprotected void onStop() { super.onStop(); if (mServiceBound) { unbindService(mServiceConnection); mServiceBound = false; }}