エラー:java.lang.IllegalArgumentException: Service not registered

28048 ワード

サービスのバインド解除小項目テストを行う場合、バインドは成功し、バインド解除も成功するが、バインド解除後にバインド解除命令(項目中はボタンをクリックしてバインドを解除する)をクリックすると、このエラーが報告される.
AndroidRuntime(7090): java.lang.IllegalArgumentException: Service not registered: 
com.m1910.servicetest.MainActivity$1@41ddfcc0

エラーはサービスが登録されていないことを示しています.実は私はManifestにいます.xmlにこのサービスが登録されています.変更前のコード:
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_service:
			Intent startIntent = new Intent(this, MyService.class);
			startService(startIntent);//     
			break;
		case R.id.stop_service:
			Intent stopIntent = new Intent(this, MyService.class);
			stopService(stopIntent);//     
			break;
		case R.id.bind_service:
			Intent bindIntent = new Intent(this, MyService.class);
                        //     
			bindService(bindIntent, connection, BIND_AUTO_CREATE);
			break;
		case R.id.unbind_service:
			unbindService(connection);//     	
			break;
		default:
			break;
		}
	}

unbindService()のこのメソッドについて、公式ドキュメントで説明します.
public abstract void unbindService (ServiceConnection conn)
 
Added in API level 1
Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.
 
Parameters
conn	The connection interface previously supplied to bindService(). This parameter must not be null.

最後の文はこの入ってきたconnパラメータがnullではないことを見て、つまりバインドが存在しなければならなくて、やっとバインドを解くことができて、小さいプロジェクトの中でバインドに成功した後に初めてクリックしてバインドを解いて間違いを報告することはできなくて、バインドを解いた後にこのパラメータはnullで、再びクリックしてバインドを解いて間違いを報告することができて、それでは私達はバインドを解いて1つの判断を加えることができます修正後のコードは次のとおりです.
private boolean isBound = false;
 
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.start_service:
			Intent startIntent = new Intent(this, MyService.class);
			startService(startIntent);//     
			break;
		case R.id.stop_service:
			Intent stopIntent = new Intent(this, MyService.class);
			stopService(stopIntent);//     
			break;
		case R.id.bind_service:
			Intent bindIntent = new Intent(this, MyService.class);
                        //     
			isBound = bindService(bindIntent, connection, BIND_AUTO_CREATE);
			break;
		case R.id.unbind_service:
			if (isBound) {
				unbindService(connection);//     
				isBound = false;
			}
			break;
		default:
			break;
		}
	}

ネット上ではgetApplicationContext()を使う人もいます.unbindService(mConnection);このようにして、どういう意味か私もよく分かりませんが、最終的な効果も同じように空かどうかの判断を加えなければなりません.