如何在"服务中的活动"类中显示对话框



我有一个正在运行的服务,它将每30秒从服务器获取一个位置。现在,当我没有从服务器获得任何数据时,我想显示一个弹出对话框,显示"Trip is not started"。单击对话框后,希望完成活动并停止服务。我怎样才能做到这一点?

我的服务等级如下:

public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread = null;
ArrayList<String> mArrLatitude = null;
ArrayList<String> mArrLongitude = null;
ArrayList<String> mArrTime = null;
ArrayList<String> mArrAddress = null;
ScheduledExecutorService scheduleTaskExecutor = null;

//    private Handler mHandler = new Handler();
private Runnable runnable = new Runnable() {
@Override
public void run() {
getLocationOnline();
}
};
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
this.context = this;
this.isRunning = false;
mArrLatitude = new ArrayList<>();
mArrLongitude = new ArrayList<>();
mArrTime = new ArrayList<>();
mArrAddress = new ArrayList<>();
scheduleTaskExecutor = Executors.newSingleThreadScheduledExecutor();
scheduleTaskExecutor.scheduleAtFixedRate(runnable, 0, 15, TimeUnit.SECONDS);
Log.d("Testing", "Service is started");
createNotification();
}
@Override
public void onDestroy() {
super.onDestroy();
scheduleTaskExecutor.shutdownNow();
runnable = null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
runnable.run();
return START_REDELIVER_INTENT;
}
private void createNotification()
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startMyOwnForeground(){
String NOTIFICATION_CHANNEL_ID = "my_channel_01";
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.drawable.ic_phone_android_black_24dp)
.setContentTitle("IPL tracker is in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}

private void getLocationOnline(){

Log.d("Testing", "inside the   getLocationOnline  "+Constants.BASE_URL+Constants.GET_STUDENT_SERVICE+"35004"+Constants.GET_CURR_TRIP);
JsonArrayRequest jsonObjReq = new JsonArrayRequest(Constants.BASE_URL+Constants.GET_STUDENT_SERVICE+"35004"+Constants.GET_CURR_TRIP,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//                        showResponse(response, "Showing POST request response...");
try
{
mArrLatitude.clear();
mArrLongitude.clear();
mArrTime.clear();
mArrAddress.clear();
if(response.length() == 0)
{
Log.d("Testing", "JSON Array is 0  ");
//                                progressDialog.cancel();
Toast.makeText(getApplicationContext(),"Trip is stopped or not started yet", Toast.LENGTH_LONG).show();
//                                stopSelf();
scheduleTaskExecutor.shutdownNow();
runnable = null;
}
else
{
Log.d("Testing", "666  ");
int len = response.length();
for (int i = 0; i < len; i++)
{
JSONObject address = (JSONObject) response.get(i);
String lat = "";
String longt = "";
String currtime = "";
String loc_addr = "";
lat = address.getString("latitude");
longt = address.getString("longitude");
currtime  = address.getString("currtime");
loc_addr = address.getString("locationAddress");
mArrLatitude.add(lat);
mArrLongitude.add(longt);
mArrAddress.add(loc_addr);
mArrTime.add(currtime);
}
Log.d("Testing", "users det::  "+mArrLatitude.size());
Intent i = new Intent("carLocationService");
i.putStringArrayListExtra("lat",mArrLatitude);
i.putStringArrayListExtra("longi",mArrLongitude);
i.putStringArrayListExtra("time",mArrAddress);
i.putStringArrayListExtra("addr",mArrTime);
sendBroadcast(i);
}
}
catch (JSONException e)
{
Log.d("Testing", "JSOn Excep:::  "+e.toString());
//progressDialog.cancel();
}
Log.d("Testing", response.toString());
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Testing", "Volley Error:::  "+error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json");
params.put("user-key",Constants.m_spAhlan.getString("key",""));
return params;
}
};
AppController.getInstance().addToRequestQueue(jsonObjReq, "JSON_OBJECT_POST_REQUEST_TAG");
}

}

我想在下面的代码片段上写下逻辑:

if(response.length() == 0){
}

寻找答案。

谢谢,阿林丹。

有很多方法可以做到,但我为您提供使用EventBus库来处理服务和活动之间的事件:

首先在onStart((中的活动中注册EventBus,然后在onStop((中注销它:

class YourActivity : ActivityCompat() {
fun onStart() {
super.onStart()
EventBus.getDefault().register(this)
}
fun onStop() {
EventBus.getDefault().unregister(this)
super.onStop()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun onEvent(MessageEvent event) {
// show your popup dialog and implement your logics and stop your service
} }

然后在您的服务中,将您的信息发送到您想要的位置:

EventBus.getDefault().post(new MessageEvent());

希望是有用的。

最新更新