如何在android中使用Service

时间:2014-07-12 13:29:18

标签: android service

我是android的新手。我想使用一些后台进程。所以我决定使用服务。因此我制作一个简单的应用程序来学习使用。但app停止。 在清单中我定义了服务。  在日志猫展示中:

07-12 17:49:03.067:E / AndroidRuntime(3367):引起:java.lang.InstantiationException:无法实例化类com.example.servicetest.service;没有空构造函数

public class MainActivity extends Activity {
private Button b;
private TextView tv;
private BroadcastReceiver br=new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // TODO Auto-generated method stub
        tv.setText(arg1.getExtras().getString("s").toString());
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b=(Button) findViewById(R.id.button1);  
    tv=(TextView) findViewById(R.id.textView1);     
    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            startService(new Intent(getApplicationContext(), service.class));
        }
    });
}

public class service extends IntentService {
public service(String name) {
    super(name);
    // TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stu
    intent.putExtra("s", "salam");
    sendBroadcast(intent);
    }
}

2 个答案:

答案 0 :(得分:1)

例外明确说明:no empty constructor

您应该为您的服务添加一个空构造函数。您应该将服务提取到一个单独的类中,并向其添加默认公共构造函数

public service() {
    super("MyService");
}

此外,您应在BroadcastReceiver注册onResume

registerReceiver(br,new IntentFilter("event"));

并在onPause中取消注册:

unregisterReceiver(br);

现在,您在onHandleIntent的服务中发送广播:

Intent send = new Intent("event");
send.putExtra("s", "salam");
sendBroadcast(send);

答案 1 :(得分:0)

任何Context后代(ActivityServiceApplication)胸围都会在其自己的文件中定义。 我不确定你是否可以将它定义为公共静态内部类,但无论如何它都是一种不好的做法。

因此,为了使其工作,将其提取到java文件,如service.java并在manifest

中定义它
<service android:name="com.example.servicetest.service"/>

不要使用android:procces attrubute ,除非您必须设计,因为它会增加太多的复杂性。

考虑到java约定,类名以大写字母开头。

此外,正如Andrei Catinean所提到的,您必须定义一个空构造函数。

public service() {
    super("Your service name");
}