Android API级别8引入了该Context.getExternalFilesDir()方法,为File特定于您的应用的SD卡路径提供对象引用.我想知道如何模仿这个低至API等级5.
我看到有一种Context.getDir()方法,但我无法从阅读中看出它是如何区别的.
我想从onChange()我的方法中发出一个意图ContentObserver.我正在尝试在发送SMS时运行服务,因此ContentObserver,但是Eclipse给了我错误,因为它无法解析"上下文".下面是我的课程代码.
public class SmsObserver extends ContentObserver {
public SmsObserver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// On outgoing SMS, do this
Intent update = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, update, 0);
try {
pendingIntent.send();
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud) 我已经在我的Android应用程序的各个活动中存储了一个全局变量,使用了Soonil所解释的android.app.Application的子类(如何在Android中声明全局变量?).
方法如下:
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,这种方法适用于从我的任何活动中访问全局变量.但是今天使用相同的方法,我得到以下错误:
Cannot make a static reference to the non-static method getApplicationContext()
from the type ContextWrapper
Run Code Online (Sandbox Code Playgroud)
与之前的关键区别在于新的Activity实际上是一个片段(SherlockFragmentActivity,确切地说).
任何想法为什么我不能像以前一样访问appState,并且有一个很好的解决方法吗?
非常感谢.
编辑:很好的捕获,马特B.事实证明我实际上调用的地方getApplicationContext()在另一个类中.这是调用点:
public class MyActivity extends SherlockFragmentActivity {
public static class AccountListFragment extends SherlockListFragment …Run Code Online (Sandbox Code Playgroud) 我有一个带有ImageButton的自定义标题栏,它会生成一个对话框,我希望能够在从对话框中选择列表项时在地图(在另一个类中)显示位置(放置itemizedOverlay),并且标题栏和地图在相同的背景.我在某处读到了我可以使用上下文调用另一个类的方法.我怎么能这样做?
public class MyTitleBar extends RelativeLayout{
private Context context;
public MyTitleBar(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
initViews();
}
// set up all the buttons & clicks
private void initViews() {
final ImageButton listImgBtn = (ImageButton) findViewById(R.id.more);
final CharSequence [] listItems = {"Elderly","Events"};
listImgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(context instanceof UserHome)
{
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("List");
builder.setItems(listItems, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface …Run Code Online (Sandbox Code Playgroud) 我是Android测试的新手,我正在尝试使用MockContext创建一个ApplicationTestCase(实际上我正在尝试使用重命名模拟上下文).但我不断收到AssertionFailedError.到目前为止,这是我的基本代码:
AppTests.java
package com.myProject.test;
import android.test.ApplicationTestCase;
public class AppTests extends ApplicationTestCase<MyApplication> {
public AppTests() {
super(MyApplication.class);
}
@Override
protected void setUp() throws Exception {
final RenamingMockContext mockContext = new RenamingMockContext(getContext());
setContext(mockContext);
createApplication();
}
}
Run Code Online (Sandbox Code Playgroud)
MyApplication.java
package com.myProject.test;
import android.app.Application;
public class MyApplication extends Application {
public MyApplication() {
}
@Override
public void onCreate() {
super.onCreate();
}
}
Run Code Online (Sandbox Code Playgroud)
RenamingMockContext.java
package com.myProject.test;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContext;
public class RenamingMockContext extends RenamingDelegatingContext {
private static final String PREFIX = …Run Code Online (Sandbox Code Playgroud) 我无法使用上下文FragmentPagerAdapter.RadioGroup(this)给我未定义的错误.我使用getContext()而不是这个,但无法实现它
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
final RadioGroup rg = new RadioGroup(this); // what can I use instead of "this" ?
}
Run Code Online (Sandbox Code Playgroud) 我通过扩展AsyncTask类来定义一个单独的线程.在这个类中,我在AsyncTask onPostExecute和onCancelled方法中执行一些Toasts和Dialog .祝酒词需要应用程序的上下文,所以我需要做的就是:
Toast.makeText(getApplicationContext(),"Some String",1);
Run Code Online (Sandbox Code Playgroud)
创建对话框时AlertDialog.Builder,还需要在其构造函数中使用上下文.我认为这个上下文应该是Activity的上下文吗?即
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
Run Code Online (Sandbox Code Playgroud)
where getActivity可以是返回当前活动的用户定义的类.如果是这样,处理这种情况的最佳方法是什么?创建一个类getActivity或将当前活动的上下文传递给AsyncTask的构造函数?
我想我正在尝试理解使用Context- 我注意到内存泄漏可能是一个问题(还没有真正理解这一点)以及如何使用getApplicationContext()是最好的方法.
android constructor inner-classes android-context android-asynctask
我意识到这个问题已被多次询问,但我仍然无法完全理解这个概念.在我的应用程序中,我使用静态实用程序类来保留常用方法(如显示错误对话框)
这是我的静态类的样子:
public class GlobalMethods {
//To show error messages
public static final void showSimpleAlertDialog(final Activity activity, String message, final boolean shouldFinishActivity) {
if (!activity.isFinishing()) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_HOLO_DARK);
builder.setCancelable(true).setMessage("\n" + message + "\n").setNeutralButton(activity.getResources().getString(R.string.label_ok), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
}).setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
if (shouldFinishActivity)
activity.finish();
}
}).show();
}
}
//check for connectivity
public …Run Code Online (Sandbox Code Playgroud) android memory-leaks pass-by-reference android-context utility-method
在我的一些应用程序中,我使用一些单例对象作为"管理器".我实例化它们Application.onCreate并将它传递给它ApplicationContext,我将它存储在一个WeakReference.
一些"管理器"方法在从a调用之后启动后台任务Activity,所以我将Activity's' 传递context给方法,并保持一个WeakReference到那个(并在其中使用AsyncTask).该引用一直保持,直到下一次的Activity调用转到后台的方法,当WeakReference设置为新Activity的context.
我的问题是,是否将ApplicationContext必须保持在WeakReference,并在那里与保持任何问题Activity的context这样呢?
有很多问题需要处理Context,使用哪些上下文以及如何存储它等等.但每次我将它传递给一个对象,或者创建一个提供访问权限的静态或单例时,我都会觉得很脏.我不确定我得到了什么味道,但它肯定闻起来.
我认为另一种方法是创建充当上下文代理的类,而不是传递给上下文,它将上下文的特性的子集定义为一种接口(不是语言interface关键字).
替代方案的示例(为了便于阅读,省略了代码):
// in activity.onCreate():
StateStorer ss = new StateStorer (getApplicationContext());
RememberMe obj = new RememberMe(ss);
ss.restore();
// in activity.onDestroy()
ss.save();
// the "proxy"
class StateStorer {
List<StateStorerListener> listeners;
Context mContext;
public StateStorer(Context context){
mContext = context;
}
public SharedPreferences getSharedPreferences(String tag){
return mContext.getSharedPreferences(tag, 0);
}
public save(){
// tell listeners to save
}
public restore(){
// tell listeners to restore
}
}
// an example class that needs to save state
class RememberMe { …Run Code Online (Sandbox Code Playgroud) android ×10
android-context ×10
java ×2
constructor ×1
directory ×1
filesystems ×1
memory-leaks ×1
mocking ×1
static ×1
unit-testing ×1