我尝试从服务的类启动一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
mre*_*elt 10
当然 - 您新创建的服务没有对上下文的引用,因此上下文是null因此系统会抛出一个NullPointerException.请记住:不要使用自己创建服务new- 系统会为您执行此操作!
| 归档时间: |
|
| 查看次数: |
14184 次 |
| 最近记录: |