eclipse 在 bindService() 之后没有创建(或连接)服务

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10581827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 18:10:24  来源:igfitidea点击:

Service not being created (or connecting) after bindService()

javaandroideclipseandroid-service

提问by bughi

I have this simple service that broadcasts the current location of the user. I want to use the binding mechanism just to control the service life-cycle, but the service is just not starting.

我有这个简单的服务,可以广播用户的当前位置。我想使用绑定机制来控制服务生命周期,但服务只是没有启动。

What did I do wrong?

我做错了什么?

public class GPSActivity extends ListActivity {
...
protected void onResume() {
        super.onResume();

        Log.i("Service", "Service bound");
        Intent intent = new Intent(this, LocationService.class);
        bindService(intent, service_connection , Context.BIND_AUTO_CREATE);
    }

protected void onPause() {
        if (dataUpdateReceiver!=null)
            unregisterReceiver(dataUpdateReceiver);
        unbindService(service_connection);
        super.onPause();
    }
class LocationServiceConnection implements ServiceConnection{
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("Service", "Service Connected");
        }
                public void onServiceDisconnected(ComponentName name) {

        }
    }
}

LocalBinder.java

LocalBinder.java

public class LocalBinder<S> extends Binder {
    private String TAG = "LocalBinder";
    private  WeakReference<S> mService;


    public LocalBinder(S service){
        mService = new WeakReference<S>(service);
    }


    public S getService() {
        return mService.get();
    }
}

LocationService.java

LocationService.java

public class LocationService extends Service {
    public void onCreate() {
        initLocationListener();
        Log.i("Location Service","onCreate()");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Location Service", "Received start id " + startId + ": " + intent);
        return START_NOT_STICKY;
    }

    private final IBinder mBinder = new LocalBinder<LocationService>(this);
    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

AndroidManifest.xml

AndroidManifest.xml

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    ...

    <service android:name=".LocationService">
    </service>
</application>  

EDIT:Fixed thanks to NickT's answer.

编辑:由于 NickT 的回答而修复。

The manifest entry did not have a intent filter or the correct name

清单条目没有意图过滤器或正确的名称

<service
   android:enabled="true"
   android:name="com.android.gps.services.LocationService">
   <intent-filter>
          <action android:name="com.android.gps.services.LocationService" />
   </intent-filter>
</service>

And the intent I used for binding was like the ones you need to use when starting an activity. the correct one is:

我用于绑定的 Intent 就像您在启动 Activity 时需要使用的 Intent。正确的是:

Intent intent = new Intent("com.android.gps.services.LocationService");

采纳答案by NickT

The onStartCommand will only execute if the service is explicitly started, it looks like you are just wanting to bind to it, which is fine. I don't see that you have set up the service connection properly though. I'm posting my stub program which shows how to bind to a service and call a method in the service through a binder. You may like to run this and see the sequence of the various log messages. You will obviously need to add your BroadcastReceiver and onLocationChaged code to make it useful for you.

onStartCommand 只会在服务显式启动时执行,看起来您只是想绑定到它,这很好。不过,我没有看到您已正确设置服务连接。我正在发布我的存根程序,该程序展示了如何绑定到服务并通过绑定器调用服务中的方法。您可能希望运行它并查看各种日志消息的顺序。您显然需要添加 BroadcastReceiver 和 onLocationChaged 代码以使其对您有用。

The Activity

活动

package com.servtest.test;

import com.servtest.test.LocationService.LocalBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class ServiceTestActivity extends Activity {

    boolean mServiceConnected = false;
    boolean mBound = false;
    private LocationService mLocnServ;

    ServiceConnection mServconn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d("SVTEST", "Activity service connected");
            LocalBinder binder = (LocalBinder) service;
            mLocnServ = binder.getService();
            // Can't call this methodInTheService UNTIL IT'S BOUND!
            mLocnServ.methodInTheService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d("SVTEST", "Activity service disconnected");
            mBound = false;
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    @Override
    public void onStart() {
        super.onStart();
        Log.d("SVTEST", "Activity onStart");
        mServiceConnected = bindService(new Intent(
                "com.servtest.test.LOCATIONSERVICE"), mServconn,
                Context.BIND_AUTO_CREATE);
    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.d("SVTEST", "Activity onResume");
    }
    @Override
    public void onPause() {
        Log.d("SVTEST", "Activity onPause");
        super.onPause();
    }
    @Override
    public void onStop() {
        Log.d("SVTEST", "Activity onStop");
        if (mBound) {
            unbindService(mServconn);
            mBound = false;
        }
        super.onStop();
    }

}

The Service

服务

package com.servtest.test;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

public class LocationService extends Service implements LocationListener {

    private final IBinder mBinder = new LocalBinder();

    @Override
    public void onLocationChanged(Location arg0) {}
    @Override
    public void onProviderDisabled(String arg0) {}
    @Override
    public void onProviderEnabled(String arg0) {}
    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}

    @Override
    public IBinder onBind(Intent intent) {
        Log.d("SVTEST", "Loc service ONBIND");
        return mBinder;
    }
    @Override
    public boolean onUnbind(Intent intent) {
        Log.d("SVTEST", "Loc service ONUNBIND");
        return super.onUnbind(intent);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // Won't run unless it's EXPLICITLY STARTED
        Log.d("SVTEST", "Loc service ONSTARTCOMMAND");
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("SVTEST", "Loc service ONDESTROY");
    }

    public class LocalBinder extends Binder {
        LocationService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocationService.this;
        }
    }

    public void methodInTheService() {
        // A method you can call in the service
        Log.d("SVTEST", "Loc service EXECUTING THE METHOD");
    }
}

The Manifest

清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.servtest.test"
    android:versionCode="1"
    android:versionName="1.0" >
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:enabled="true"
            android:name="LocationService">
            <intent-filter>
                <action android:name="com.servtest.test.LOCATIONSERVICE" />
            </intent-filter>
        </service>
    </application>
</manifest>

Hope this helps

希望这可以帮助

回答by HChen

When you call bindServiceyou may get this error:

当您打电话时,bindService您可能会收到此错误:

ActivityManager java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.android.server.am.ActivityRecord$Token

ActivityManager java.lang.ClassCastException: android.os.BinderProxy cannot be cast to com.android.server.am.ActivityRecord$Token

Check the output of logcat.

检查 logcat 的输出。

This is a bug of Android.

这是安卓的一个bug。

To solve it, use getApplicationContext().bindService(...)

要解决它,请使用 getApplicationContext().bindService(...)

回答by ScouseChris

I had my Activityimplement ServiceConnectionand bound like this:

我有我的Activity工具ServiceConnection并像这样绑定:

bindService( new Intent( this, Service.class ), this, Context.BIND_AUTO_CREATE );

Then handled the callbacks for onServiceConnected()and onServiceDisconnected()in my Activity

然后处理的回调onServiceConnected()onServiceDisconnected()Activity