有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在安卓中创建队列?

        Uri uriSMSURI = Uri.parse("content://sms/inbox");
        Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
        int i=0;
        while (cur.moveToNext()) {
            Phone_no=cur.getString(2);
            Time=cur.getLong(4);
            Message_body=cur.getString(11);
            Date dateObj = new Date(Time);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
            String Timenew = df.format(dateObj);
            Log.d(Tag,"INSIDE OF READ SMS INBOX");


           service.setClass(getBaseContext(), Background_Service.class);
           service.putExtra("Phone_no", Phone_no);
           service.putExtra("Message_body", Message_body);
           service.putExtra("Timenew", Timenew);
           getBaseContext().startService(service);
           } 

上面的代码从收件箱中读取消息。我将这些消息发送给服务进行进一步处理。这样做对吗。我是否应该为服务执行创建队列,如果是,如何创建,实现上述代码的队列


共 (1) 个答案

  1. # 1 楼答案

    是的,这是一种适用的方式。 但是,我更喜欢另一个

    您可以创建一次服务并绑定到它,然后向它发送Message,而不是启动一个新服务并将新的意图路由到它

    首先,您需要一个消息传递协议。最简单的方法是创建具有类似内容的AIDL文件

    package org.your.pkg;
    
    interface IBackgroundService {
      void queueMsg(String phoneNo, String msgBody, String timeNew);
    }
    

    然后,您必须在您的服务中实现它

    class BackgroundService extends Service {
    
      IBackgroundService.Stub binder = new IBackgroundService.Stub() {
        public void queueMsg(String phoneNo, String msgBody, String timeNew) {
          // enqueue message to service thread. Do not process msg in this method.
        }
      };
    
      public IBinder getBinder() {
        return binder;
      }
    }
    

    然后,您必须连接到您的服务

    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            IBackgroundService yourService = IBackgroundService.Stub.asInterface(service);
    
            // calls to yourService.queueMsg(...)
        }
    
        public void onServiceDisconnected(ComponentName className) {
            Log.e(TAG, "Service has unexpectedly disconnected");
        }
    };
    

    还有更多关于this主题的内容