我想创建一个将在单独的线程(而不是 UI 线程)上运行的服务,所以我实现了一个扩展 IntentService 的类。但我没有运气。这是代码。
public class MyService extends IntentService {
public MyService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e("Service Example", "Service Started.. ");
// pushBackground();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e("Service Example", "Service Destroyed.. ");
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
for (long i = 0; i <= 1000000; i++) {
Log.e("Service Example", " " + i);
try {
Thread.sleep(700);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Activity 按钮中的服务消费点击:
public void onclick(View view) {
Intent svc = new Intent(this, MyService.class);
startService(svc);
}