AndroidでのContextの詳細について


AndroidベースコンセプトContextの役割
 
Context文字通りの意味コンテキストはframework packageのandroidにある.content.Contextでは、実はこのクラスはLONG型で、Win 32のHandleハンドルのように、多くの方法でContextを通じて呼び出し者のインスタンスを識別する必要があります.例えば、Toastの最初のパラメータはContextです.一般的にActivityでは、呼び出し者を表すインスタンスがActivityであり、buttonのonClick(View view)などの方法では、thisを使用するとエラーが報告されるので、Activity Nameを使用する可能性があります.これは、Contextを実装するクラスが主にAndroid特有のいくつかのモデル、Activity、Service、BroadcastReceiverを持っているためです.通常、Contextインスタンスを必要とするメソッドには、主に様々なサービス実装クラスがあります.たとえば、SensorManagerがインスタンス化時にgetSystemService(String)メソッドを必要とする場合はContextのインスタンスによって実行する必要があります.また、openFileInputや一般的なToastのmakeTextメソッドなどのプライベートファイルシステムI/Oもあります.android context理解
 android context       ,                。 android    context,    application context,   activity context,                activity context。
    activity onCreate:
protected void onCreate(Bundle state) {
        super.onCreate(state);

        TextView label = new TextView(this); //  context view control
        label.setText("Leaks are bad");

        setContentView(label);
}
 activity context   view,   view      activity   ,    activity     :view hierachy, resource 。
    context        ,        。
        gc      activity   。

Leaking an entire activity        。

        ,        activity,      ,       。

            ,            ,                      ,    。                    Drawable,  Activity               。
    :
public class myactivity extends Activity {
        private static Drawable sBackground;
        protected void onCreate(Bundle state) {
                super.onCreate(state);

                TextView label = new TextView(this);
                label.setText("Leaks are bad");

                if (sBackground == null) {
                        sBackground = getDrawable(R.drawable.large_bitmap);
                }
        label.setBackgroundDrawable(sBackground);//drawable attached to a view

        setContentView(label);
        }
}
          ,       。          leak( gc    activity)。
      ,               activity。   drawable view   ,drawable   view  reference, sBackground   label   , label   activity   。  drawable    ,                ,              activity,         。gc                。

              activity             activity,        activity     activity       。      application context。application context  application   , activity       。application context    Context.getApplicationContext  Activity.getApplication    。

  context       ,      :
1.              activity context,     activity     activity          
2.           ,    application context
3.          ,       ,        ,                     

パッケージNameによるContextの構築
 
 
            context    getApplicationContext,
         packageName     Context ? 
Android                    。
       
     try 
    {
            Context ctx= createPackageContext("com.android123.Cwj", 0);

            //ctx   com.android123.cwj   
    } 
      catch (NameNotFoundException e) 
      {
        //     pacakgeName                    
      }
      ,createPackageContext           CONTEXT_INCLUDE_CODE    CONTEXT_IGNORE_SECURITY ,
     4 2,   0。              CONTEXT_IGNORE_SECURITY   ,
          SecurityException   .

[Android]Contextはどう書きますか?  
 
        AlertDialog,        

view sourceprint?1 AlertDialog.Builder alert =new AlertDialog.Builder(this);  

2 alert.setTitle("Warning");  

3 alert.setMessage("Wrong time!");  

4 alert.show(); 

 


          AlertDialog.Builder(Context arg)     Context        ,      Activity  ,   this,           AlertDialog。

 


        ,         Public interface CustomPickerListener,                   AlertDialog,  ,      this       :The constructor AlertDialog.Builder(new CustomPickerListener(){}) is undefined.


       this       ,             ?


      context    Interface to global information about an application environment. This is an abstract class whose implementation is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities, broadcasting and receiving intents, etc.


               .   .this ,   

view sourceprint?1 AlertDialog.Builder alert =new AlertDialog.Builder(com.android.alcoholtest.AlcoholTest.this); 

      


 
 
AndroidでActivityが変数を共有するもう一つの方法:Application context
 
