android 前后台保活 实现定位数据定时上传并展示轨迹 (中)

前一篇文章: https://blog.csdn.net/qq_40803752/article/details/86182480

前一篇讲解了,我应用的后台保活。这篇文章说下,前台,还有保活的关闭,
把无限音乐的放在工作服务,还有工作服务的保活效果测试。

1.工作服务 :无限播放音乐 ,并且设置变量,可以关闭播放,如果是在其他服务,就
不好控制关闭了。
public class DownloadService extends Service {
public Context mContext=this;
private MediaPlayer mMediaPlayer;
private Timer mRunTimer;
private int mTimeSec;
private int mTimeMin;
private int mTimeHour;

@Override
public void onCreate() {
    super.onCreate();
    mContext=this;
    //后台播放无声 音乐
    mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
    mMediaPlayer.setLooping(true);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("TAG","onStartCommand");
    mContext=this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            startPlayMusic();
        }
    }).start();

    return START_STICKY;
}
private void startPlayMusic() {
    if (mMediaPlayer != null) {
        mMediaPlayer.start();
    }
}

private void stopPlayMusic() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
    }
}
@Nullable
@Override
public IBinder onBind(Intent intent) {

    return mDownloadBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    Log.e("TAG","onUnbind");
    return super.onUnbind(intent);
}

@Override
public void onDestroy() {
    super.onDestroy();
    NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (mManager == null) {
        return;
    }
    mManager.cancel(NOTICE_ID);
    stopRunTimer();
    stopPlayMusic();
    // 重启自己

    if (sign){
        Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
        startService(intent);
    }

}

}

2.设置前台代码:
/**
* 启动前台通知
*/
private void showNotification() {
String string = mContext.getResources().getString(R.string.app_name_);
//创建通知详细信息
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.logo)
.setContentTitle(string)
.setContentText(“系统后台服务”);
// Intent intent = new Intent(this, MainProgramActivity.class);
//创建任务栈Builder
//获取通知服务
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    //获取PendingIntent
    Intent mainIntent = new Intent(this, MainProgramActivity.class);
    PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder .setContentIntent(mainPendingIntent);
    
    //构建通知
    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    //显示通知
    nm.notify(NOTICE_ID, notification);
    //启动为前台服务
    startForeground(NOTICE_ID, notification);
}
  1. 下面就是完整代码了。测试下效果用,下一篇,加上定位逻辑。
    package com.example.admin.linyuandome.houtaibaohuo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.admin.linyuandome.R;
import com.example.admin.linyuandome.activity.MainProgramActivity;
import com.example.admin.linyuandome.activity.bean.OffPointBean;
import com.example.admin.linyuandome.model.DataControl;
import com.example.admin.linyuandome.model.GPSUtils;
import com.example.admin.linyuandome.model.Model;
import com.example.admin.linyuandome.utils.MyUtils;
import com.jinye.oa.mylib.HttpCore.DataResponse;
import com.jinye.oa.mylib.LibUtils.Tools;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class DownloadService extends Service {
boolean sign=false;
public Context mContext=this;
LocationClient mLocationClient;
public static final int NOTICE_ID = 100;
private MediaPlayer mMediaPlayer;
private DownloadBinder mDownloadBinder;
private NotificationCompat.Builder mBuilderProgress;
private NotificationManager mNotificationManager;
private ScreenReceiverUtil mScreenListener;
private ScreenManager mScreenManager;
private Timer mRunTimer;
private int mTimeSec;
private int mTimeMin;
private int mTimeHour;
private OnTimeChangeListener mOnTimeChangeListener;

@Override
public void onCreate() {
    super.onCreate();
    mContext=this;

    mDownloadBinder = new DownloadBinder();
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    //后台播放无声 音乐
    mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.no_notice);
    mMediaPlayer.setLooping(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // 6.0 以上 jobservice
        useJobServiceForKeepAlive();
    }

    // 通知栏
    showNotification();

}
/**
 * 使用JobScheduler进行保活
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void useJobServiceForKeepAlive() {
    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    if (jobScheduler == null) {
        return;
    }
    jobScheduler.cancelAll();
    JobInfo.Builder builder = new JobInfo.Builder(1024, new ComponentName(getPackageName(), ScheduleService.class.getName()));
    //周期设置为了2s
    builder.setPeriodic(1000 * 10);
    builder.setPersisted(true);
    builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
    int schedule = jobScheduler.schedule(builder.build());
    if (schedule <= 0) {

    }

}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.e("TAG","onStartCommand");
    mContext=this;
    new Thread(new Runnable() {
        @Override
        public void run() {
            startPlayMusic();
        }
    }).start();
    startRunTimer();
    return START_STICKY;
}
private void startPlayMusic() {
    if (mMediaPlayer != null) {
        mMediaPlayer.start();
    }
}

private void stopPlayMusic() {
    if (mMediaPlayer != null) {
        mMediaPlayer.stop();
    }
}
@Nullable
@Override
public IBinder onBind(Intent intent) {

    return mDownloadBinder;
}

@Override
public boolean onUnbind(Intent intent) {
    Log.e("TAG","onUnbind");
    return super.onUnbind(intent);
}

@Override
public void onDestroy() {
    super.onDestroy();
    NotificationManager mManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (mManager == null) {
        return;
    }
    mManager.cancel(NOTICE_ID);
    stopRunTimer();
    stopPlayMusic();
    // 重启自己

    if (sign){
        Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class);
        startService(intent);
    }
}
private void startRunTimer() {
    TimerTask mTask = new TimerTask() {
        @Override
        public void run() {
            mTimeSec++;
            if (mTimeSec == 60) {
                mTimeSec = 0;
                mTimeMin++;
            }
            if (mTimeMin == 60) {
                mTimeMin = 0;
                mTimeHour++;
            }
            if (mTimeHour == 24) {
                mTimeSec = 0;
                mTimeMin = 0;
                mTimeHour = 0;
            }
            String time = "时间为:" + mTimeHour + " : " + mTimeMin + " : " + mTimeSec;
            if (mOnTimeChangeListener != null) {
                mOnTimeChangeListener.showTime(time);
            }
        }
    };
    mRunTimer = new Timer();
    // 每隔1s更新一下时间
    mRunTimer.schedule(mTask, 1000, 1000);
}
private void stopRunTimer() {
    if (mRunTimer != null) {
        mRunTimer.cancel();
        mRunTimer = null;
    }
    mTimeSec = 0;
    mTimeMin = 0;
    mTimeHour = 0;
    Log.e("TAG","时间为:" + mTimeHour + " : " + mTimeMin + " : " + mTimeSec);
}

public interface OnTimeChangeListener {
    void showTime(String time);
}

public class DownloadBinder extends Binder {
    public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener) {
        mOnTimeChangeListener = onTimeChangeListener;
    }
    public void setStopStatus(boolean status) {
        sign = status;
    }

}

/**
 * 启动前台通知
 */
