Android - 绑定到服务

发布于 2024-10-19 18:30:53 字数 2585 浏览 6 评论 0原文

您好:我似乎无法将活动绑定到同一包中的服务。

该活动如下所示:

public class myApp extends TabActivity {
    static private String TAG = "myApp";
    private myService mService = null;
    private ServiceConnection mServiceConn = new ServiceConnection(){
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v(TAG, "Service: " + name + " connected");
            mService = ((myService.myBinder)service).getService();
        }

        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "Service: " + name + " disconnected");
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        doBind();
        Log.i(TAG, "Started (UI Thread)");

        // set content
        setContentView(R.layout.main);

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost

        ... add some tabs here....

        tabHost.setCurrentTab(0);
    }

    private void doBind(){      
        Intent i = new Intent(this,myService.class);
        if( bindService(i, mServiceConn, 0 )){
            Log.i(TAG, "Service bound");
        } else {
            Log.e(TAG, "Service not bound");
        }
    }

}

然后服务:

public class myService extends Service {
    private String TAG = "myService";

    private boolean mRunning = false;

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        Log.i(TAG,"Service start");

        mRunning = true;

        Log.d(TAG,"Finished onStartCommand");
        return START_STICKY;
    }

    /*
     * Called on service stop
     */
    @Override
    public void onDestroy(){
        Log.i(TAG,"onDestroy");
        mRunning = false;
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    boolean isRunning() {
        return mRunning;
    }

    /*
     * class for binding
     */
    private final IBinder mBinder = new myBinder();
    public class myBinder extends Binder {
        myService getService() {
            return myService.this;
        }
    }
}

bindService 返回 true,但 onServiceConnection 从未被调用(mService 始终为 null,因此我无法执行 mService.isRunning() 之类的操作)

该服务的清单条目只是:

<service android:name=".myService"></service>

我是直接从 Android 开发者网站复制代码,但我一定错过了一些东西。

Hi: I can't seem to get an activity to bind to a service in the same package.

The activity looks like this:

public class myApp extends TabActivity {
    static private String TAG = "myApp";
    private myService mService = null;
    private ServiceConnection mServiceConn = new ServiceConnection(){
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.v(TAG, "Service: " + name + " connected");
            mService = ((myService.myBinder)service).getService();
        }

        public void onServiceDisconnected(ComponentName name) {
            Log.v(TAG, "Service: " + name + " disconnected");
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        doBind();
        Log.i(TAG, "Started (UI Thread)");

        // set content
        setContentView(R.layout.main);

        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost();  // The activity TabHost

        ... add some tabs here....

        tabHost.setCurrentTab(0);
    }

    private void doBind(){      
        Intent i = new Intent(this,myService.class);
        if( bindService(i, mServiceConn, 0 )){
            Log.i(TAG, "Service bound");
        } else {
            Log.e(TAG, "Service not bound");
        }
    }

}

Then the service:

public class myService extends Service {
    private String TAG = "myService";

    private boolean mRunning = false;

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        Log.i(TAG,"Service start");

        mRunning = true;

        Log.d(TAG,"Finished onStartCommand");
        return START_STICKY;
    }

    /*
     * Called on service stop
     */
    @Override
    public void onDestroy(){
        Log.i(TAG,"onDestroy");
        mRunning = false;
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }


    boolean isRunning() {
        return mRunning;
    }

    /*
     * class for binding
     */
    private final IBinder mBinder = new myBinder();
    public class myBinder extends Binder {
        myService getService() {
            return myService.this;
        }
    }
}

