0

我在 AlarmManager 中启动了一个重复任务,但我怎样才能获得服务中的重复计数。这是代码 MyActivity

mAlarmSender = PendingIntent.getService(MyActivity.this,0, new Intent(MyActivity2.this, AutoBuild.class), 0);

    long firstTime = SystemClock.elapsedRealtime();

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            firstTime, 1000 * 5, mAlarmSender);

自动构建

public class AutoBuild extends Service {

private String[] infos;

private Intent mIntent;

private String pathStr;

static final String TAG = "AutoBuild";

private int i=0;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    this.mIntent = intent;

    return START_STICKY;
}

@Override
public void onCreate() {

    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    printData(i);/**print result*/

    i++;/*count ++*/

    AutoBuild.this.stopSelf();/*stop service */

}

private void printData(int i) {     

   Log.i(TAG, i + "");    
}


@Override
public IBinder onBind(Intent intent) {

    return mBinder;
}

private final IBinder mBinder = new Binder() {

    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply,
                                 int flags) throws RemoteException {
        return super.onTransact(code, data, reply, flags);
    }
};

}

i 的值始终为 0:Alarmanage 重复时是否可以更改此值

4

1 回答 1

0

问题Service是它作为单个实例运行。每次启动同一个服务时,只onStartCommand()调用该方法。因此,如果您使用 analarmManager并且想要更改其中的变量,Service您可以在onStartCommand(). onCreate()仅在第一次启动时调用一次,Service因此在您的情况下,变量i在连续调用Service.

检查以下内容以获取更多详细信息:http: //developer.android.com/guide/components/services.html#StartingAService

于 2012-06-26T03:58:37.113 回答