getSystemService method is used when we want to access one of few Android system-level services. To name only few of managers that we can get: LocationManager – access GPS device information. NotificationManager – manage (create, cancel) notifications.
In an android Application, is there any way to get the context in android in a non-activity class if the activity class name is known? pass the context of ur current activity to the java class constructor... If your non-activity class is a Fragment , see stackoverflow.com/questions/8215308/using-context-in-a-fragment.
You need to pass your context to your fyl class..
One solution is make a constructor like this for your fyl
class:
public class fyl {
Context mContext;
public fyl(Context mContext) {
this.mContext = mContext;
}
public Location getLocation() {
--
locationManager = (LocationManager)mContext.getSystemService(context);
--
}
}
So in your activity class create the object of fyl in onCreate
function like this:
package com.atClass.lmt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.location.Location;
public class lmt extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
fyl lfyl = new fyl(this); //Here the context is passing
Location location = lfyl.getLocation();
String latLongString = lfyl.updateWithNewLocation(location);
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current position is:\n" + latLongString);
}
}
You can go for this :
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
One way I have gotten around this is by create a static class for instances. I used it a lot in AS3 I has worked great for me in android development too.
Config.java
public final class Config {
public static MyApp context = null;
}
MyApp.java
public class MyApp extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Config.context = this;
}
...
}
You can then access the context or by using Config.context
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);
Use this in Activity:
private Context context = this;
........
if(Utils.isInternetAvailable(context){
Utils.showToast(context, "toast");
}
..........
in Utils:
public class Utils {
public static boolean isInternetAvailable(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With