简体   繁体   中英

How to call MainActivity method in a java class?

I'm trying ways to call my MainActivity method into my doWork in java class in android studio. But I'm not getting it. Is there any way to call this method ?

Class in the MainActivity

public class MainActivity extends AppCompatActivity implements LocationListener {

    protected double latitude, longitude;
    TextView txtLat, txtLng;

    LocationManager locationManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void LocalizarUsuario(){

        txtLat = (TextView) findViewById(R.id.txtLat);
        txtLng = (TextView) findViewById(R.id.txtLng);


        locationManager =(LocationManager)

                getSystemService(Context.LOCATION_SERVICE);

        if(ActivityCompat.checkSelfPermission(MainActivity .this,Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED)

        {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
        }
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
    }
}

Java class with the doWork

public class WorkerClass extends Worker {
    public WorkerClass(
            @NonNull Context context,
            @NonNull WorkerParameters params) {
        super(context, params);
    }

    @Override
    public Result doWork() {

             LocalizarUsuario();


        // Indicate whether the work finished successfully with the Result
        return Result.success();
    }
}

根据您想要做什么,您可以将 WorkerClass 放入 MainActivity(内部类),或者如果您只想从 MainActivity 使用 WorkerClass,您可以传递

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM