如何从其他活动android调用函数

时间:2018-09-08 10:05:37

标签: java android android-studio android-activity

在我的Android应用中,我有两个活动:

1)MapsActivity
2)OtherActivity

MapsActivity 具有导航抽屉,通过该导航抽屉打开了 OtherActivity 。现在,我想从 MapsActivity 调用一个方法(例如 updatemap())。

在Google上搜索了很多之后,我在stackoverflow上发现了这个问题 How to call method in main activity from other activity?,但这不能解决我的问题。

更新:

这是OtherActivity的代码:

public class OtherActivity extends AppCompatActivity {
   @Override
   protected void attachBaseContext(Context newBase) {.....}

   @Override
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState); 
     .... }

   @Override
   protected void onStart() {
     super.onStart();  
     removeConnection(userID)
     .... }

   private void removeConnection(String currentUserId) { 
     ... 
     // Here I want to call a function from MapsActivity i.e. disaplayLocation()
   }

   public static class ConnectedViewHolder extends 
   RecyclerView.ViewHolder{ ... }
}

MapsActivity的代码为:

  public class MapsActivity extends AppCompatActivity implements 
  OnMapReadyCallback,
  GoogleApiClient.ConnectionCallbacks,
  GoogleApiClient.OnConnectionFailedListener,
  LocationListener {

      @Override
      protected void attachBaseContext(Context newBase) { ... }

      @Override
      protected void onCreate(Bundle savedInstanceState) { ... }

      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull 
       String[] permissions, @NonNull int[] grantResults) { ... }

      private void setUpLocation() { ... }

      public void displayLocation() { ... }  // This is the function i want to call

      private void createLocationRequest() { ... } 

      @Override
      protected void onActivityResult(int requestCode, int resultCode, Intent data) { ... } 

      protected synchronized void buildGoogleApiClient() { ... } 

      private boolean checkPlayServices() { ... }

      private void requestRuntimePermission() { ... } 

      private void startLocationUpdates()  { ... }

      @Override
      public void onMapReady(GoogleMap googleMap) { ... }

      @Override
      public void onConnected(@Nullable Bundle bundle) { ... }

      @Override
      public void onConnectionSuspended(int i) { ... }

      @Override
      public void onConnectionFailed(@NonNull ConnectionResult 
       connectionResult) { ... }

      @Override
      public void onLocationChanged(Location location) { ... }

      @Override
      public boolean onCreateOptionsMenu(Menu menu) { ... }

      @Override
      public boolean onOptionsItemSelected(MenuItem item) { ... }

      private void makeConnectionToGetLocation() { ... }

      private void updateConnectedLatLng() { ... }

  }

我仅粘贴代码的结构,因为它是1000行代码,此处粘贴没有用,并且阅读起来更加复杂。

我试图在displayLocation方法之前添加 static 关键字,但是它在函数内的变量中产生错误,并且不可能将每个变量都设置为global。

3 个答案:

答案 0 :(得分:1)

如果MapsActivity期望从OtherActivity获得结果,那么最好使用Getting Result From an Activity。只需通过OtherActivity(而不是startActivityForResult())来调用startActivity()

static final int MAP_REQUEST = 1;  // your request code
...
private void callOtherActivity() {
    Intent intent = new Intent(this, OtherActivity.class)
    startActivityForResult(intent, MAP_REQUEST);
}

然后在您的MapsActivity中,执行以下操作:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == MAP_REQUEST) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            updateMap();
        }
    }
}

答案 1 :(得分:0)

在一个Activity中创建静态函数,例如

public static double getVariance(double[] data)
{
    double mean = getMean(data);
    double temp = 0;
    for(double a :data)
        temp += (mean-a)*(mean-a);
    return temp/data.length;
}

然后在另一个活动中将其称为:

double res = Activity1.getVariance(<your data>);

希望有帮助。

答案 2 :(得分:0)

请注意,如果其他活动已关闭,则可能会得到NullObjectRefernce。

要执行此操作,可以使用$('#tblPartySalesReport').DataTable.ajax.reload(null, false)({ bPaginate: false, dom: 'Bfrtip', buttons: [ { text: 'Party Report', action: function ( e, dt, node, config ) { window.location.href= "@Url.Action("ServicesDetailedReportPartyWise", "DetailedServicesReport")"; } }, { text: 'Expenses Report', action: function ( e, dt, node, config ) { window.location.href= "@Url.Action("ExpensesReport", "Expenses")"; } }, 'copyHtml5', 'excelHtml5', 'csvHtml5', { extend: 'pdfHtml5', footer: true, title: 'Closing Report (' + $('#FromDate').val() + ' - ' + $('#ToDate').val() + ')', customize: function (doc) { doc.styles.title = { color: 'gray', fontSize: '15', alignment: 'center' } doc.content[1].table.widths = Array(doc.content[1].table.body[0].length + 1).join('*').split(''); doc.styles.tableHeader.fontSize = 10; doc.styles.tableHeader.alignment = 'left'; doc.styles.tableHeader.color = 'white' } }, { extend: 'print', footer: true //title: 'Sales Report' } ] }); } 方法。因此,您可以从应用程序中的任何位置调用它。

在活动中添加它。

public static

要在第二个活动中调用它,请将其添加。

public static void YOUR_NAME(){}

另一种解决方案,您可以使用 EventBus

https://github.com/greenrobot/EventBus