我正在尝试在我的主要活动(Home.java)中使用警报管理器启动服务(NotificationService.java)。我在执行AlarmManager的setInexactRepeating后放了一个日志,它显示成功执行了setInexactRepeating,但服务从未启动。
下面是启动服务的代码: public void startService(Context context){
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(Home.this, NotificationService.class);
int minutes = 1 ;
PendingIntent pi = PendingIntent.getService(Home.this, 0, i, 0);
am.cancel(pi);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
System.currentTimeMillis(),
minutes*60*1000, pi);
Log.e("Service Started","Halilujia");
}
清单中的声明如下:
<service
android:name=".services.NotificationService"
android:enabled="true">
</service>
public class NotificationService extends Service {
private WakeLock mWakeLock;
private Context activity = getApplicationContext();
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void handleIntent(Intent intent) {
// obtain the wake lock
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DebuggingTag");
mWakeLock.acquire();
// check the global background data setting
ConnectivityManager cm = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
if (!cm.getBackgroundDataSetting()) {
stopSelf();
return;
}
Log.e("Just before request","Just before Request");
// send http request here and create notification
}
@Override
public void onStart(Intent intent, int startId) {
Log.e("Onstart Called","Onstart has been Called");
handleIntent(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Onstart Called","Onstart has been Called");
handleIntent(intent);
return START_NOT_STICKY;
}
public void onDestroy() {
super.onDestroy();
mWakeLock.release();
}
}
谢谢
根据评论,这是一个新的(编辑的)回答…
你方Service
的舱单声明是…
<service
android:name=".services.NotificationService"
android:enabled="true">
</service>
…它将NotificationService
声明为包含在一个名为services
的包中。例子…
主包为com.example.MyApp
,服务在com.example.MyApp.services
。
将服务的代码文件放在/src/services
中不会改变android:name
属性使用的包名/路径。
要解决这个问题,要么将声明更改为使用android:name=".NotificationService
,要么创建一个单独的com.example.MyApp.services
包,并将服务代码文件放在那里。