0

在我的项目中,每天只需要更新一个 Web 服务,每天下午 4 点。

但我不知道如何创建一个后台服务,每天下午 4 点执行

请帮助我如何解决此问题

提前致谢

4

1 回答 1

0

只需像下面的示例一样创建一项服务并将时间 9 更改为 16 以执行您的任务

import java.util.Calendar;
import java.util.Date;

import android.R.integer;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

public class MantraAlarmService extends Service {

private Handler handler;
private Runnable runnable;
integer message;

@Override
public void onCreate() {
    super.onCreate();

    handler = new Handler();
    runnable = new Runnable() {

        public void run() {
            // TODO Auto-generated method stub

            Calendar cal = Calendar.getInstance();

            Date time = cal.getTime();

            Calendar cal1 = Calendar.getInstance();

            cal1.set(cal1.get(Calendar.YEAR), cal1.get(Calendar.MONTH),
                    cal1.get(Calendar.DAY_OF_MONTH), 9, 0, 0);

            Date time1 = cal1.getTime();

            if (time1.equals(time)) {


                int day = cal.get(Calendar.DAY_OF_WEEK);

                // do your task here 
            }

            handler.postDelayed(runnable, 1000);

        }
    };

    handler.post(runnable);

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
@Deprecated
public void onStart(Intent intent, int startId) {
    super.onStart(intent, startId);

}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();

}

private void generateNotification(Context context, String message) {
    System.out.println(message + "++++++++++2");
    int icon = R.drawable.manta_icon;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    String subTitle = message;
    Intent notificationIntent = new Intent(context, PlayView.class);
    notificationIntent.putExtra("content", message);
    PendingIntent intent = PendingIntent.getActivity(context, 0,
            notificationIntent, 0);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    notification.setLatestEventInfo(context, title, subTitle, intent);
    // To play the default sound with your notification:
    notification.defaults = Notification.DEFAULT_SOUND;
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);

}
}
于 2014-05-07T07:18:04.630 回答