【问题标题】:How to dismiss progress dialog from service?如何从服务中关闭进度对话框?
【发布时间】:2019-10-18 11:39:38
【问题描述】:

我有一个活动,当用户开始下载时它会显示进度对话框 并在服务中从 ftp 开始下载

我想在服务完成下载文件后关闭此进度对话框

如何将其从服务中解雇?

【问题讨论】:

    标签: android service dialog


    【解决方案1】:

    更好的方法是使用 LocalBroadcastManagerService 通知Activity

    第 1 步:从您的服务发送本地广播

    public class MyService extends Service {
    
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
    
          // do your operation here(create worker thread for blocking operations)
    
          sendLocalBroadCast() //call this method as soon as above operations completes
          return Service.START_NOT_STICKY;
      }
    } 
    
      private void sendLocalBroadCast() {  
    
      Intent intent = new Intent("MY_SERVICE_NOTIFICATION");
      LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    
    }
    

    请注意,系统会在您的服务的主线程上调用 onStartCommand(Intent intent, int flags, int startId)。一种 服务的主线程与 UI 操作使用的线程相同 在同一进程中运行的活动的位置。你应该永远 避免停止主线程的事件循环。长跑时 操作、网络调用或繁重的磁盘 I/O,您应该启动一个 新线程,或者使用 AsyncTask

    第 2 步:让您的 Activity 收听此广播

        public class MyActivity extends Activity{
    
             BroadcastReceiver mReceiver = new BroadcastReceiver() {
    
              @Override
              public void onReceive(Context context, Intent intent) {
    
               // you can dismiss your progress dialog here. This method will be called when we receive broadcast from service after the service operation is completed
    
              }
            }
    
            @Override
            public void onCreate(Bundle savedInstanceState) {
    
            //register for listening to "MY_SERVICE_NOTIFICATION" event 
    
    
              LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
                  new IntentFilter("MY_SERVICE_NOTIFICATION"));
            }
    
            @Override
            protected void onDestroy() {
              super.onDestroy();
    
           // remove the receiver   
            LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
            }
        }
    

    【讨论】:

    • 好,但是如何触发事件取消mainactivity中的进度对话框?
    • @user12227210 只需使用您的 ProgressDialog 实例并调用 dismiss() 即可。
    • 什么是 MyReceiver?
    • 我无法定义 MyReceirver
    • @user12227210 我已经进行了更改,现在应该可以正常工作了
    【解决方案2】:

    创建一个具有listen方法的接口finishListener,在activity中实现它来做任何你想做的事情,然后从那里调用listen方法将它传递给服务构造函数

    【讨论】:

      【解决方案3】:

      很简单

       alertdialog.dismiss();
      

      只需将其放在安装代码的底部

      【讨论】:

        猜你喜欢
        • 2016-07-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多