Android 如何在所有活动中重用函数

Android 如何在所有活动中重用函数,android,android-studio,android-fragments,Android,Android Studio,Android Fragments,大家好,我正在开发一个android应用程序,我在活动中创建了函数getGPS()。现在我想在我的应用程序的任何地方,所有的活动中都使用这个功能。我已经尝试创建另一个java文件,但它需要工作。有人能告诉我怎么用吗 package com.example.hp.mirocareltd; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import a

大家好,我正在开发一个android应用程序,我在活动中创建了函数getGPS()。现在我想在我的应用程序的任何地方,所有的活动中都使用这个功能。我已经尝试创建另一个java文件,但它需要工作。有人能告诉我怎么用吗

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

            }
        });

    }
}
我创建了另一个java文件并编写了以下代码

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();
        }
    }
}

答案很简单。创建一个从
AppCompatActivity
扩展的新抽象类(例如,将其命名为:
BaseActivity
)。然后,您添加的每个活动都应该从
BaseActivity
扩展。使您的
getGPS()
功能受到保护,您将能够从所有子活动访问它

abstract class BaseActivity extends AppCompatActivity {
    ...
    protected void getGPS() {
        ...
    }
}

答案很简单。创建一个从
AppCompatActivity
扩展的新抽象类(例如,将其命名为:
BaseActivity
)。然后,您添加的每个活动都应该从
BaseActivity
扩展。使您的
getGPS()
功能受到保护,您将能够从所有子活动访问它

abstract class BaseActivity extends AppCompatActivity {
    ...
    protected void getGPS() {
        ...
    }
}

我建议使用正确的方法,使用依赖项注入(例如Dagger2),并创建一个名为PositionService或LocationService的接口来注入到您的活动中。该服务将包含您的方法getGPS()


通过这种方式,现在您可以轻松地测试getGPS()方法,并将该服务注入应用程序中需要它的任何部分。您甚至可以控制依赖项的生命周期,如果每次都需要相同的实例或新实例。

我建议使用依赖项注入(例如Dagger2)并创建名为PositionService或LocationService的接口,将其注入到您的活动中。该服务将包含您的方法getGPS()


通过这种方式,现在您可以轻松地测试getGPS()方法,并将该服务注入应用程序中需要它的任何部分。您甚至可以控制依赖项的生命周期,如果每次都需要相同的实例或新实例。

要在任何地方重用该函数,请创建一个类utils.java。它应该是公开的和最终的。然后,编写你认为需要在应用程序中随处重用的所有函数。将函数公开为静态

下面是一个示例代码:

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()
{
}

}

您可以通过调用utils.getGps()来使用这些函数。

要在任何地方重用该函数,请创建一个类utils.java。它应该是公开的和最终的。然后,编写你认为需要在应用程序中随处重用的所有函数。将函数公开为静态

下面是一个示例代码:

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()
{
}

}


您可以通过调用utils.getGps()来使用这些功能。

这可能不是最好的方法,但您可以重写应用程序类,将此方法放在那里,并通过以下方式在每个活动中访问:
((MyApplication)getApplication()).getGps()
@GabrielCosta,这会使代码因强制转换而看起来很糟糕。最好将此类代码远离应用程序类。@Jeffrey,尽管它可以工作,但我同意,就可读性而言,这是不好的。有人能告诉我如何调用此函数吗?这可能不是最好的方法,但您可以重写应用程序类,将此方法放在那里,并通过:
((MyApplication)getApplication()).getGPS()
@GabrielCosta由于强制转换,这会使代码看起来很糟糕。最好不要让这种代码出现在应用程序类中。@Jeffrey尽管它可以工作,但我同意,就可读性而言,这是不好的。有人能告诉我如何调用此函数吗?这显然是更好的方法,因为它遵循设计原则上,我认为这个答案对于OP来说太复杂了。在基本活动类中继承这种功能更有意义,因为OP指出它将在整个应用程序中使用。这意味着
getGPS()
方法可以从
onCreate()中的
BaseActivity
调用
,防止大量代码重复。虽然这是真的,为什么不从一开始就教他一些好的实践呢?因为教这么复杂的东西是没有意义的,它只会提出比解决当前问题更多的问题。我认为,要有人完全理解这样的原则需要几年的时间。显然,OP已经退出了e还有一条路要走…@Jeffrey,我确实会给你这个答案。我甚至投票赞成你的答案。:)虽然这显然是更好的方法,因为它遵循设计原则,但我认为这个答案对于OP来说太复杂了。在基本活动类中继承这种功能更有意义,因为OP表示它将在整个应用程序中使用。这意味着可以从
onCreate()
中的
BaseActivity
调用
getGPS()
方法,从而防止大量代码重复。尽管如此,为什么不从一开始就教他一些好的实践呢?因为教这么复杂的东西是没有意义的,它只会提出比解决当前问题更多的问题。我认为,要有人完全理解这样的原则需要很多年。很明显,行动还有很长的路要走…@Jeffrey,我确实会告诉你的。我甚至投票赞成你的答案我尝试了您的代码,只在主页面上出现了一个错误。这个非封闭类=>AlertDialog AlertDialog=new AlertDialog.Builder(主页面.this.create();如果在活动之外的其他地方需要它怎么办?我知道他没有指定,但为什么活动有责任获取GPS定位并显示视图?@dipeshmodi将
主页替换为
主页。此
替换为
,错误将消失。@PmanAce你说得对,不是活动负责处理GPS,但为了简单起见,这似乎是对OP所问问题的一个合适答案。继续使用最佳实践,最好将您的上下文注入到实体中