我的Activity正在尝试创建一个AlertDialog,它需要一个Context作为参数.如果我使用,这可以按预期工作:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
Run Code Online (Sandbox Code Playgroud)
但是,我很谨慎地使用"this"作为上下文,因为当Activity被销毁并重新创建甚至在屏幕旋转之类的简单事件时,可能会发生内存泄漏.来自Android开发者博客上的相关帖子:
有两种简单的方法可以避免与上下文相关的内存泄漏.最明显的一个是避免在其自身范围之外逃避上下文.上面的例子显示了静态引用的情况,但内部类及其对外部类的隐式引用可能同样危险.第二种解决方案是使用Application上下文.只要您的应用程序处于活动状态并且不依赖于活动生命周期,此上下文就会存在.如果您计划保留需要上下文的长期对象,请记住应用程序对象.您可以通过调用Context.getApplicationContext()或Activity.getApplication()轻松获取它.
但是对于这AlertDialog()两者来说,getApplicationContext()或者getApplication()作为一个Context是可接受的,因为它抛出异常:
"无法添加窗口 - 令牌null不适用于应用程序"
那么,这真的应该被视为一个"错误",因为我们被正式建议使用Activity.getApplication(),但它没有宣传的功能吗?
吉姆
这让我很难过,我在Android 2.1-r8 SDK中使用它:
ProgressDialog.show(getApplicationContext(), ....);
Run Code Online (Sandbox Code Playgroud)
还有
Toast t = Toast.makeText(getApplicationContext(),....);
Run Code Online (Sandbox Code Playgroud)
使用getApplicationContext()崩溃ProgressDialog和Toast....导致我这个问题:
尽管分享了"上下文"的措辞,但活动上下文和应用程序上下文之间的实际差异是什么?
当我尝试打开对话框时,我收到以下Android异常.有人可以帮我理解发生了什么,我该如何解决这个问题?
android.view.WindowManager$BadTokenException:
Unable to add window -- token null is not for an application
at android.view.ViewRoot.setView(ViewRoot.java:509)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:241)
Run Code Online (Sandbox Code Playgroud) android runtimeexception android-dialog android-windowmanager
从我的主要activity,我需要调用内部类和类中的方法,我需要显示AlertDialog.解除后,按下确定按钮后,转发到Google Play进行购买.
在大多数情况下,事情完美无缺,但对于少数用户而言,它正在崩溃builder.show(),我可以看到"android.view.WindowManager$BadTokenException:无法在崩溃日志中添加窗口.请建议.
我的代码非常像这样:
public class classname1 extends Activity{
public void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.<view>);
//call the <className1> class to execute
}
private class classNamename2 extends AsyncTask<String, Void, String>{
protected String doInBackground(String... params) {}
protected void onPostExecute(String result){
if(page.contains("error"))
{
AlertDialog.Builder builder = new AlertDialog.Builder(classname1.this);
builder.setCancelable(true);
builder.setMessage("");
builder.setInverseBackgroundForced(true);
builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton){
dialog.dismiss();
if(!<condition>)
{
try
{
String pl = "";
mHelper.<flow>(<class>.this, SKU, RC_REQUEST,
<listener>, …Run Code Online (Sandbox Code Playgroud) 我想使用数字选择器来获取用户的折扣百分比.一旦用户输入销售价格,我想要一个对话框来询问折扣百分比.我找不到在对话框中集成numberpicker的方法.
伙计们 - 谁能解释这个堆栈?请注意,我的代码无处可去.如果你谷歌中的任何一个例外,遇到此问题的每个人都试图在活动终止后创建对话框,这似乎不是这里的情况.这只是一个简单的活动简历.我经常看到该领域的客户报告此异常,并且如果可能的话想要纠正它.
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@405177d8 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:527)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2268)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1721)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:2955)
at android.app.ActivityThread.access$1600(ActivityThread.java:124)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:972)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:3806)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
at dalvik.system.NativeStart.main(Native Method)
Run Code Online (Sandbox Code Playgroud)
更新:
以下是我能够远程检索此堆栈的方法.首先,我在我的活动的onCreate顶部添加了一个uncaughtExceptionHandler:
try {
File crashLogDirectory = new File(Environment.getExternalStorageDirectory().getCanonicalPath() + Constants.CrashLogDirectory);
crashLogDirectory.mkdirs();
Thread.setDefaultUncaughtExceptionHandler(new RemoteUploadExceptionHandler(this, crashLogDirectory.getCanonicalPath()));
} catch (Exception e) {
if (MyActivity.WARN) Log.e(MyActivity.TAG, "Exception setting up …Run Code Online (Sandbox Code Playgroud) 我使用MediaPlayer在前台服务中播放音频文件.当用户点击与前台服务关联的通知时,我使用Intent启动一个Activity,如下所示:
Intent audioPlayIntent = new Intent(context, AudioPlayActivity.class);
audioPlayIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
audioPlayIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, audioPlayIntent, 0);
Run Code Online (Sandbox Code Playgroud)
然后,此Activity绑定到服务以向用户显示MediaController.
这是服务中的绑定代码:
public class AudioPlayerServiceBinder extends Binder{
public AudioPlayerService getAudioService(){
return AudioPlayerService.this; //this class is declared in AudioPlayerService.java, so it has access to the Service instance.
}
}
Run Code Online (Sandbox Code Playgroud)
..并且在Activity中onStart我调用了这个方法:
private void bindAudioService()
{
Intent i = new Intent(this, AudioPlayerService.class);
serviceConnection = new AudioServiceConnection();
bindService(i, serviceConnection, 0);
}
Run Code Online (Sandbox Code Playgroud)
我在下面的mediaController.show(5000)行上遇到异常:
private class AudioServiceConnection implements ServiceConnection{
AudioPlayerServiceBinder audioServiceBinder;
@Override
public void onServiceConnected(ComponentName name, IBinder serviceBinder) …Run Code Online (Sandbox Code Playgroud) Iam 从预定服务中调用Asynctask每10分钟就会运行一次.
运行Service时,Progress对话框从OnpreExecute获取Exception .
错误:
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:594)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:259)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
Run Code Online (Sandbox Code Playgroud)
编辑1: 警报管理器每5分钟调用一次服务
/*Alarm manager Service for From Server*/
private void setServerFetch() {
// for to Server to GPS PING
Intent myIntent1 = new Intent(LoginPage.this, AlarmService.class);
pendingintent1 = PendingIntent.getService(LoginPage.this, 1111, myIntent1, 0);
AlarmManager alarmManager5 = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeInMillis(System.currentTimeMillis());
calendar1.add(Calendar.SECOND, 1);
alarmManager5.set(AlarmManager.RTC_WAKEUP, …Run Code Online (Sandbox Code Playgroud) service android progressdialog android-asynctask android-pendingintent
我使用MvvmCross创建我的Android应用程序,我面临以下问题:
当我试图显示在ViewModel中创建的AlertDialog时,
出现" 未处理的异常:Android.Views.WindowManagerBadTokenException ".
public class MyViewModel : MvxViewModel
{
public ICommand ShowAlertCommand { get; private set; }
public AuthorizationViewModel()
{
ShowAlertCommand = new MvxCommand(() =>
{
var adb = new AlertDialog.Builder(Application.Context);
adb.SetTitle("Title here");
adb.SetMessage("Message here");
adb.SetIcon(Resource.Drawable.Icon);
adb.SetPositiveButton("OK", (sender, args) => { /* some logic */});
adb.SetNegativeButton("Cancel", (sender, args) => { /* close alertDialog */});
adb.Create().Show();
});
}
}
Run Code Online (Sandbox Code Playgroud)
当我在研究时,我发现它是因为传递了对Context的引用而不是在AlertDialog.Builder中的Activity.
在本主题中,我发现了以下决定:通过使用GetService()接收对当前Activity的引用,但我没有找到mvvmcross插件用于IMvxServiceConsumer,IMvxAndroidCurrentTopActivity接口.
我的问题是我可以从ViewModel显示AlertDialog吗?我怎样才能获得对Activity的引用,而不是Application.Context?什么是关闭AlertDialog的正确方法,用户将留在当前视图?
这是我的问题:
我正在尝试显示AlertDialog,但我似乎无法做到这一点.
这是我的代码:
tv.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
final EditText input = new EditText(c);
AlertDialog.Builder adb = new AlertDialog.Builder(c);
adb.setTitle(lb)
.setMessage("Test")
.setView(input)
.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
//tv.setText(input.getEditableText().toString());
Toast.makeText(c, input.getEditableText().toString(), Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
dialog.cancel();
}
}).show();
}
});
Run Code Online (Sandbox Code Playgroud)
我想在用户点击标签时显示此AlertDialog,然后在用户按OK时使用编辑文本更改标签值.
但是当它在点击时显示对话框时,它会崩溃.
07-18 16:04:59.240: E/AndroidRuntime(10503): FATAL EXCEPTION: main
07-18 16:04:59.240: E/AndroidRuntime(10503): android.view.WindowManager$BadTokenException: Unable to add window --
token null is …Run Code Online (Sandbox Code Playgroud)