java - 在 android 中使用类 - 使用 Context 和 helper 类

标签 java android

我还是android新手,请有人帮忙。

我想使用 Net 类中的方法,如下所示:

package com.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;

public class MyApp extends Activity {

  /** Called when the activity is first created. */
  private Net wifi;

  TextView textStatus;    

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

    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.main);

    wifi=new Net(this);
    textStatus = (TextView) findViewById(R.id.text); 
    textStatus.append("Your online status is ");

    if (wifi.isOnline()) {
      textStatus.append("online "+wifi.getInfo());
    } else {
      textStatus.append("offline "+wifi.getInfo());
    }
  }
}

和我的网络类(class):

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;

public class Net {
  WifiManager wifi;
  ConnectivityManager cm;
  NetworkInfo netInfo;

  public Net (Context ctx) {
    cm = (ConnectivityManager) ctx.getSystemService(ctx.CONNECTIVITY_SERVICE);
    netInfo = cm.getActiveNetworkInfo();
    wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
  }

  public boolean isOnline() { 
    netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
      return true;
    } else {
      return false;
    }
  }

  public NetworkInfo[] getName() {
    NetworkInfo[] name=cm.getAllNetworkInfo();
    return name;    
  }

  public String getInfo() {
    // Get WiFi status
    WifiInfo info = wifi.getConnectionInfo();
    return info.getSSID().toString();
  }
}

我相信我不应该用 Activity 来扩展我的 Net 类?运行应用程序时,我收到未找到源错误。

最佳答案

I believe I should not be extending my Net class with Activity?

正确!

您的Net类只是助手,因此可以简单地定义为:

public class Net {

  public Net (Context ctx) {
    cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
    netInfo = cm.getActiveNetworkInfo();
  }

  // Your other methods here...
}

当您创建 wifi 对象时,请使用 wifi = new Net(this);

Android 中的 Activity 类用于为视觉/交互元素(例如按钮、 TextView 等)提供 UI 框架 - 基本上是用户需要交互的任何元素。这不适合您的 Net 类(class)。

关于java - 在 android 中使用类 - 使用 Context 和 helper 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5526221/

相关文章:

android - 将 View 层次结构旋转 90 度

java - 比较文件中的行

java - android - 无法实例化 Activity - ClassNotFound - 在一个 eclipse 上失败但在其他 eclipse 上失败

java - 关于java中无限期运行的小部件

java - 如何在打印流中创建文件夹?

android - 我的应用程序支持多屏幕吗?

android - 错误:.dex文件中方法引用的数量不能超过64k

java - Hibernate工具Pojo Generation默认使用Set

Android 从 MyLocation 类获取准确位置

android - 如何在 viewpager 滑动时播放声音