也许有更好的方法,但我按照@Rahul的建议实现了一个STICK_SERVICE,并且为了避免杀死该服务,在状态栏中强制显示了一个固定的通知。我知道这可能不是一个好习惯,但是客户要求在状态栏中显示“应用程序正在运行...”,所以没问题。
SyncService.class
public class SyncService extends IntentService {
private static int FOREGROUND_ID = 1338;
public Boolean isServiceRunning = false;
Integer delay;
private NotificationManager mgr;
public SyncService() {
super("SyncService");
}
@Override
public void onStart(@Nullable Intent intent, int startId) {
super.onStart(intent, startId);
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
performSync();
startSyncThread();
mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final NotificationCompat.Builder builder = buildForeground();
startForeground(1, builder.build());
return START_STICKY;
}
public Boolean isWifiConnected() {
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
return mWifi.isConnected();
}
public void startSyncThread() {
Handler handler = new Handler();
delay = 1000;
handler.postDelayed(new Runnable() {
public void run() {
performSync();
handler.postDelayed(this, delay);
}
}, delay);
}
public void performSync() {
if (isWifiConnected()) {
Log.i("SyncService:", "Wifi connected, start syncing...");
Sync sync = new Sync(this);
sync.postPhotos();
sync.postEvents();
sync.getEvents();
delay = 60000;
} else {
Log.i("SyncService:", "Wifi IS NOT connected, ABORT syncing...");
delay = 1000;
}
Log.i("SyncService:", delay + "");
}
@Override
protected void onHandleIntent(Intent intent) {
WakefulReceiver.completeWakefulIntent(intent);
}
private NotificationCompat.Builder buildForeground() {
Intent intent = new Intent(this, EventsActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
b.setContentTitle("Prime Share is running")
.setSmallIcon(android.R.drawable.stat_notify_sync_noanim)
.setOngoing(true)
.setAutoCancel(false)
.setPriority(Notification.PRIORITY_MAX)
.setContentIntent(pendingIntent);
return (b);
}
}
然后在我的第一个活动的onCreate中,我调用了这个:
context = this;
startSyncIntent = new Intent(this, SyncService.class);
startService(startSyncIntent);