private void showNotification() {
    String string = mContext.getResources().getString(R.string.app_name_);
    //创建通知详细信息
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.logo)
            .setContentTitle(string)
            .setContentText("系统后台服务");
  //  Intent intent = new Intent(this, MainProgramActivity.class);
    //创建任务栈Builder
    //获取通知服务
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    //获取PendingIntent
    Intent mainIntent = new Intent(this, MainProgramActivity.class);
    PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder .setContentIntent(mainPendingIntent);
    
    //构建通知
    Notification notification = builder.build();
    notification.flags |= Notification.FLAG_NO_CLEAR;
    //显示通知
    nm.notify(NOTICE_ID, notification);
    //启动为前台服务
    startForeground(NOTICE_ID, notification);
}

}

  1. 调用。在一个activity:
    public class MainActivity extends AppCompatActivity {
    private TextView mShowTimeTv;
    private DownloadService.DownloadBinder mDownloadBinder;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
    mDownloadBinder = (DownloadService.DownloadBinder) service;
    mDownloadBinder.setOnTimeChangeListener(new DownloadService.OnTimeChangeListener() {
    @Override
    public void showTime(final String time) {
    runOnUiThread(new Runnable() {
    @Override
    public void run() {
    mShowTimeTv.setText(time);
    }
    });
    }
    });
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
    

    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    //判断服务
    boolean serviceAlice = ServiceAliveUtils.isServiceAlice();

         if (!serviceAlice){
             xitongbaohuoStart(mContext);
         }
    

}

@Override
public void onContentChanged() {
super.onContentChanged();
mShowTimeTv = findViewById(R.id.tv_show_time);
}

@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
}

private void xitongbaohuoStart(Context mContext) {
Intent intent = new Intent(mContext, DownloadService.class);
//bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
startService(intent);
//双守护线程,优先级不一样
startService(new Intent(mContext, StepService.class));
startService(new Intent(mContext, GuardService.class));
}

@SuppressLint("NewApi")
private void xitongbaohuoStop(Context mContext) {

// if (mDownloadBinder!=null){
// mDownloadBinder.setStopStatus(false);
// }

   // unbindService(mServiceConnection);
    Intent intent = new Intent(mContext, DownloadService.class);
    //intent.
    stopService(intent);
    //双守护线程关闭
    stopService(new Intent(mContext, StepService.class));
    stopService(new Intent(mContext, GuardService.class));

    //关闭jobserver
    JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
    jobScheduler.cancelAll();

}

保活逻辑基本完成。下一篇,添加上百度定位,再讲解下纯Gps定位,一些户外软件就是
纯GPS,不过在城市里不行。使用百度的化,室内室外都可以理论上,但是离线定位不确定。

猜你喜欢

转载自blog.csdn.net/qq_40803752/article/details/86304508