我正在尝试使用主要活动(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();
}
}
由于
答案 0 :(得分:0)
根据评论,这是一个新的(编辑过的)答案......
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
包并将服务代码文件放在其中。