小编vit*_*1.6的帖子

来自服务类本身的startService()

我尝试从服务的类启动一个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, …
Run Code Online (Sandbox Code Playgroud)

android

6
推荐指数
1
解决办法
1万
查看次数

标签 统计

android ×1