我尝试从服务类启动 android 服务。
这样做的原因是为了实现一定的平台独立性。
这样做我在 android.content.ContextWrapper.startService(ContextWrapper.java:326) 处收到 NullPointerException。平台目标是2.1-update1,有什么建议吗?
请参阅下面的代码(我保留了导入以节省一些空间)
/* GUI: HelloAndroid.java */
package com.example.helloandroid;
public class HelloAndroid extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// that works!
startService(new Intent("com.example.helloandroid.UnusualService"));
// stop the service works of course, too
stopService(new Intent("com.example.helloandroid.UnusualService"));
// unusual start does not work:
UnusualService myService = new UnusualService();
myService.startService();
}
}
/* Service: UnusualService.java */
package com.example.helloandroid;
public class UnusualService extends Service {
@Override
public void onCreate() {
Toast.makeText(this, R.string.service_started, Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
Toast.makeText(this, R.string.service_stopped, Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return null; // make something here when the rest works
}
public void startService() {
// folowing line will cause the NullPointerException
startService(new Intent("com.example.helloandroid.UnusualService"));
}
public void stopService() {
stopSelf();
}
}
当然 - 您新创建的服务没有对上下文的引用,因此上下文是null
因此系统会抛出一个NullPointerException
。
请记住:不要使用以下方式自行创建服务new
- 系统会为您做这件事!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)