可以在Service [android app]中显示对话框吗?

时间:2012-03-12 16:06:00

标签: java android service

我是Android新手,所以我正在尝试开发一个应用程序,在特定时间后向用户显示通知,我不知道:是否可以使用Service中的对话框!或不!...

我的目标是:在特定时间后问他一个问题,如下面的代码所示,

import android.app.AlertDialog;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyAlarmService extends Service {

    @Override
    public void onCreate() {
        Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG)
                .show();
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG)
                .show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG)
                .show();
        // For Notification
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setTitle("Conformation");
        alertDialog
                .setMessage("Are you sure you want to Expand Report Region?");
        alertDialog.setButton("Yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Sending a Message to server that the plaintiff wants to
                // expand report region
            }
        });
        alertDialog.setButton2("No", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // Do nothing
            }
        });
    }
}

另外我不知道我应该使用Service还是BroadcastReceiver?

任何建议,在此先感谢=)

2 个答案:

答案 0 :(得分:0)

使用广播接收器和服务总是更好。在广播接收器中注册意图,并从广播接收器重定向请求到服务。

可以从服务中显示对话框。你需要的只是一个活动。

简而言之,您的应用程序将拥有一个活动,一个服务和一个广播接收器。您的广播接收器将捕获将重定向到服务的意图,然后您的服务将调用显示对话框的活动。

BroadCast接收器 - >服务 - >活性

答案 1 :(得分:0)

BroadCast接收器 - >服务 - >活动这个顺序很好。 要在不按任何按钮调用方法的情况下显示警告对话框,请在Activity的onCreate()方法中显示showDialog()。