bindService returns true, but onServiceConnection is never called (mService is always null, so I can't do something like mService.isRunning() )

The manifest entry for the service is just:

<service android:name=".myService"></service>

I was copying the code direct from the Android developers site, but I must have missed something.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜血缘 2024-10-26 18:30:53

一个已知问题是,作为选项卡活动(在选项卡主机中运行)中的子活动启动的活动无法绑定到服务,即使在同一包中也是如此。有一个“黑客”解决方法。如果你打电话:

 getApplicationContext().bindService(Intent, connection, flags);

而不仅仅是:

 bindService(Intent, connection, flags);

一切都会正常。遇到了同样的问题,在此错误报告中找到了详细信息:
http://code.google.com/p/android/issues/detail ?id=2483

it's a known issue that activities started as a subactivity in a tabactivity (running in the tabhost) cannot bind to services, even in the same package. there is a "hack" workaround. if you call:

 getApplicationContext().bindService(Intent, connection, flags);

rather than just:

 bindService(Intent, connection, flags);

everything will work. had this same problem, found the details in this bug report:
http://code.google.com/p/android/issues/detail?id=2483

听风吹 2024-10-26 18:30:53

您的服务从未启动。启动服务
startService(bindIntent)

请参阅类似的代码:

Intent bindIntent = new Intent(this,ServiceTask.class);
if (ServiceTools.isServiceRunning() == false){
    Log.d(Global.TAG,"-->service will be started.");
    startService(bindIntent);
}else{
    Log.d(Global.TAG,"-->service already is running");
}
boolean bound = bindService(bindIntent,mConnection,0);

您还可以在使用 BIND_AUTO_CREATE 而不是 0 绑定时自动启动服务。

如果您只希望服务启动一次,这里也是 ServiceTools 类。否则,您可能会获得多个正在运行的服务实例,并且每次 onCreate() / doBind() 时在 onServiceConnected 中调用的方法都会一成不变。

public class ServiceTools {
    public static boolean isServiceRunning(){
        final ActivityManager activityManager = (ActivityManager)Global.gContext.getSystemService(Global.gContext.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        boolean isServiceFound = false;

        for (int i = 0; i < services.size(); i++) {
            //Log.d(Global.TAG, "Service" + i + " :" + services.get(i).service);
            //Log.d(Global.TAG, "Service" + i + " package name : " + services.get(i).service.getPackageName());
            //Log.d(Global.TAG, "Service" + i + " class name : " + services.get(i).service.getClassName());

            if ("com.atClass.lmt".equals(services.get(i).service.getPackageName())){
                if ("com.atClass.lmt.ServiceTask".equals(services.get(i).service.getClassName())){
                    isServiceFound = true;
                }
            }
        }
        return isServiceFound;
     }
}

Your service is never started. Start the service with
startService(bindIntent)

See this similar code:

Intent bindIntent = new Intent(this,ServiceTask.class);
if (ServiceTools.isServiceRunning() == false){
    Log.d(Global.TAG,"-->service will be started.");
    startService(bindIntent);
}else{
    Log.d(Global.TAG,"-->service already is running");
}
boolean bound = bindService(bindIntent,mConnection,0);

You could also start the service automatically when binding with BIND_AUTO_CREATE instead of 0.

Here is the ServiceTools class also if you only want your service to be started once. Otherwise you may get more than one running instance of your service and methods called in onServiceConnected will be rut every time onCreate() / doBind() are.

public class ServiceTools {
    public static boolean isServiceRunning(){
        final ActivityManager activityManager = (ActivityManager)Global.gContext.getSystemService(Global.gContext.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        boolean isServiceFound = false;

        for (int i = 0; i < services.size(); i++) {
            //Log.d(Global.TAG, "Service" + i + " :" + services.get(i).service);
            //Log.d(Global.TAG, "Service" + i + " package name : " + services.get(i).service.getPackageName());
            //Log.d(Global.TAG, "Service" + i + " class name : " + services.get(i).service.getClassName());

            if ("com.atClass.lmt".equals(services.get(i).service.getPackageName())){
                if ("com.atClass.lmt.ServiceTask".equals(services.get(i).service.getClassName())){
                    isServiceFound = true;
                }
            }
        }
        return isServiceFound;
     }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文