0

在我的应用程序中,我每隔一分钟从活动中重新启动我的服务。但如果应用程序被强制关闭,它将启动服务。当时的活动状态如何。

这是我的代码。

void toggleLogging(boolean isStart, int interval) 
{
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent loggerIntent = PendingIntent.getBroadcast(this, 0,new Intent(this,AlarmReceiver.class), 0);       
    long duration = interval * 60 * 1000;
    manager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    SystemClock.elapsedRealtime(), duration, loggerIntent);
    AppSettings.setServiceRunning(this, true);
}
4

1 回答 1

0

是的,即使应用程序被强制关闭,也会注册警报,所以不用担心

根据您的要求,我添加了代码

public class SampleActivity extends Activity{
    public static AlarmManager mAlarmManager;
    public static PendingIntent mPintent;
    public static Intent mIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Context context = getApplicationContext();
        SampleActivity.startAlarmManager(context);
    }

    public static void startAlarmManager(Context context){
        SampleActivity.mIntent = new Intent(context, YourService.class);
        mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        mPintent = PendingIntent.getService(context, 0, SampleActivity.mIntent, 0);
        Calendar cal = Calendar.getInstance();
        mAlarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 2000, mPintent);
    }
}

然后在启动完成时启动相同的警报

public class SampleBootComplete extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent arg1) {
        SampleActivity.startAlarmManager(context);
    }

}

在清单文件中注册启动完成接收器

<receiver android:name="com.sample.receiver.SampleBootComplete">
           <intent-filter >
               <action android:name="android.intent.action.BOOT_COMPLETED"/>
           </intent-filter>
       </receiver>
于 2013-04-15T06:21:58.910 回答