我确实创建了一个Android应用,每15秒发送一次短信。我确实创建了一个可以实现它的服务,它永远不会结束,因为我需要向我的客户发送警报,这对于丢失消息至关重要。 服务代码如下:
public class AppService extends Service {
private static final long _updateIntervar = 15000;
private static final long _initialInterval = 100;
private static Timer timer = new Timer();
private PowerManager.WakeLock mWakeLock = null;
public AppService() {}
@Override
public void onCreate() {
super.onCreate();
PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, AppService.class.getName());
this.runingAppService();
}
@Override
public void onDestroy() {
super.onDestroy();
mWakeLock.release();
stopForeground(true);
}
public void runingAppService() {
try {
TimerTask task = new TimerTask() {
@Override
public void run() {
sendMessages();
}
};
timer.schedule(task, _initialInterval, _updateIntervar);
} catch (Exception e) {
Common.showToast(e.getMessage(), Common._shortPeriodToast);
}
}
private void sendMessages() {
if (InternalData.getStatusLogin() && InternalData.getStatusService()) {
Map<String, String> data = new HashMap<String, String>();
data.put("OPTION", "GET_MESSAGES");
data.put("DISTRIBUTOR", String.valueOf(InternalData.getIdDistribuidor()));
data.put("SMS_GATEWAY", String.valueOf(InternalData.getIdGateWay()));
HttpServerRequest.getDataMessages(data);
HttpServerRequest.setMessageReceived(SMS.readInboxSMS());
System.gc();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(Process.myPid(), new Notification());
mWakeLock.acquire();
return START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Null");
return null;
}}
我在我的服务上使用TimerTask来调用方法sendMessages()并且确实如此,但是在五次或有时候我的服务停止之后。如果有人知道我做错了,我会非常感谢他们。
答案 0 :(得分:0)
尝试从onStartCommand方法返回START_STICKY:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startForeground(Process.myPid(), new Notification());
mWakeLock.acquire();
return START_STICKY;
}
START_STICKY用于根据需要显式启动和停止的服务: https://developer.android.com/reference/android/app/Service.html#START_STICKY