简体   繁体   English

我如何在另一个类中调用方法

[英]How can I call a method in another class

I have 2 classes: 1. public class UltimateInfoServiceForGear extends SAAgent 2. public class NotificationService extends NotificationListenerService 我有2个类:1.公共类UltimateInfoServiceForGear扩展了SAAgent 2.公共类NotificationService扩展了NotificationListenerService

In the second class, I would like to call a function from the first class: 在第二堂课中,我想从第一堂课中调用一个函数:

The function is: public void sendmydata () under the inner class public class HelloAccessoryProviderConnection extends SASocket 函数是:内部类public class HelloAccessoryProviderConnection下的public void sendmydata ()扩展SASocket

So, in my second class I create following funtion: 因此,在第二堂课中,我创建了以下函数:

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

Then, I call it from my main function with: 然后,从我的主要函数中调用它:

    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();
    }

But, here , newInstance does not work. 但是,在这里,newInstance不起作用。

I get the following error: 我收到以下错误:

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

What is wrong with my code ? 我的代码有什么问题? How can I call the fuction in my other class ? 我如何在其他课堂上称呼功能?

here is the class : 这是课程:

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);
                }
            }
        }

Thanks. 谢谢。

Add a default empty constructor in class HelloAccessoryProviderConnection 在类HelloAccessoryProviderConnection添加默认的空构造HelloAccessoryProviderConnection

See the accepted answer for this question. 有关此问题,请参阅接受的答案。 Exactly same problem is happening with you intentservice no empty constructor, but there is a constructor 您的intentservice发生了完全相同的问题, 没有空的构造函数,但是有一个构造函数

Because your class is inside another class you might have to change the modifier. 因为您的课程在另一个课程中,所以您可能必须更改修饰符。 Go through the question for better understanding. 通过问题以更好地理解。

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). 

You have not created static so you have to create instance of class: ie 您尚未创建静态,因此必须创建类的实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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