0
私は15秒ごとにテキストメッセージを送信するAndroidアプリを作成しました。私はそれを作るサービスを作りました、そして、私はクライアントにアラートを送る必要があり、メッセージを失うことが非常に重要なので、決して終了する必要はありません。 サービスコードは以下の通りです:いつもバックグラウンドでサービス
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;
}}
は、私は、メソッドsendMessages()への呼び出しのための私のサービスにTimerTaskをを使用し、それがない、時には5以降に以下の私のサービスが停止しています。誰かが私が間違っていると思っているなら、私はとても感謝するつもりです。
おかげで、私がしようこの方法で。よろしく。 – Jarboox