Android服务的寿命

Android服务的寿命,android,service,Android,Service,我试图了解Android中服务的工作原理,并阅读绑定服务的Android文档: 对于以后的项目,我需要一个不断在后台运行的服务,并且可以通过应用程序与之交互。文档中指出,您还可以绑定到startService()启动的服务。然而,我有一些困难使它正常工作 服务很简单。它的唯一用途是提供一个计数器(我跳过了导入以避免不必要地弄乱代码): 我控制服务的活动包含两个按钮,一个用于获取随机数,另一个用于终止服务: package com.wursti.servicetest0r; import com

我试图了解Android中服务的工作原理,并阅读绑定服务的Android文档: 对于以后的项目,我需要一个不断在后台运行的服务,并且可以通过应用程序与之交互。文档中指出,您还可以绑定到startService()启动的服务。然而,我有一些困难使它正常工作

服务很简单。它的唯一用途是提供一个计数器(我跳过了导入以避免不必要地弄乱代码):

我控制服务的活动包含两个按钮,一个用于获取随机数,另一个用于终止服务:

package com.wursti.servicetest0r;

import com.wursti.servicetest0r.LocalService.LocalBinder;

public class MainActivity extends Activity {

LocalService mService;
boolean mBound = false;

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

@Override
protected void onStart(){
    super.onStart();
    // bind to local service
    if(!isServiceRunning())
        startService(new Intent(this,LocalService.class));
    else
        Toast.makeText(this, "Service is already running.", Toast.LENGTH_SHORT).show();

    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

private boolean isServiceRunning(){
    ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if(LocalService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

@Override
protected void onStop() {
    super.onStop();
    // unbind from the service
    if(mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}

public void onButtonClick(View v) {
    if(mBound) {
        int num = mService.getNumber();
        Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    }
}

public void onKillServiceClick(View v) {
    mBound = false; // <-- this line was edited because of a comment
    stopService(new Intent(this, LocalService.class));
    unbindService(mConnection);
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        // we've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0){
        mBound = false;
    }
};
}
老实说,我不知道如何从这里继续下去,非常感谢您的帮助:)

解除绑定服务(mConnection)

在onStop中,即使在您之前终止服务后也会调用

也许这就是错误所在


试着处理一下

您是否在AndroidManifest.xml中注册了LocalService?是的,我想如果不是这样,我甚至无法启动该服务?我在清单文件中也有这样的内容:android:enabled=“true”您可以尝试先交换unbindService,然后再交换stopService()@ganathy:我已经切换了语句(在onKillServiceClick()中),但结果是一样的:[unbindService(mConnection);在您之前终止服务后仍会调用onStop。可能就是这个错误。请尝试处理它。这解决了关闭应用程序时出现崩溃的部分!谢谢。我选择此作为答案,因为它解决了一半的问题。感谢您的努力。
package com.wursti.servicetest0r;

import com.wursti.servicetest0r.LocalService.LocalBinder;

public class MainActivity extends Activity {

LocalService mService;
boolean mBound = false;

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

@Override
protected void onStart(){
    super.onStart();
    // bind to local service
    if(!isServiceRunning())
        startService(new Intent(this,LocalService.class));
    else
        Toast.makeText(this, "Service is already running.", Toast.LENGTH_SHORT).show();

    Intent intent = new Intent(this, LocalService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}

private boolean isServiceRunning(){
    ActivityManager manager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
    for(RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if(LocalService.class.getName().equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

@Override
protected void onStop() {
    super.onStop();
    // unbind from the service
    if(mBound) {
        unbindService(mConnection);
        mBound = false;
    }
}

public void onButtonClick(View v) {
    if(mBound) {
        int num = mService.getNumber();
        Toast.makeText(this, "number: " + num, Toast.LENGTH_SHORT).show();
    }
}

public void onKillServiceClick(View v) {
    mBound = false; // <-- this line was edited because of a comment
    stopService(new Intent(this, LocalService.class));
    unbindService(mConnection);
}

/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName className, IBinder service) {
        // we've bound to LocalService, cast the IBinder and get LocalService instance
        LocalBinder binder = (LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0){
        mBound = false;
    }
};
}
07-05 10:44:21.964: E/AndroidRuntime(792): java.lang.RuntimeException: Unable to stop activity {com.wursti.servicetest0r/com.wursti.servicetest0r.MainActivity}: java.lang.IllegalArgumentException: Service not registered: com.wursti.servicetest0r.MainActivity$1@40e81200
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3415)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:3469)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread.access$1200(ActivityThread.java:141)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1287)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.os.Looper.loop(Looper.java:137)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-05 10:44:21.964: E/AndroidRuntime(792):  at java.lang.reflect.Method.invokeNative(Native Method)
07-05 10:44:21.964: E/AndroidRuntime(792):  at java.lang.reflect.Method.invoke(Method.java:511)
07-05 10:44:21.964: E/AndroidRuntime(792):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-05 10:44:21.964: E/AndroidRuntime(792):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-05 10:44:21.964: E/AndroidRuntime(792):  at dalvik.system.NativeStart.main(Native Method)
07-05 10:44:21.964: E/AndroidRuntime(792): Caused by: java.lang.IllegalArgumentException: Service not registered: com.wursti.servicetest0r.MainActivity$1@40e81200
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:921)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ContextImpl.unbindService(ContextImpl.java:1451)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.content.ContextWrapper.unbindService(ContextWrapper.java:484)
07-05 10:44:21.964: E/AndroidRuntime(792):  at com.wursti.servicetest0r.MainActivity.onStop(MainActivity.java:61)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1205)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.Activity.performStop(Activity.java:5246)
07-05 10:44:21.964: E/AndroidRuntime(792):  at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:3410)
07-05 10:44:21.964: E/AndroidRuntime(792):  ... 11 more