公司最近的新需求,需要实时动态的向后台上传经纬度,每隔10s上传一次,记录运行轨迹,尝试了多种办法都不行,只能用开启无声音乐来保活。
下面是service的主要代码
先注册一下:
<service
android:name="com.common.x.areainspect.AreaInspectService"
android:exported="true"
android:priority="1000">
<intent-filter>
<action android:name="com.common.x.areainspect.AreaInspectService" />
</intent-filter>
</service>
service的主要代码
package com.project.common.work;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import com.project.R;
import java.util.Timer;
import java.util.TimerTask;
public class AreaInspectService extends Service {
private Timer timer;
private long when = 1000 * 2; // 延迟2秒执行
private long period = 1000 * 5; // 每次定位执行间隔
private long periodAreaInspect = 1000 * 10; // 每次巡查执行间隔
@Override
public IBinder onBind(Intent intent) {
return null;
}
/**
* 定时定位
*/
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
//在这里面定时传送数据
}
};
@Override
public void onCreate() {
super.onCreate();
timer = new Timer();
// 启动定位
timer.schedule(timerTask, when, period);
}
@Override
public void onDestroy() {
if (timer != null) {
timer.cancel();
}
stopVoice();
stopForeground(true);
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
PendingIntent notificationIntent = PendingIntent.getActivity(this, 0, new Intent(this, AreaInspectActivity.class), 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("正在巡查")
.setContentText("位置刷新中")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(notificationIntent)
.build();
startForeground(123456,noti);
start_mp3();
return Service.START_STICKY;
}
private MediaPlayer mediaPlayer;
//开始播放声音
private void start_mp3() {
try {
mediaPlayer = MediaPlayer.create(this, R.raw.silent);//silent为无声音乐,网上搜索下载就可以
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
//停止播放声音
public void stopVoice(){
if(null!=mediaPlayer) {
mediaPlayer.stop();
}
}
}
开启服务
Intent intent = new Intent(AreaInspectActivity.this, AreaInspectService.class); startService(intent);
停止服务
Intent intent = new Intent(AreaInspectActivity.this, AreaInspectService.class); stopService(intent);
扫描二维码关注公众号,回复:
13085432 查看本文章