首页 > 解决方案 > 如何在服务类的活动中显示对话框?

问题描述

我有一个正在运行的服务,它将每 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){
}

寻找答案。

谢谢,阿林丹。

标签: androidandroid-activityserviceandroid-alertdialog

解决方案


有很多方法可以做,但我建议您使用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());

希望有用。


推荐阅读