2011-04-02 7 views
2

私はまだアンドロイドに初心者です。アンドロイドのクラスを使用する - コンテキストとヘルパークラスを使って作業する

私は次のようにネットクラスのメソッドを使用します:

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

と私のネットクラス

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

私は私が私のネットクラスを拡張すべきではないと考えていますアクティビティ?アプリを実行しているときにソースが見つかりませんでした。

+0

最初のコードサンプルの上部に数行がないようです。 – harpo

+0

どのリソースが見つかりませんか?一般的には少なくともあなたのクラスの1つで活動を拡張する必要があります。 – RoflcoptrException

+0

アプリケーションのAndroidマニフェストファイルで、コードのすべてのアクティビティを定義する必要があります。 –

答えて

3

私は私の活動を延長するべきではないと私は信じています アクティビティのネットクラス?

正解!

あなたネットクラスはヘルパーはそう単純のように定義することができ、単にです:アンドロイドでActivityクラスをするために使用されwifi = new Net(this);

を使用し、あなたのwifiオブジェクトを作成すると

public class Net { 

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

    // Your other methods here... 
} 

ボタン、テキストビューなどの視覚的/インタラクティブな要素(基本的にユーザーが対話する必要があるもの)のためのUIフレームワークを提供します。これは、ネットクラスには適していません。

+0

アクティビティやサービスから継承しないと、getSystemServiceメソッドが認識されません。( – Alanagh

+0

@Alanagh:Netクラスの編集済みコード例を参照してください。アクティビティコンテキストをNetクラスに渡すと、 ctx.getSystemService()。 – Squonk

+0

実際、MisterSquonkは正しいです。ActivityクラスはContextを拡張しているので、現在のオブジェクトのgetSystemServiceのようなメソッドを呼び出すことができます。 + –