0

我有一个名为BroadcastReceiverStartService,它在手机启动时启动,然后启动服务,但是当我从这个BroadcastReceiver去服务时, 我得到了异常:

android.content.ReceiverCallNotAllowedException: IntentReceiver 组件不允许绑定到服务

我的代码如下:

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;

public class StartService extends BroadcastReceiver {
        private RemoteServiceConnection conn = null;
        private IMyRemoteService remoteService;
        @Override
        public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        Intent startServiceIntent = new Intent(context, RemoteServiceClient.class);
                                    context.startService(startServiceIntent);
                                    conn = new RemoteServiceConnection();


                                        Intent i = new Intent();
                                        i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
                                        context.bindService(i, conn, Context.BIND_AUTO_CREATE);
                                }

                                class RemoteServiceConnection implements ServiceConnection {
                                    public void onServiceConnected(ComponentName className, 
                                        IBinder boundService ) {
                                      remoteService = IMyRemoteService.Stub.asInterface((IBinder)boundService);
                                      Log.d( getClass().getSimpleName(), "onServiceConnected()" );
                                    }

                                    public void onServiceDisconnected(ComponentName className) {
                                      remoteService = null;
                                       Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
                                    }
                                };
                            }
4

1 回答 1

0

一些步骤如下。

步骤1:

public class StartService extends BroadcastReceiver
        {  
            @Override
            public void onReceive(Context context, Intent intent) {
                Intent startServiceIntent = new Intent(context, myServices.class);
                context.startService(startServiceIntent);           
            }    
        } 

第2步:

// make all service related task

第 3 步:

<service
            android:name=".myServices"
            android:enabled="true" />
        <receiver android:name="com.yourpackage.StartService " >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

我总是以这种方式使用 BroadcastReceiver 和服务。

可能对您有帮助。如果有帮助,请接受答案。

于 2013-03-28T10:16:16.647 回答