问题
Error Unable to start activity ComponentInfo: java.lang.IllegalStateException: System services not available to Activities before onCreate()
I´m experimenting with seperating the code and the use of a helper class. (Created different Java files) What I did is created an Activity Java file that is registred in the Manifest and I didn´t register this following class (Java file):
import android.app.Activity;
import android.location.LocationManager;
import android.net.ConnectivityManager;
....
public class DeviceMonitor extends Activity {
boolean laag=false;
int level=-1;
double batterylevel=-1;
public boolean GPSEnabled() {
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) { // NO GPS ENABLED
//ErrorMessage.append(R.string.enablegps);
//ErrorMessage.append("\n");
Log.d("StartPrepare","GPS DISABLED");
return false;
} else {
Log.d("StartPrepare","GPS ENABLED");
return true;
}
}
I removed the OnCreate() method, is this correct? Should I have registred in the Manifest, if yes, how?
I received the following error while calling from the registred Activity like this:
DeviceMonitor MyDevice = new DeviceMonitor();
if (MyDevice.GPSEnabled()){gpsenabled=true;}else{gpsenabled=false;fout=true;}
Error:
E/AndroidRuntime(1912): java.lang.RuntimeException: Unable to start activity ComponentInfo{package}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
Anybody that can give me some light on the helper classes (I´m kind of new in Java/Android) and has any clue what the error can cause? I tried to add the OnCreate() method, but it didn´t help.
Thanks a lot!
回答1:
Do NOT do this...
DeviceMonitor MyDevice = new DeviceMonitor();
DeviceMonitor
extends Activity
and you should never create an instance of an Activity
using new
. An Android Activity
is a special-case class and shouldn't be treated like a normal Java class.
If you want to start an Activity
you need to do it using startActivity...)
or one of the other 'start' methods.
If you want a 'helper' class just create a standard Java class which doesn't extend anything. When you create an instance of it from your main Activity
, pass the Activity
Context
to it in its constructor then use that to access Android services etc. Example...
public class DeviceMonitor {
Context mContext = null;
public DeviceMonitor (Context context) {
mContext = context;
}
}
EDIT: To create your helper and pass a Context
from your main Activity
do this...
// An Activity IS a Context so pass 'this'
DeviceMonitor MyDevice = new DeviceMonitor(this);
回答2:
You need to declare your
boolean GPSEnabled
after onCreate() method is callded in your class or service.
来源:https://stackoverflow.com/questions/8661729/helper-class-error-unable-to-start-activity-componentinfo