Вот что я нашел относительно использования context
:
1). Внутри самого Activity
используйте this
для надувания макетов и меню, регистрации контекстных меню, создания экземпляров виджетов, запуска других действий, создания новых Intent
в Activity
. создание экземпляров предпочтений или другие методы, доступные в Activity
.
Раздувная раскладка:
View mView = this.getLayoutInflater().inflate(R.layout.myLayout, myViewGroup);
Меню надувать:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
this.getMenuInflater().inflate(R.menu.mymenu, menu);
return true;
}
Регистрация контекстного меню:
this.registerForContextMenu(myView);
Инстанцирующий виджет:
TextView myTextView = (TextView) this.findViewById(R.id.myTextView);
Начало Activity
:
Intent mIntent = new Intent(this, MyActivity.class);
this.startActivity(mIntent);
Создание предпочтений:
SharedPreferences mSharedPreferences = this.getPreferenceManager().getSharedPreferences();
2). Для класса всего приложения используйте getApplicationContext()
, поскольку этот контекст существует для срока службы приложения.
Получить имя текущего пакета Android:
public class MyApplication extends Application {
public static String getPackageName() {
String packageName = null;
try {
PackageInfo mPackageInfo = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
packageName = mPackageInfo.packageName;
} catch (NameNotFoundException e) {
// Log error here.
}
return packageName;
}
}
Привязка класса приложения:
Intent mIntent = new Intent(this, MyPersistent.class);
MyServiceConnection mServiceConnection = new MyServiceConnection();
if (mServiceConnection != null) {
getApplicationContext().bindService(mIntent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
3). Для прослушивателей и других типов классов Android (например, ContentObserver) используйте подстановку контекста, например:
mContext = this; // Example 1
mContext = context; // Example 2
, где this
или context
- это контекст класса (Activity и т. Д.).
Activity
замена контекста:
public class MyActivity extends Activity {
private Context mContext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
}
}
Подстановка контекста слушателя:
public class MyLocationListener implements LocationListener {
private Context mContext;
public MyLocationListener(Context context) {
mContext = context;
}
}
ContentObserver
замена контекста:
public class MyContentObserver extends ContentObserver {
private Context mContext;
public MyContentObserver(Handler handler, Context context) {
super(handler);
mContext = context;
}
}
4). Для BroadcastReceiver
(включая встроенный / встроенный получатель) используйте собственный контекст получателя.
Внешний BroadcastReceiver
:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
sendReceiverAction(context, true);
}
private static void sendReceiverAction(Context context, boolean state) {
Intent mIntent = new Intent(context.getClass().getName() + "." + context.getString(R.string.receiver_action));
mIntent.putExtra("extra", state);
context.sendBroadcast(mIntent, null);
}
}
}
Встроенный / Встроенный BroadcastReceiver
:
public class MyActivity extends Activity {
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final boolean connected = intent.getBooleanExtra(context.getString(R.string.connected), false);
if (connected) {
// Do something.
}
}
};
}
5). Для служб используйте собственный контекст службы.
public class MyService extends Service {
private BroadcastReceiver mBroadcastReceiver;
@Override
public void onCreate() {
super.onCreate();
registerReceiver();
}
private void registerReceiver() {
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
this.mBroadcastReceiver = new MyBroadcastReceiver();
this.registerReceiver(this.mBroadcastReceiver, mIntentFilter);
}
}
6). Для тостов обычно используют getApplicationContext()
, но, где возможно, используют контекст, переданный из Activity, Service и т. Д.
Использовать контекст приложения:
Toast mToast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
mToast.show();
Использовать контекст, переданный из источника:
public static void showLongToast(Context context, String message) {
if (context != null && message != null) {
Toast mToast = Toast.makeText(context, message, Toast.LENGTH_LONG);
mToast.show();
}
}
И, наконец, не используйте getBaseContext()
, как советуют разработчики фреймворков Android.
ОБНОВЛЕНИЕ: Добавить примеры использования Context
.