从另一个Activity调用Activity的方法

时间:2013-12-18 06:09:15

标签: java android android-intent android-activity

我有两个Activities A和B. B有一个方法searchDevices。我想从A的onCreate方法访问该方法。如何使用Intent执行此操作? 我试过这个:

public void onCreate(Bundle savedInstanceState)
{
    try{


    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");    


    //Function enbling Bluetooth
    enableBluetooth();

    ///Function to initialize components
    init();


    //Calling AvailableDevices class's method searchDevice to get                AvailableDevices
    Intent intent=new Intent(this,AvailableDevices.class);
    int x=10;
    intent.putExtra("A", x);

    }catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(),   Toast.LENGTH_LONG).show();}
}

3 个答案:

答案 0 :(得分:4)

您还可以创建ActivityAActivityB扩展的基本活动,并将searchDevices()方法放入其中。

例如:

public class BaseActivity extends Activity{

public void searchDevices(){

}

}


public class ActivityB extends BaseActivity{
onCreate..
{
  ...
  searchDevices();
}
}


public class ActivityA extends BaseActivity{
onCreate..
{
  ...
  searchDevices();
}
}

答案 1 :(得分:2)

如果ActivityA位于名为class1的类中,请在类1中创建一个方法

public static void method1(){
}

然后在活动2中通过执行此ActivityA.method1()

来调用该方法

答案 2 :(得分:1)

为什么不使用StartActivityForResult

根据我的理解你可以启动AvailableDevices Activity获取结果,Intent拥有额外的数据并调用searchDevice来获取AvailableDevices并将结果返回给Activity。

[编辑]

在A组

//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100

还覆盖onActivityResult()

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == searchDevicesRequestCode) {
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            // Manipulate searchDevicesResult from Intent data
        }
    }
}

在B组中

@override    
onCreate()
{
    //call searchDevices()
    String result = searchDevices(); // save result to send in any form
    // Create intent to deliver some kind of result data
    Intent intentResult = new Intent("RESULT_ACTION");
    intentResult.putExtra("key",result);
    setResult(Activity.RESULT_OK, intentResult);
    finish();
}