【问题标题】:How to use "Context" of one class into another class - Android如何将一个类的“上下文”用于另一个类 - Android
【发布时间】:2014-07-15 14:10:05
【问题描述】:

我在一堂课中使用了上下文。在另一个类中启动它时如何引用相同的上下文?

MyHttpClient.java

public class MyHttpClient extends DefaultHttpClient {


    final Context contextkey;

    public MyHttpClient(Context contextkeystore) {
        this.contextkey = contextkeystore;
    }

    @Override
    protected ClientConnectionManager createClientConnectionManager() {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        // Register for port 443 our SSLSocketFactory with our keystore
        // to the ConnectionManager
        registry.register(new Scheme("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);
    }

    private SSLSocketFactory newSslSocketFactory() {
        try {
            // Get an instance of the Bouncy Castle KeyStore format
            KeyStore trusted = KeyStore.getInstance("BKS");
            // Get the raw resource, which contains the keystore with
            // your trusted certificates (root and any intermediate certs)
            InputStream in = contextkey.getResources().openRawResource(R.raw.mykeystore);
            try {
                // Initialize the keystore with the provided trusted certificates
                // Also provide the password of the keystore
                trusted.load(in, "mysecret".toCharArray());
            } finally {
                in.close();
            }
            // Pass the keystore to the SSLSocketFactory. The factory is responsible
            // for the verification of the server certificate.
            SSLSocketFactory sf = new SSLSocketFactory(trusted);
            // Hostname verification from certificate
            // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
            sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            return sf;
        } catch (Exception e) {
            throw new AssertionError(e);
        }
    }
}

在另一个类中使用:

DefaultHttpClient client = new MyHttpClient(getApplicationContext()); ?? 

这里“getApplicationContext”不起作用并显示错误

【问题讨论】:

  • 你从哪里调用 getApplicationContext()?你能发布在 getApplicationContext() 上抛出的错误吗?
  • 我在“DefaultHttpClient client = new MyHttpClient(getApplicationContext());”中的另一个类中调用它
  • 这个类是否扩展了Activity?你能把错误日志贴在 getApplicationContext() 上吗?
  • 不,这个类不是活动类。没有错误,但它显示红色下划线并要求我创建方法“getApplicationContext()”

标签: java android class android-context


【解决方案1】:

获取Application Context的简单方法如下

package com.example.testactivity;

        public class App extends Application {
        public static Context context;

    public void onCreate() {
                    super.onCreate();
                    context=getApplicationContext();
                           }
    public static Context getcontext(){
     return context;
     }

   }

在清单文件中 在应用程序标签中添加该行

<application
        android:name="com.example.testactivity.App" 
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

现在您将在应用程序中的任何位置查看应用程序的上下文

打个电话

App.getcontext();

开心:)

【讨论】:

    【解决方案2】:

    您需要一个有效的上下文来使用 SSL 扩展 DefaultHttpClient。

    似乎调用您的 MyHttpClient 构造函数的类没有有效的上下文来传递给 HttpClient。

    您应该通过该类将上下文传递给您的客户端:

    • 从您的应用启动的地方开始(Launcher Activity、Service 等...)
    • 创建您的类(您尚未给我们命名),将 getApplicationContext 或活动转换 (this) 作为参数传递。
    • 让您的类创建 MyHttpClient,将所述上下文传递给构造函数。

    是这样的:

    public class Main extends Activity
    {
          private Foo myfoo;
    
          @Override
          protected void onCreate(Bundle icicle)
          {
                 myfoo = new Foo(this); //Or myFoo = new Foo(getApplicationContext());   
          }
    }
    
    public class Foo
    {
        private Context mycontext;
        private MyHttpClient myclient;
    
        public Foo(Context ctx)
        {
            mycontext = ctx;//No need to save the context if you aren't reusing it after this.
            myclient = new MyHttpClient(mycontext); 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      • 2018-10-15
      • 2021-12-01
      • 1970-01-01
      相关资源
      最近更新 更多