android - 使用bindService启动IntentService时是否应该调用onHandleIntent?

标签 android intentservice

我的服务扩展了 IntentService,当它用 startService 启动时,onHandleIntent 被调用。但是,当使用 bindService 启动服务时(我确实需要绑定(bind)),onHandleIntent 不会被调用。

IntentServicebindService启动时,是否应该调用onHandleIntentstartServiceIntentService 应该启动的唯一方式吗?

IntentService 的文档说明如下:

客户端通过 startService(Intent) 调用发送请求;服务根据需要启动,使用工作线程依次处理每个 Intent,并在用完工作时自行停止。

目前,我通过在 bindService 之后立即调用 startService 来解决我的问题,但我发现它很难看。我想知道有没有办法让它只需要一个电话就可以工作。

后面是代码 fragment ,可能是我遗漏了一些明显的东西。

ExampleService.java

public class ExampleService extends IntentService {

private class IncomingHandler extends Handler {

    @Override
    public void handleMessage(Message message) {

        if (message.replyTo != null) {
            outMessenger = message.replyTo;
        }
    }
}

private Messenger messenger = new Messenger(new IncomingHandler()); 
private Messenger outMessenger = null;


public ExampleService() {
    super("ExampleService");
}

@Override
public IBinder onBind(Intent intent) {
    return messenger.getBinder();
}

@Override
protected void onHandleIntent(Intent arg0) {

    System.out.println("Service started");

    for (int i = 0; i < 5; i++) {

        SystemClock.sleep(5000);

        if (outMessenger != null) {
            try {
                outMessenger.send(Message.obtain());
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
}

服务 list .xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="3"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <service android:name=".ExampleService">
        <intent-filter>
            <action android:name="com.example.service.ExampleService" />
        </intent-filter>
    </service>
</application>
</manifest>

MainActivity.java(调用者)

public class MainActivity extends Activity implements ServiceConnection {


private class IncomingHandler extends Handler {

    @Override
    public void handleMessage(Message msg) {

        Toast.makeText(getApplicationContext(), "Message received", Toast.LENGTH_SHORT).show();
        System.out.println("Message received!");
        super.handleMessage(msg);
    }
}

private Messenger messenger = new Messenger(new IncomingHandler());

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            Intent intent = new Intent("com.example.service.ExampleService");
            bindService(intent, MainActivity.this, Context.BIND_AUTO_CREATE);
            //startService(intent);
        }
    });

}

@Override
public void onServiceConnected(ComponentName name, IBinder binder) {

    Message message = Message.obtain();
    message.replyTo = messenger;

    try {
        new Messenger(binder).send(message);
    } catch (RemoteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

@Override
public void onServiceDisconnected(ComponentName name) {
    // TODO Auto-generated method stub
}
}

最佳答案

Should onHandleIntent be called when IntentService is started with bindService?

没有。

Is startService the only way IntentService should be started?

恕我直言,是的。恕我直言,IntentService 不是为绑定(bind)模式设计的。

在您的情况下,您可以:

  • 通过 startService() 发送的命令中的 Intent extra 中的 Activity 传递 Messenger,或者
  • 使用LocalBroadcastManager,或者
  • 使用Otto , 或
  • 使用有序广播,如果 IntentService 可能会在 Activity 的生命周期结束后继续,并且您希望在这种情况下工作完成时显示 Notification
  • 等等

关于android - 使用bindService启动IntentService时是否应该调用onHandleIntent?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12498919/

相关文章:

android - 在其他应用程序编写的服务中获取任何应用程序的前台 Activity

android - 允许其他应用程序从我的应用程序中选择图像,例如图库

php - 我如何将 session 电子邮件发送给 php?

java - 返回值的可运行替代方案

android - IntetentService 中的 NetworkOnMainThreadException

android - IntentService 中的数据变化

android - 如果我的 Intent 服务会被破坏

android - 加载数据后隐藏 ProgressDialog

android - 如何使用 Rxjava 进行长时间运行的后台任务

java - 如何使条码扫描仪只扫描一次(Google Mobile Vision API)?