gpt4 book ai didi

android - 在 Android 中启动服务

转载 作者:IT老高 更新时间:2023-10-28 13:02:21 25 4
gpt4 key购买 nike

我想在某个 Activity 开始时调用服务。所以,这里是 Service 类:

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);

问题是什么都没有发生。上面的代码块在activity的onCreate结束时被调用。我已经调试过了,没有抛出异常。

有什么想法吗?

最佳答案

您的 list 中可能没有该服务,或者它没有 <intent-filter>符合你的行动。检查 LogCat(通过 adb logcat、DDMS 或 Eclipse 中的 DDMS 透视图)应该会出现一些可能有帮助的警告。

更有可能,您应该通过以下方式启动服务:

startService(new Intent(this, UpdaterServiceManager.class));

关于android - 在 Android 中启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4765517/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com