簡體   English   中英

我如何在另一個類中調用方法

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

我有2個類:1.公共類UltimateInfoServiceForGear擴展了SAAgent 2.公共類NotificationService擴展了NotificationListenerService

在第二堂課中,我想從第一堂課中調用一個函數:

函數是:內部類public class HelloAccessoryProviderConnection下的public void sendmydata ()擴展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);
                }
            }
        }

謝謝。

在類HelloAccessoryProviderConnection添加默認的空構造HelloAccessoryProviderConnection

有關此問題,請參閱接受的答案。 您的intentservice發生了完全相同的問題, 沒有空的構造函數,但是有一個構造函數

因為您的課程在另一個課程中,所以您可能必須更改修飾符。 通過問題以更好地理解。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM