从服务Android调用对话框时出错
当我试图打开一个对话框时,我得到以下android异常从服务Android调用对话框时出错,android,service,dialog,Android,Service,Dialog,当我试图打开一个对话框时,我得到以下android异常 09-20 09:27:46.119: W/System.err(558): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application 09-20 09:27:46.139: W/System.err(558): at android.view.ViewRoot.setView(Vie
09-20 09:27:46.119: W/System.err(558): android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
09-20 09:27:46.139: W/System.err(558): at android.view.ViewRoot.setView(ViewRoot.java:440)
09-20 09:27:46.139: W/System.err(558): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:181)
09-20 09:27:46.139: W/System.err(558): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:95)
09-20 09:27:46.139: W/System.err(558): at android.app.Dialog.show(Dialog.java:269)
09-20 09:27:46.139: W/System.err(558): at android.app.AlertDialog$Builder.show(AlertDialog.java:907)
我正在从Android服务调用dialog,我尝试了以下代码:
handler.post(new Runnable() {
public void run() {
try{
new AlertDialog.Builder(getApplicationContext()).setTitle("Alert!").setMessage("SIMPLE MESSAGE!").setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
}).show();
} catch(Exception ex){
ex.printStackTrace();
}
}
});
我想问题出在
getApplicationContext()
可能是它返回null,传递正确的上下文…您无法从服务打开对话框。对话框是一个UI组件,它需要与UI元素(活动)关联。您可以做的是从您的服务启动一个“看起来像”对话框的活动。您可以为活动的UI设置一个“DialogTheme”,使其看起来像一个标准的Android对话框。只需在StackOverflow中搜索“活动对话框主题”。步骤1:
创建MyReceiver类:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)){
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent);
}
}
步骤2:
创建类MyService
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class MyService extends Service {
public MyService() {
}
@Override
public void onCreate() {
//your SERVICE code here...
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
步骤3:
在MainActivity类中启动服务:
startService(new Intent(this, MyService.class));
如果我使用它而不是getApplicationContext(),问题仍然存在。可能是因为我正在从服务调用dialog。您的广播接收器将捕获重定向到服务的意图,然后您的服务将调用显示对话框的活动。广播接收器-->服务-->活动我需要更多详细信息:(