我正在尝试在Android上启动服务,以便在后台执行一些与网络相关的任务。我为我的应用程序编写了一个基本的网络管理器,这是一项服务。我基本上使用了android文档中的教程。基本结构如下:
public class MyNetworkManager extends Service {
// some code
private final IBinder mBinder = (IBinder) new MyBinder();
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
MyNetworkManager getService() {
return MyNetworkManager.this;
}
}
public void onCreate() {
// some network related stuff like setting up sockets etc.
}
public void onStart(Intent intent, int startid) {
while(true) {
// receive new connections etc
}
}
然后调用app / activity:
public class AndroidNetworkManagerClient extends Activity {
private Button buttonSend;
private EditText inputText;
private TextView outputText;
private MyNetworkManager networkManager;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
networkManager = ((MyNetworkManager.MyBinder) binder).getService();
}
public void onServiceDisconnected(ComponentName className) {
networkManager = null;
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
inputText = (EditText) findViewById(R.id.textInput);
outputText = (TextView) findViewById(R.id.textOutput);
buttonSend = (Button)this.findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (inputText.getText().length() != 0) {
outputText.append("Out: " + inputText.getText() + "\n");
networkManager.sendData("localhost", inputText.getText().toString());
}
}
});
bindService(new Intent(this, MyNetworkManager.class), mConnection, Context.BIND_AUTO_CREATE);
doSomeAppRelatedStuff();
}
似乎没有任何问题地调用了bindService(),但变量“networkManager”始终为null!我已经尝试调试onCreate()方法或onServiceConnected(),但似乎根本没有到达这些部分(至少没有触发断点)。
该服务已在AndroidManifest.xml中注册:
package="some.random.name"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".AndroidNetworkManagerClient"
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:name=".MyNetworkManager"></service>
</application>
有人有想法吗?
答案 0 :(得分:1)
有可能,您的Activity
进入doSomeAppRelatedStuff()
并尝试在绑定完成之前使用networkManager
。
如果doSomeAppRelatedStuff()
绝对必须让网络管理员运行,请将您的呼叫转移到doSomeAppRelatedStuff()
进入onServiceConnected()
,这样在绑定完成之前它才会真正启动。请注意,如果您这样做,您的onStart()
和onResume()
调用可能会(但不能保证!)在绑定完成之前发生,因此请进行相应的编程。