添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Hello Everyone I'm developing an android app in which I've created function getGPS() in my Activity. Now I wanna use this function everywhere in my app, in all the activities. I've tried by creating another java file but it want works. Can anyone tell me how can I use it?

package com.example.hp.mirocareltd;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.location.*;
public class main_page extends AppCompatActivity {
    LocationManager service;
    Intent intent;
    boolean enabled;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);
        //super.getGPS(); // not working
        // new BaseMethods().getGSP(); // not working 
        Button buttonLogin = (Button)findViewById(R.id.btn_login);
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Do something in response to button click

I've created another java file and written following code

package com.example.hp.mirocareltd;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
abstract class BaseMethods extends AppCompatActivity {
    public void getGPS(){
        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabled = service
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        // check if enabled and if not send user to the GSP settings
        // Better solution would be to display a dialog and suggesting to
        // go to the settings
        if (!enabled) {
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("GPS Location");
            alertDialog.setMessage("Turn ON your GPS location to Access!");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //finish();
                            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
            alertDialog.show();
                It might not be the best way but you can override the Application class, put this method there and access in every Activity via: ((MyApplication) getApplication()).getGPS()
– Gabriel Costa
                Oct 16, 2017 at 14:15
                @GabrielCosta That would make the code look nasty due to casting. And it's best to keep this kind of code away from the Application class.
– Jeffrey
                Oct 16, 2017 at 14:16

The answer is quite simple. Create a new abstract class that extends from AppCompatActivity (for example, name it: BaseActivity). Then, every Activity you add should extend from the BaseActivity. Make your getGPS() function protected and you'll be able to access it from all sub-Activities.

abstract class BaseActivity extends AppCompatActivity {
    protected void getGPS() {
                I've tried your code only one error left main_page.this not enclosing class => AlertDialog alertDialog = new AlertDialog.Builder(main_page.this).create();
– DIPESH
                Oct 16, 2017 at 14:21
                What if it is needed somewhere else than in an activity? I know he didn't specify it but why would an activity have the responsibility in getting a GPS positioning and displaying a view?
– PmanAce
                Oct 16, 2017 at 14:22
                @PmanAce You're right about it not being the activity's responsibility to handle GPS, but for the sake of simplicity, this does seem like a suitable answer for what the OP is asking.
– Jeffrey
                Oct 16, 2017 at 14:23
                Continuing using best practices, it's better to inject your context to the entities that need it than relying on an Activity or Service object, talk about overkill. :)
– PmanAce
                Oct 16, 2017 at 14:27

I suggest doing it the proper way, using dependency injection (something like Dagger2 for example) and create an interface named PositioningService or LocationService to inject into your activity. That service would contain your method getGPS().

This way now you can easily test your getGPS() method and inject that service in any part of your app that needs it. You can even control the lifecycle of your dependency, if it's the same instance every time it is needed or a new instance.

While this is clearly the better way to go, because it follows design principles, I think this answer is too complicated for the OP. Inheriting this kind of functionality in a base activity class makes more sense, because the OP indicated it will be used throughout the entire app. Meaning the getGPS() method can be called from the BaseActivity in onCreate(), preventing a lot of code duplication. – Jeffrey Oct 16, 2017 at 14:21 Because there's no point in teaching something so complicated it will only raise so many more questions than solve the current one. I think it takes years before someone fully understands principles like this. Clearly, the OP has quite a way to go... – Jeffrey Oct 16, 2017 at 14:26

To reuse the function everywhere, create a class utils.java. It should be declared public and final. Then, write all the functions you think you need to reuse everywhere in your app. Make the functions public static.

Here is an example code:

public final class utils.java
private utils()
//Here is your function
public static void getGPS() {
//You can add how many every functions you want
//And use them across your app
public void getSum()

You can use these funtions by calling utils.getGps().

Well, you can't access services in static methods because you need the context. Even if that was allowed, using it may cause memory leaks. – Gabriel Costa Oct 16, 2017 at 14:33 While this may seem like something easy, you will have a tough time mocking static methods when you unit test. It is better to mock the behaviour of an instance of a class. – PmanAce Oct 16, 2017 at 14:34

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.