如果强制关闭,则重启服务

时间:2013-04-15 06:08:50

标签: android android-service

在我的应用中,我每分钟都会从活动中重新启动服务。但如果申请被强制关闭,它将启动该服务。那段时间的活动状态如何。

这是我的代码。

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);
}

1 个答案:

答案 0 :(得分: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);
    }

}

在manifestfile中注册启动完成接收器

<receiver android:name="com.sample.receiver.SampleBootComplete">
           <intent-filter >
               <action android:name="android.intent.action.BOOT_COMPLETED"/>
           </intent-filter>
       </receiver>