gpt4 book ai didi

android - 来自服务类本身的 startService()

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:59:06 25 4
gpt4 key购买 nike

我尝试从服务类启动 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 自行创建服务 - 系统会为您完成!

关于android - 来自服务类本身的 startService(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3888602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com