0

我需要与我的服务类共享某些字符串,但是当我尝试这样做时,在尝试使用以下方法实现字符串数组时出现两个错误,指出“无法解析 myWifiInfo”(如下面的源代码所示 - 和下方链接):

在android应用程序中的两个类之间传递字符串数组

有什么建议么?(我一直在非常努力地将这些数据传递给我正在运行的服务器 - 我觉得我快到了 - 我只是无法弄清楚为什么服务类无法从 Main.java 中找到字符串)

主.java:

 Intent intent = new Intent(Main.this, Service_class.class);
        String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
        intent.putExtra("strings", myStrings);
        startActivity(intent); 

服务类.java:

 Intent intent = getIntent();
        String[] myStrings = intent.getStringArrayExtra("strings");

Main.java 完整源代码:

import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;

public class Main extends Activity {    

TextView textSsid, textSpeed, textRssi;

public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // Start service using AlarmManager

    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.SECOND, 10);

    Intent intent = new Intent(Main.this, Service_class.class);
    String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
    intent.putExtra("strings", myStrings);
    startActivity(intent);

    PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
            0);
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            12 * 1000, pintent);

    // click listener for the button to start service
    Button btnStart = (Button) findViewById(R.id.button1);
    btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            startService(new Intent(getBaseContext(), Service_class.class));

        }
    });

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            stopService(new Intent(getBaseContext(), Service_class.class));
        }
    });


        textSsid = (TextView) findViewById(R.id.Ssid);
        textSpeed = (TextView) findViewById(R.id.Speed);
        textRssi = (TextView) findViewById(R.id.Rssi);
        Long.toString(mStartTX);
        Long.toString(mStartRX);
        Long.toString(txBytes);

        ParseAnalytics.trackAppOpened(getIntent());




         mStartRX = TrafficStats.getTotalRxBytes();
            mStartTX = TrafficStats.getTotalTxBytes();
            if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setTitle("Uh Oh!");
                alert.setMessage("Your device does not support traffic stat monitoring.");
                alert.show();
            } else {
                mHandler.postDelayed(mRunnable, 1000);
            }}



        private final Runnable mRunnable = new Runnable() {
            public void run() {

                TextView RX = (TextView)findViewById(R.id.RX);
                TextView TX = (TextView)findViewById(R.id.TX);
                long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
                RX.setText(Long.toString(rxBytes));
                long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
                TX.setText(Long.toString(txBytes));
                mHandler.postDelayed(mRunnable, 1000);


                final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
                myChronometer.start();



                DisplayWifiState();
                this.registerReceiver(this.myWifiReceiver, new IntentFilter(
                        ConnectivityManager.CONNECTIVITY_ACTION));

            }

            private void registerReceiver(BroadcastReceiver myWifiReceiver2,
                    IntentFilter intentFilter) {
                // TODO Auto-generated method stub

            }

            private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {

                @Override
                public void onReceive(Context arg0, Intent arg1) {
                    // TODO Auto-generated method stub
                    NetworkInfo networkInfo = (NetworkInfo) arg1
                            .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        DisplayWifiState();
                    }
                }
            };

            public void DisplayWifiState() {

                ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
                NetworkInfo myNetworkInfo = myConnManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

                if (myNetworkInfo.isConnected()) {

                    textSsid.setText(myWifiInfo.getSSID());

                    textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
                            + WifiInfo.LINK_SPEED_UNITS);
                    textRssi.setText(String.valueOf(myWifiInfo.getRssi()));

                } else {
                    textSsid.setText("---");

                    textSpeed.setText("---");
                    textRssi.setText("---");




                }
    };
};}

服务类完整源代码:

import com.parse.ParseObject; 
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;

public class Service_class extends Service {
    public static String TAG="TEST TAG";
  TextView textSsid, textSpeed, textRssi;

  public Handler mHandler = new Handler();
    public long mStartRX = 0;
  public long mStartTX = 0;
  public long txBytes;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate();

        Intent intent = getIntent();
        String[] myStrings = intent.getStringArrayExtra("strings");


  textSsid = (TextView) findViewById(R.id.Ssid);
  textSpeed = (TextView) findViewById(R.id.Speed);
  textRssi = (TextView) findViewById(R.id.Rssi);
  Long.toString(mStartTX);
  Long.toString(mStartRX);
  Long.toString(txBytes);

