我有一個意圖服務,每天與服務器連接一次,並且工作正常,就像在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