在Android的启动服务 [英] Start service in Android
问题描述
我想有一定的活动启动时调用服务。所以,这里的服务类:
I want to call a service when a certain activity starts. So, here's the Service class:
public class UpdaterServiceManager extends Service {
private final int UPDATE_INTERVAL = 60 * 1000;
private Timer timer = new Timer();
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;
public UpdaterServiceManager() {}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// Code to execute when the service is first created
}
@Override
public void onDestroy() {
if (timer != null) {
timer.cancel();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startid) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
int icon = android.R.drawable.stat_notify_sync;
CharSequence tickerText = "Hello";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = "My notification";
CharSequence contentText = "Hello World!";
Intent notificationIntent = new Intent(this, Main.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
notificationManager.notify(NOTIFICATION_EX, notification);
Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
// Check if there are updates here and notify if true
}
}, 0, UPDATE_INTERVAL);
return START_STICKY;
}
private void stopService() {
if (timer != null) timer.cancel();
}
}
这就是我把它叫做:
Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);
问题是,什么也不会发生。上述code块被称为在结束活动的的onCreate
。我已经调试,并不会引发任何异常。
The problem is that nothing happens. The above code block is called at the end of the activity's onCreate
. I already debugged and no exception is thrown.
你知道吗?
推荐答案
也许你没有服务在你的清单,也没有一个<意向滤光器>
相匹配的行动。检查LogCat中(通过亚行logcat
,DDMS或DDMS透视图在Eclipse)应该把一些警告可能会有帮助。
Probably you don't have the service in your manifest, or it does not have an <intent-filter>
that matches your action. Examining LogCat (via adb logcat
, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.
更有可能的是,你应该通过启动服务:
More likely, you should start the service via:
startService(new Intent(this, UpdaterServiceManager.class));
这篇关于在Android的启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!