【问题标题】:How can I call a method in another class如何调用另一个类中的方法
【发布时间】:2016-01-19 13:25:47
【问题描述】:

我有 2 节课: 1. 公共类 UltimateInfoServiceForGear 扩展 SAAgent 2. 公共类 NotificationService 扩展 NotificationListenerService

在第二类中,我想从第一类中调用一个函数:

功能是: 公共无效 sendmydata() 在内部类下 公共类 HelloAccessoryProviderConnection 扩展 SASocket

所以,在我的第二堂课中,我创建了以下函数:

private void senddata(UltimateInfoServiceForGear.HelloAccessoryProviderConnection param) {
    param.sendmydata();
}

然后,我从我的主函数调用它:

    try {
        senddata(UltimateInfoServiceForGear.HelloAccessoryProviderConnection.class.newInstance());
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

但是,在这里,newInstance 不起作用。

我收到以下错误:

10-27 22:34:01.563: D/dalvikvm(4973): newInstance failed: no <init>()

10-27 22:34:01.563: W/System.err(4973): java.lang.InstantiationException: can't instantiate class com.gearwatch.ultimateinfoserviceforgear.service.UltimateInfoServiceForGear$HelloAccessoryProviderConnection; no empty constructor

10-27 22:34:01.563: W/System.err(4973):     at java.lang.Class.newInstanceImpl(Native Method)

10-27 22:34:01.563: W/System.err(4973):     at java.lang.Class.newInstance(Class.java:1208)

10-27 22:34:01.563: W/System.err(4973):     at com.gearwatch.ultimateinfoserviceforgear.service.NotificationService.onNotificationRemoved(NotificationService.java:85)

10-27 22:34:01.563: W/System.err(4973):     at android.service.notification.NotificationListenerService$INotificationListenerWrapper.onNotificationRemoved(NotificationListenerService.java:176)

10-27 22:34:01.563: W/System.err(4973):     at android.service.notification.INotificationListener$Stub.onTransact(INotificationListener.java:69)

10-27 22:34:01.563: W/System.err(4973):     at android.os.Binder.execTransact(Binder.java:404)

10-27 22:34:01.573: W/System.err(4973):     at dalvik.system.NativeStart.run(Native Method)

10-27 22:34:01.583: D/SAAgent(4973): intent Actionandroid.accessory.service.action.ACCESSORY_SERVICE_CONNECTION_IND : Thread Name UltmateInfoServiceForGear

我的代码有什么问题?如何在我的其他班级中调用该函数?

这是课程:

public class HelloAccessoryProviderConnection extends SASocket {
            private int mConnectionId;

            public HelloAccessoryProviderConnection() {
                super(HelloAccessoryProviderConnection.class.getName());
            }

            @Override
            public void onError(int channelId, String errorString, int error) {

            }           

            @Override
            public void onReceive(int channelId, byte[] data) {
                String receivedStr = new String(data);
                String messagex = new String();
                String weatherforecast="";
                String m="0";
                String w="0";

                if (receivedStr.equals("battery")){
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    }
                    messagex = "battery|:" + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                } else if (receivedStr.equals("won")){
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
                    wifiManager.setWifiEnabled(true);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    } else {
                            try {
                                Thread.sleep(2000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            wifi = conMan.getNetworkInfo(1).getState();
                            if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                            {
                                w="1";
                            } else {
                                    try {
                                        Thread.sleep(2000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    wifi = conMan.getNetworkInfo(1).getState();
                                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                                    {
                                        w="1";
                                    } 
                                    else { w="2";}      
                            }
                    }
                    messagex = "battery|:" + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                } else if (receivedStr.equals("woff")){
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); 
                    wifiManager.setWifiEnabled(false);
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    }
                    messagex = "battery|:" + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                } else if (receivedStr.equals("don")){
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    try {
                         Class conmanClass;
                         conmanClass = Class.forName(conMan.getClass().getName());
                         final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
                         iConnectivityManagerField.setAccessible(true);
                         final Object iConnectivityManager = iConnectivityManagerField.get(conMan);
                         final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
                         final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
                         setMobileDataEnabledMethod.setAccessible(true);
                         setMobileDataEnabledMethod.invoke(iConnectivityManager, true);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    }
                    messagex = "battery|:" + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                } else if (receivedStr.equals("doff")){
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    try {
                         Class conmanClass;
                         conmanClass = Class.forName(conMan.getClass().getName());
                         final Field iConnectivityManagerField = conmanClass.getDeclaredField("mService");
                         iConnectivityManagerField.setAccessible(true);
                         final Object iConnectivityManager = iConnectivityManagerField.get(conMan);
                         final Class iConnectivityManagerClass = Class.forName(iConnectivityManager.getClass().getName());
                         final Method setMobileDataEnabledMethod = iConnectivityManagerClass.getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
                         setMobileDataEnabledMethod.setAccessible(true);
                         setMobileDataEnabledMethod.invoke(iConnectivityManager, false);
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    } catch (NoSuchFieldException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    }
                    messagex = "battery|:" + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                } else if (receivedStr.equals("calendar")) {
                    String cevent = readCalendarEvent(getBaseContext());
                    messagex = "calendar|:"+ cevent;
                } else if (receivedStr.equals("location")) {
                    if (loc!=null) {
                        Geocoder gcd = new Geocoder(getBaseContext(),Locale.getDefault());               
                        List<Address>  addresses;    
                        try {    
                            addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 5);    
                            if (addresses != null && addresses.size() > 0)    
                                //System.out.println(addresses.get(0).getLocality()); 
                                cityName=addresses.get(0).getLocality();
                                if (cityName==null) cityName="";
                                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                                ltime = format.format(loc.getTime());
                                lp = loc.getProvider();
                                    try {weatherforecast=getWeatherT(getWeatherTData(loc.getLatitude(), loc.getLongitude()));
                                    } catch (JSONException e) {             
                                        e.printStackTrace();
                                    }
                                    /*
                                    try {weathernow=getWeather(getWeatherData(loc.getLatitude(), loc.getLongitude()));
                                    } catch (JSONException e) {             
                                        e.printStackTrace();
                                    }
                                    */
                                messagex =  "location|:" + cityName + "|:" + ltime + "|:" + lp + "|:" + weatherforecast; //+ "|:" + weathernow;
                            } catch (IOException e) {              
                                e.printStackTrace();    
                                messagex =  "location|:" + cityName + "|: ";
                        } 
                    } else { messagex =  "location|:n/a";}
                } else if (receivedStr.equals("batloc")) {
                    ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    State mobile = conMan.getNetworkInfo(0).getState();
                    State wifi = conMan.getNetworkInfo(1).getState();
                    if (mobile == android.net.NetworkInfo.State.CONNECTED || mobile == android.net.NetworkInfo.State.CONNECTING)
                    {
                        m="1";
                    }
                    if (wifi == android.net.NetworkInfo.State.CONNECTED || wifi == android.net.NetworkInfo.State.CONNECTING)
                    {
                        w="1";
                    }
                    if (loc!=null) {
                        Geocoder gcd = new Geocoder(getBaseContext(),Locale.getDefault());               
                        List<Address>  addresses;    
                        try {    
                            addresses = gcd.getFromLocation(loc.getLatitude(), loc.getLongitude(), 5);    
                            if (addresses != null && addresses.size() > 0)    
                                //System.out.println(addresses.get(0).getLocality()); 
                                cityName=addresses.get(0).getLocality();
                                if (cityName==null) cityName="";
                                SimpleDateFormat format = new SimpleDateFormat("HH:mm");
                                ltime = format.format(loc.getTime());
                                lp = loc.getProvider();
                                    try {weatherforecast=getWeatherT(getWeatherTData(loc.getLatitude(), loc.getLongitude()));
                                    } catch (JSONException e) {             
                                        e.printStackTrace();
                                    }
                                    /*
                                    try {weathernow=getWeather(getWeatherData(loc.getLatitude(), loc.getLongitude()));
                                    } catch (JSONException e) {             
                                        e.printStackTrace();
                                    }
                                    */
                                messagex =  "batloc|:"  + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + cityName + "|:" + ltime + "|:" + lp + "|:" + weatherforecast + "|:" + String.valueOf(nc); //+ "|:" + weathernow;
                            } catch (IOException e) {              
                                e.printStackTrace();    
                                messagex =  "battery|:"  + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);
                        } 
                    } else { messagex =  "battery|:"  + w + "|:" + m + "|:" + String.valueOf(level) + "|:" + String.valueOf(nc);}

                } else {
                    messagex = "error|:no input";
                }
                final String message = messagex;
                Log.d(TAG, receivedStr + " " + message);
                final HelloAccessoryProviderConnection uHandler = mConnectionsMap.get(Integer
                        .parseInt(String.valueOf(mConnectionId)));
                if(uHandler == null){
                    return;
                }
                new Thread(new Runnable() {
                    public void run() {
                        try {
                            uHandler.send(HELLOACCESSORY_CHANNEL_ID, message.getBytes());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }

            @Override
            protected void onServiceConnectionLost(int errorCode) {

                if (mConnectionsMap != null) {
                    mConnectionsMap.remove(mConnectionId);
                }
            }
        }

谢谢。

【问题讨论】:

标签: java android


【解决方案1】:

在类HelloAccessoryProviderConnection中添加一个默认的空构造函数

查看此问题的已接受答案。完全相同的问题发生在你身上intentservice no empty constructor, but there is a constructor

因为您的类在另一个类中,您可能需要更改修饰符。仔细阅读问题以更好地理解。

【讨论】:

  • @AnthonyBonarrigo - 仅当您自己没有定义任何构造函数时。
  • 是的......隐式不足以实例化。
  • @Rohit5k2 ,我在帖子中添加了类的代码。有什么想法吗?
  • 那么,您认为如果我将内部类更改为“静态”,那么它会允许我调用它吗?
  • 我觉得是这样,但您可能需要稍微更改代码以管理更改。试一试。
【解决方案2】:
you can call your method...

public static void methodname(Params){
} 

i.e. If it is static method then You can directly call using:
UltimateInfoServiceForGear.sendData(paramValue). 

你还没有创建静态,所以你必须创建类的实例: 即

UltimateInfoServiceForGear ultimateInfoServiceForGear=new UltimateInfoServiceForGear();     
ultimateInfoServiceForGear.sendData(paramValue);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    相关资源
    最近更新 更多