我在Professional Android 4 Application Development一书中读到:“对startService的调用不会嵌套,因此对stopService的一次调用将终止它匹配的正在运行的服务,无论startService被调用了多少次。”
这是否意味着如果我启动两个相同类型的单独服务,它会在调用 stopService 时终止?还是它首先找到就停止?
我创建了一个 IntentService,它创建了一个在特定时间响起的警报。可以在警报响起之前将其删除。我怎样才能找到正确的服务,以阻止它?
public class AlarmService extends IntentService {
public static final String CREATE = "CREATE";
public static final String CANCEL = "CANCEL";
private IntentFilter matcher;
public AlarmService() {
super("ctor AlarmService");
matcher = new IntentFilter();
matcher.addAction(CREATE);
matcher.addAction(CANCEL);
}
@Override
protected void onHandleIntent(Intent intent) {
String action = intent.getAction();
String notificationId = intent.getStringExtra("notificationId");
if (matcher.matchAction(action)) {
execute(action, notificationId);
}
}
private void execute(String action, String notificationId) {
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Cursor c = getContentResolver().query(ReminderContentProvider.CONTENT_URI, null, "_id = ?", new String[]{notificationId}, null);
if (c.moveToFirst()) {
if(c.getString(c.getColumnIndex(ReminderColumns.ADDRESS)) == null)
{
Intent i = new Intent(this, AlarmReceiver.class);
i.putExtra("id", c.getLong(c.getColumnIndex(ReminderColumns._ID)));
i.putExtra("msg", c.getString(c.getColumnIndex(ReminderColumns.TITLE)));
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i,
PendingIntent.FLAG_UPDATE_CURRENT);
long time = c.getLong(c.getColumnIndex(ReminderColumns.DATE));
if (CREATE.equals(action)) {
am.set(AlarmManager.RTC_WAKEUP, time, pi);
} else if (CANCEL.equals(action)) {
am.cancel(pi);
}
}
}
c.close();
}
}
主要活动
Intent intent = new Intent(MainActivity.this, AlarmService.class);
intent.setAction(AlarmService.CREATE);
intent.putExtra("notificationId", idStr);
startService(intent);