从Service Android调用对话框出错

时间:2012-09-20 09:41:21

标签: 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(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服务调用对话框,我尝试了以下代码:

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();
        }
    }
});

3 个答案:

答案 0 :(得分:1)

您无法从服务中打开对话框。 Dialog是一个UI组件,它需要与UI元素(Activity)相关联。你可以做的是从你的服务开始一个“看起来像”对话的活动。您可以为Activity提供一个“DialogTheme”,使其看起来像一个标准的Andrdoid对话框。只需在StackOverflow中搜索“活动对话框主题”。

答案 1 :(得分:0)

我想问题出在getApplicationContext()可能会返回null,传递正确的上下文......

答案 2 :(得分:0)

第1步: 创建类MyReciever:

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));