Android - 如何在服务类中显示警告对话框构建器

时间:2016-05-23 09:31:59

标签: android service dialog

我在Android中实现了一个服务类(扩展服务)。在我的服务类中,我必须显示一个Alert对话框,我该怎么做?

这是我的代码

public class BackgroundService extends Service {

@Override
public void onCreate() {
    super.onCreate();
    //Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
    Log.i(tag, "Service created...");

}

@Override
public int  onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);
   AlertDialog.Builder builder = new AlertDialog.Builder(getApplication());
                                builder.setTitle("Test dialog");
                                builder.setMessage("Content");
                                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        //Do something
                                        dialog.dismiss();
                                    }
                                });
                                builder.setNegativeButton("Close", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int whichButton) {
                                        dialog.dismiss();
                                    }
                                });
                                AlertDialog alert = builder.create();
                                alert.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                                alert.show();

    return START_STICKY;

}
@Override
public void onDestroy() {
    super.onDestroy();
    t.cancel();
   // Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

在上面的代码中我已实现但我不知道如何在服务类中实现警报对话框

1 个答案:

答案 0 :(得分:1)

您必须将对话框配置为系统警报,因为只能使用服务显示系统警报。

将此添加到您的清单文件中:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

编辑:

为对话框创建样式:

<style name="dialog" parent="Theme.AppCompat.Dialog">
    <item name="android:windowNoTitle">true</item>
</style>

在创建构建器时添加它:

AlertDialog.Builder builder = new AlertDialog.Builder(new ContextThemeWrapper(getApplication(), R.style.dialog));