我有一个意图服务,每天与服务器连接一次,并且工作正常,就像在android教程中的例子。因为它只是每天轮询服务器一次,所以我有疑问。 如果服务尝试连接服务器并且用户不在线会发生什么情况? 我想念那一天,或者有一种方法可以在运行时重新安排闹钟,并尝试在用户在线时进行连接?Android- Reschelude闹钟
这里是我的代码: OBS:我叫setAlarm(上下文)在我的发射活动
public class SampleBootReceiver extends BroadcastReceiver {
SampleAlarmReceiver alarm = new SampleAlarmReceiver();
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
alarm.setAlarm(context);
}
}
}
public class SampleAlarmReceiver extends WakefulBroadcastReceiver {
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, SampleSchedulingService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context) {
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, SampleAlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
alarmMgr.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime()+60*1000, AlarmManager.INTERVAL_DAY , alarmIntent);
ComponentName receiver = new ComponentName(context, SampleBootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
public class SampleSchedulingService extends IntentService {
public boolean serviceGetNews;
public SampleSchedulingService() {
super("SchedulingService");
}
@Override
public void onCreate() {
super.onCreate();
}
public static final int NOTIFICATION_ID = 1;
public static NotificationManager mNotificationManager;
@Override
protected void onHandleIntent(Intent intent) {
Utils.serviceGetNews(getBaseContext());
SampleAlarmReceiver.completeWakefulIntent(intent);
}
public static void sendNotification(String msg, Context context) {
mNotificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, NewsActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("title")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg)
.setAutoCancel(true);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
您需要澄清一下您的使用情况。您是否已经使用'AlarmManager'来触发'BroadcastReceiver',然后启动您的服务?你的'Service'是否设置为通过其他机制自动启动? –
我发布了我正在使用的代码。它是来自开发人员教程的副本,用于使用IntentService与服务器进行连接。 – user3249186