我是Android开发的初学者。 可以任意1请指导我如何调用其他包下的类的方法。
与包1中的类A类似,调用包2的类B中的方法,该方法返回一个数组或对象。
我必须为此创建一个Intent吗?实际上,我必须从不同包中的不同类中收集1个类中的所有信息。
提前致谢。
package com.xyz.Master;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.telephony.CellLocation;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
public class PhoneInfo extends Activity {
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation location = (GsmCellLocation) tm.getCellLocation();
public int cellID, lac,mcc,mnc;
public String imei,manufacturer,model,product;
String[] phoneInfo;
int[] phoneLocationInfo;
public String[] getHandsetInfo()
{
manufacturer = Build.MANUFACTURER;
model = Build.MODEL;
product = Build.PRODUCT;
imei=tm.getDeviceId();
String softwareVersion = tm.getDeviceSoftwareVersion();
phoneInfo = new String[5];
phoneInfo[0]=imei;
phoneInfo[1]=product;
phoneInfo[2]=model;
phoneInfo[3]=manufacturer;
phoneInfo[4]=softwareVersion;
return phoneInfo;
}
public int[] getHandsetLocationInfo()
{
phoneLocationInfo= new int[4];
String networkOperator = tm.getNetworkOperator();
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
}
CellLocation.requestLocationUpdate();
cellID = location.getCid();
lac = location.getLac();
phoneLocationInfo[0]=cellID;
phoneLocationInfo[1]=lac;
phoneLocationInfo[2]=mcc;
phoneLocationInfo[3]=mnc;
return phoneLocationInfo;
}
}
我想从其他类调用上面的方法并获取这些数组。 怎么做,上面的代码是否有任何错误?
答案 0 :(得分:19)
假设我们正在谈论Java package
,那么我们有几个规则来调用其他包中的类的方法。为了简单起见,这有效:
package com.example.one;
public class ArrayProvider {
public String[] getArray() {
return new String{"I'm ","inside ", "an ", "array "};
}
public static Object getObject() {
return new String{"I'm ","inside ", "an ", "array "};
}
}
现在您的代码可以从其他包中访问类ArrayProvider
的方法:
package my.namespace.app;
import com.example.one.ArrayProvider; // import the other class
public class MyClass {
public static void main(String[] args) {
// to access the static method
Object result1 = ArrayProvider.getObject();
// to access "the other" method
ArrayProvider provider = new ArrayProvider();
String[] result2 = provider.getArray();
}
}
进一步阅读
答案 1 :(得分:6)
只需导入其他包并实例化B类并调用该函数。
package Package1;
import Package2;
Class A {
void callClassBFunction(){
B b = new B(); //In Package 1 we are instantiating B, however the reference is missing, it should be B b = new B();
b.callFunction();
}
package Package2;
public class B { //class B should be public
Object callFunction(){
//do something and return object
}
}