1
        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);
           } 

上記のコードは、受信トレイからメッセージを読み取ります。そして、これらのメッセージをサービスに送信して、さらに処理します。これは正しい方法ですか。サービス実行用のキューを作成する必要がある場合、作成する方法は、上記のコードにキューを実装します。

4

1 に答える 1

4

はい、適用方法です。しかし、私は別のものを好む。

新しいサービスを開始して新しいインテントをルーティングする代わりに、サービスを一度作成してバインドし、それにMessages を送信できます。

まず、メッセージング プロトコルが必要です。最も簡単な方法は、同様の内容で 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");
    }
};

このトピックについては他にもあります。

于 2012-08-01T14:23:27.103 に答える