我的服务类没有在后台运行我已经按照示例教程,不是什么问题以及为什么它没有运行?
这是我的服务类
public class Services extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d("OnBind", "OnBind");
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
Log.d("OnCreate", "OnCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d("OnStart", "OnStart");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
我的宣言
<service
android:name=".Services"
android:enabled="true" >
</service>
调用服务的MyActivity
startService(new Intent(getApplicationContext(), Services.class));
请查看我的编码,并帮助我正确运行应用程序,
先谢谢。
答案 0 :(得分:2)
通过在清单文件中提供com.example.Services
而不是.Services
等服务类的全名来进行检查。
要继续运行服务,请执行以下操作:
public class YourServiceName extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent i, int startId) {
this.test.run();
this.stopSelf();
}
public Runnable test= new Runnable() {
public void run() {
// Do something
}
};
}
启动它的AlarmManager:
Intent testService = new Intent(this, YourServiceName .class);
PendingIntent pitestService = PendingIntent.getService(this, 0,testService,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pitestService);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pitestService);
希望这有帮助。