   mStartRX = TrafficStats.getTotalRxBytes();
     mStartTX = TrafficStats.getTotalTxBytes();
     if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
      AlertDialog.Builder alert = new AlertDialog.Builder(this);
          alert.setTitle("Uh Oh!");
          alert.setMessage("Your device does not support traffic stat monitoring.");
          alert.show();
     } else {
      mHandler.postDelayed(mRunnable, 1000);
     }

  }

 private Intent getIntent() {
        // TODO Auto-generated method stub
        return null;
    }

private TextView findViewById(int speed) {
      //   TODO Auto-generated method stub
      return null;
  }

private final Runnable mRunnable = new Runnable() {
     public void run() {

         TextView RX = (TextView)findViewById(R.id.RX);
      TextView TX = (TextView)findViewById(R.id.TX);
      long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
      RX.setText(Long.toString(rxBytes));
      long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
      TX.setText(Long.toString(txBytes));
      mHandler.postDelayed(mRunnable, 1000);
      ParseObject testObject = new ParseObject("TestObject");
      testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
      testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
      testObject.put("DataRSSI", String.valueOf(textRssi));
      testObject.put("DataSpeed", String.valueOf(textSpeed));
      testObject.saveInBackground();


      final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
      myChronometer.start();



      DisplayWifiState();
      this.registerReceiver(this.myWifiReceiver, new IntentFilter(
              ConnectivityManager.CONNECTIVITY_ACTION));

  }

  private Chronometer findViewById(int chronometer) {
      //   TODO Auto-generated method stub
      return null;
  }

  private void registerReceiver(BroadcastReceiver myWifiReceiver2,
              IntentFilter intentFilter) {
         //    TODO Auto-generated method stub

      }

      private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {

      @Override
      public void onReceive(Context arg0, Intent arg1) {
         //    TODO Auto-generated method stub
          NetworkInfo networkInfo = (NetworkInfo) arg1
                  .getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
          if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
              DisplayWifiState();
          }
      }
  };

  public void DisplayWifiState() {

      ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
      NetworkInfo myNetworkInfo = myConnManager
              .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
      WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

      if (myNetworkInfo.isConnected()) {

          textSsid.setText(myWifiInfo.getSSID());

          textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
                  + WifiInfo.LINK_SPEED_UNITS);

          textRssi.setText(String.valueOf(myWifiInfo.getRssi()));


      } else {
          textSsid.setText("---");

          textSpeed.setText("---");
          textRssi.setText("---");
         }}};

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
     //   Log.d(TAG, "starting service");

        ParseObject testObject = new ParseObject("TestObject");

        testObject.put("DataOut", Long.valueOf(txBytes));
      testObject.put("DataIn", Long.valueOf(mStartRX));
      testObject.put("DataRSSI", String.valueOf(textRssi));
      testObject.put("DataSpeed", String.valueOf(textSpeed));
      testObject.saveInBackground();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {

        super.onDestroy();
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();

    }

    @Override
    public void onCreate() {
        super.onCreate();

    }

}
4

3 回答 3

0

myWifiInfo未在您使用它的地方声明/可见。WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();像上面在 run() 方法中所做的那样实例化它 。仅仅因为您已经myWifiInfo在代码中的某处声明了并不意味着您可以在任何地方使用它。myWifiInfo从 run 方法中看不到的声明。它被称为“范围”。

所以改变这个:

  testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
  testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));

WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); 
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
于 2013-04-15T08:22:43.750 回答
0

当您编写时,new Runnable(){...}您正在实例化一个内联类;insede 这个类this是指类本身。您指的是,this.myWifiReceiver但我看不到该myWifiReceiver对象的声明位置。

于 2013-04-15T08:25:07.690 回答
0
btnStart.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);

   intent.putExtra("strings", myStrings);
    startActivity(intent);
            startService(new Intent(getBaseContext(), Service_class.class));


        }
    });

    // click listener for the button to stop service
    Button btnStop = (Button) findViewById(R.id.button2);
    btnStop.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);
           intent.putExtra("strings", myStrings);
    startActivity(intent);
            stopService(new Intent(getBaseContext(), Service_class.class));
        }
    });

试试这个...myStrings 全局声明并删除意图并将值行写入按钮单击事件。

于 2013-04-15T10:27:17.273 回答