Android    Activity     ,    Intent Bundle         。

  view plaincopy to clipboardprint?

  Intent intent = new Intent();

  intent.setClass(A.this, B.class);

  Bundle bundle = new Bundle();

  bundle.putString("Info", "Information");

  intent.putExtras(bundle);

  startActivity(intent);

  Intent

  intent = new Intent();

  intent.setClass(A.this, B.class);

  Bundle bundle = new Bundle();

  bundle.putString("Info", "Information");

  intent.putExtras(bundle);

  startActivity(intent);

       Activity          ,  Bundle     ,    Activity       。

            , java          ,  android            Application context。

       ,   Application

  view plaincopy to clipboardprint?

  class MyApp extends Application {

  private String myState;

  public String getState() {

  return myState;

  }

  public void setState(String s) {

  myState = s;

  }

  }

  class MyApp extends

  Application {

  private String myState;

  public String getState() {

  return myState;

  }

  public void setState(String s) {

  myState = s;

  }

  }

   AndroidManifest.xml application  name      ,     :

  view plaincopy to clipboardprint?

  

  < p> 

  android:name=".MyApp" android:icon="@drawable/icon"

  android:label="@string/app_name">

     :

  view plaincopy to clipboardprint?

  class Blah extends Activity {

@Override

  public void onCreate(Bundle b){

  ...

  MyApp appState = ((MyApp)getApplicationContext());

  String state = appState.getState();

  ...

  }

  }

  class Blah extends

  Activity {

  @Override

  public void onCreate(Bundle b){

  ...

  MyApp appState = ((MyApp)getApplicationContext());

  String state = appState.getState();

  ...

  }

  }

      :http://stackoverflow.com/questions/708012/android-how-to-declare- global-variables

  The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.

  --          , java          ,  android            Application context。

  As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.

  --  Activity   Context,             ,android     single instance 。

  The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):

  --             android.app.Application   ,   manifest        ,   android              ,            Context.getApplicationContext()        ,         (  )。

 
 
[テクニック]アプリケーションContext-[Android学習ノート]を任意の場所で取得
 
Android            Context,         component (Activity, Provider  )       api   Context,                 。  ,         Application        。

import android.app.Application;

public class MyApplication extends Application {
    private static MyApplication instance;

    public static MyApplication getInstance() {
        return instance;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        instance = this;
    }
}

   manifest    name="mypackage.MyApplication"          MyApplication.getInstance()       Context 。

Androidは他のパッケージのContextインスタンスを取得して悪いことをします
 
 
Android  Context   ,       。Context       ,  activity、    、            、  classLoader、      。           Context  ,                      。 

                ?       , !
      Context  createPackageContext  ,             ,           Context  ,        。 


               :
1。packageName    ,   Context   
2。flags     , CONTEXT_INCLUDE_CODE CONTEXT_IGNORE_SECURITY    。CONTEXT_INCLUDE_CODE        ,                。CONTEXT_IGNORE_SECURITY          ,          ,         ,       。 


             ,                。
               chroya.demo,  Main,   print,    : 

Java   
package chroya.demo;   
  
import android.app.Activity;   
import android.os.Bundle;   
import android.util.Log;   
  
class Main extends Activity {   
       
    @Override  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
    }   
       
    public void print(String msg) {   
        Log.d("Main", "msg:"+ msg);   
    }   
}  

package chroya.demo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

class Main extends Activity {
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    public void print(String msg) {
        Log.d("Main", "msg:"+ msg);
    }
}            Main print        : 

Java   
Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);   
//        
Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");   
//         
Object owner = clazz.newInstance();   
//  print  ,          
Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");  

Context c = createPackageContext("chroya.demo", Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
//     
Class clazz = c.getClassLoader().loadClass("chroya.demo.Main");
//      
Object owner = clazz.newInstance();
//  print  ,       
Object obj = clazz.getMethod("print", String.class).invoke(owner, "Hello");       ok,  ,      chroya.demo  Main  print  ,    ,    Hello。 

         ,                ,     Context,        ,  ,       ,       。