简体   繁体   中英

Android -How to display alert dialog builder in service class

I have Implemented one service class that is (extends Service) in Android .In my service class I have to display one Alert dialog ,How can I do this?

Here is my code

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

In that above code I have Implemented but I don't know how to implement alert dialog in service class

You will have to configure your dialog as System alert as only System alert can be shown using service .

Add this to your manifest file :

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

Edit :

Create a style for your dialog :

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

add it while creating the builder :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM