Reputation: 9
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
Upvotes: 0
Views: 2005
Reputation: 2208
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));
Upvotes: 1