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!
Do NOT do this…
DeviceMonitorextendsActivityand you should never create an instance of anActivityusingnew. An AndroidActivityis a special-case class and shouldn’t be treated like a normal Java class.If you want to start an
Activityyou need to do it usingstartActivity...)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 theActivityContextto it in its constructor then use that to access Android services etc. Example…EDIT: To create your helper and pass a
Contextfrom your mainActivitydo this…