本文原作者“minminaya”,作者网站:minminaya.cn,为了提升文章品质,即时通讯网对内容作了幅修订和改动,感谢原作者。
333.jpeg (29.97 KB, 下载次数: 1251)
下载附件 保存到相册
5 年前 上传
11.jpg (12.03 KB, 下载次数: 1271)
KeepAliveConnection interface KeepAliveConnection { }
/** * 主进程 双进程通讯 * * @author LiGuangMin * @time Created by 2018/8/17 11:26 */ public class StepService extends Service { private final static String TAG = StepService.class.getSimpleName(); private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Logger.d(TAG, "StepService:建立链接"); boolean isServiceRunning = ServiceAliveUtils.isServiceAlice(); if (!isServiceRunning) { Intent i = new Intent(StepService.this, DownloadService.class); startService(i); } } @Override public void onServiceDisconnected(ComponentName componentName) { // 断开链接 startService(new Intent(StepService.this, GuardService.class)); // 重新绑定 bindService(new Intent(StepService.this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT); } }; @Nullable @Override public IBinder onBind(Intent intent) { return new KeepAliveConnection.Stub() { }; } @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(1, new Notification()); // 绑定建立链接 bindService(new Intent(this, GuardService.class), mServiceConnection, Context.BIND_IMPORTANT); return START_STICKY; } }
/** * 守护进程 双进程通讯 * * @author LiGuangMin * @time Created by 2018/8/17 11:27 */ public class GuardService extends Service { private final static String TAG = GuardService.class.getSimpleName(); private ServiceConnection mServiceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { Logger.d(TAG, "GuardService:建立链接"); boolean isServiceRunning = ServiceAliveUtils.isServiceAlice(); if (!isServiceRunning) { Intent i = new Intent(GuardService.this, DownloadService.class); startService(i); } } @Override public void onServiceDisconnected(ComponentName componentName) { // 断开链接 startService(new Intent(GuardService.this, StepService.class)); // 重新绑定 bindService(new Intent(GuardService.this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT); } }; @Nullable @Override public IBinder onBind(Intent intent) { return new KeepAliveConnection.Stub() { }; } @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(1, new Notification()); // 绑定建立链接 bindService(new Intent(this, StepService.class), mServiceConnection, Context.BIND_IMPORTANT); return START_STICKY; } }
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) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, DownloadService.class); startService(intent); bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); //双守护线程,优先级不一样 startAllServices(); } @Override public void onContentChanged() { super.onContentChanged(); mShowTimeTv = findViewById(R.id.tv_show_time); } @Override protected void onDestroy() { super.onDestroy(); unbindService(mServiceConnection); } /** * 开启所有守护Service */ private void startAllServices() { startService(new Intent(this, StepService.class)); startService(new Intent(this, GuardService.class)); } }
public class SinglePixelActivity extends AppCompatActivity { private static final String TAG = SinglePixelActivity.class.getSimpleName(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window mWindow = getWindow(); mWindow.setGravity(Gravity.LEFT | Gravity.TOP); WindowManager.LayoutParams attrParams = mWindow.getAttributes(); attrParams.x = 0; attrParams.y = 0; attrParams.height = 1; attrParams.width = 1; mWindow.setAttributes(attrParams); ScreenManager.getInstance(this).setSingleActivity(this); } @Override protected void onDestroy() { if (!SystemUtils.isAppAlive(this, Constant.PACKAGE_NAME)) { Intent intentAlive = new Intent(this, DownloadService.class); startService(intentAlive); } super.onDestroy(); } }
public class ScreenReceiverUtil { private Context mContext; private SreenBroadcastReceiver mScreenReceiver; private SreenStateListener mStateReceiverListener; public ScreenReceiverUtil(Context mContext) { this.mContext = mContext; } public void setScreenReceiverListener(SreenStateListener mStateReceiverListener) { this.mStateReceiverListener = mStateReceiverListener; // 动态启动广播接收器 this.mScreenReceiver = new SreenBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_ON); filter.addAction(Intent.ACTION_SCREEN_OFF); filter.addAction(Intent.ACTION_USER_PRESENT); mContext.registerReceiver(mScreenReceiver, filter); } public void stopScreenReceiverListener() { mContext.unregisterReceiver(mScreenReceiver); } /** * 监听sreen状态对外回调接口 */ public interface SreenStateListener { void onSreenOn(); void onSreenOff(); void onUserPresent(); } public class SreenBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (mStateReceiverListener == null) { return; } if (Intent.ACTION_SCREEN_ON.equals(action)) { // 开屏 mStateReceiverListener.onSreenOn(); } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { // 锁屏 mStateReceiverListener.onSreenOff(); } else if (Intent.ACTION_USER_PRESENT.equals(action)) { // 解锁 mStateReceiverListener.onUserPresent(); } } } }
public class ScreenManager { private static final String TAG = ScreenManager.class.getSimpleName(); private static ScreenManager sInstance; private Context mContext; private WeakReference<Activity> mActivity; private ScreenManager(Context mContext) { this.mContext = mContext; } public static ScreenManager getInstance(Context context) { if (sInstance == null) { sInstance = new ScreenManager(context); } return sInstance; } /** 获得SinglePixelActivity的引用 * @param activity */ public void setSingleActivity(Activity activity) { mActivity = new WeakReference<>(activity); } /** * 启动SinglePixelActivity */ public void startActivity() { Intent intent = new Intent(mContext, SinglePixelActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); } /** * 结束SinglePixelActivity */ public void finishActivity() { if (mActivity != null) { Activity activity = mActivity.get(); if (activity != null) { activity.finish(); } } } }
<style name="SingleActivityStyle" parent="android:Theme.Holo.Light.NoActionBar"> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:windowFrame">@null</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item> <item name="android:windowContentOverlay">@null</item> <item name="android:backgroundDimEnabled">false</item> <item name="android:windowAnimationStyle">@null</item> <item name="android:windowDisablePreview">true</item> <item name="android:windowNoDisplay">false</item>
<activity android:name=".activity.SinglePixelActivity" android:configChanges="keyboardHidden|orientation|screenSize|navigation|keyboard" android:excludeFromRecents="true" android:finishOnTaskLaunch="false" android:launchMode="singleInstance" android:theme="@style/SingleActivityStyle" />
public class DownloadService extends Service { public static final int NOTICE_ID = 100; private static final String TAG = DownloadService.class.getSimpleName(); 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 ScreenReceiverUtil.SreenStateListener mScreenListenerer = new ScreenReceiverUtil.SreenStateListener() { @Override public void onSreenOn() { mScreenManager.finishActivity(); Logger.d(TAG, "关闭了1像素Activity"); } @Override public void onSreenOff() { mScreenManager.startActivity(); Logger.d(TAG, "打开了1像素Activity"); } @Override public void onUserPresent() { } }; private OnTimeChangeListener mOnTimeChangeListener; @Override public void onCreate() { super.onCreate(); // 注册锁屏广播监听器 mScreenListener = new ScreenReceiverUtil(this); mScreenManager = ScreenManager.getInstance(this); mScreenListener.setScreenReceiverListener(mScreenListenerer); mDownloadBinder = new DownloadBinder(); mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Logger.d(TAG, "onStartCommand"); startRunTimer(); return START_STICKY; } @Nullable @Override public IBinder onBind(Intent intent) { return mDownloadBinder; } @Override public boolean onUnbind(Intent intent) { Logger.d(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(); // mScreenListener.stopScreenReceiverListener(); } 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); } Logger.d(TAG, 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; Logger.d(TAG, "时间为:" + mTimeHour + " : " + mTimeMin + " : " + mTimeSec); } public interface OnTimeChangeListener { void showTime(String time); } public class DownloadBinder extends Binder { public void setOnTimeChangeListener(OnTimeChangeListener onTimeChangeListener) { mOnTimeChangeListener = onTimeChangeListener; } } }
记得当时用的是某运动记步APP,它为了保活就是这么干的。之所以被我发现,是因为在我的Android手机上,每次打开这个APP居然总能莫名其妙听到若有若无的环境噪音样的声音,尤其安静的场所下更明显。我个人估计这个APP里用的保活音频文件,很可能就是程序员在简陋的条件下随手自已录制的,虽然也是不得以为之,但做法确实是有点粗糙。
public class PlayerMusicService extends Service { private final static String TAG = PlayerMusicService.class.getSimpleName(); private MediaPlayer mMediaPlayer; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { super.onCreate(); Logger.d(TAG, TAG + "---->onCreate,启动服务"); mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent); mMediaPlayer.setLooping(true); } @Override public int onStartCommand(Intent intent, int flags, int startId) { new Thread(new Runnable() { @Override public void run() { startPlayMusic(); } }).start(); return START_STICKY; } private void startPlayMusic() { if (mMediaPlayer != null) { Logger.d(TAG, "启动后台播放音乐"); mMediaPlayer.start(); } } private void stopPlayMusic() { if (mMediaPlayer != null) { Logger.d(TAG, "关闭后台播放音乐"); mMediaPlayer.stop(); } } @Override public void onDestroy() { super.onDestroy(); stopPlayMusic(); Logger.d(TAG, TAG + "---->onCreate,停止服务"); // 重启自己 Intent intent = new Intent(getApplicationContext(), PlayerMusicService.class); startService(intent); } }
Intent intent = new Intent(this, PlayerMusicService.class); startService(intent);
<service android:name=".service.PlayerMusicService" android:enabled="true" android:exported="true" android:process=":music_service" />
public class ScheduleService extends JobService { private static final String TAG = ScheduleService.class.getSimpleName(); @Override public boolean onStartJob(JobParameters params) { boolean isServiceRunning = ServiceAliveUtils.isServiceAlice(); if (!isServiceRunning) { Intent i = new Intent(this, DownloadService.class); startService(i); Logger.d(TAG, "ScheduleService启动了DownloadService"); } jobFinished(params, false); return false; } @Override public boolean onStopJob(JobParameters params) { return false; } }
/** * 使用JobScheduler进行保活 */ 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 * 2); builder.setPersisted(true); builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); int schedule = jobScheduler.schedule(builder.build()); if (schedule <= 0) { Logger.w(TAG, "schedule error!"); } }
<service android:name=".service.ScheduleService" android:enabled="true" android:exported="true" android:permission="android.permission.BIND_JOB_SERVICE" />
public class ServiceAliveUtils { public static boolean isServiceAlice() { boolean isServiceRunning = false; ActivityManager manager = (ActivityManager) MyApplication.getMyApplication().getSystemService(Context.ACTIVITY_SERVICE); if (manager == null) { return true; } for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if ("demo.lgm.com.keepalivedemo.service.DownloadService".equals(service.service.getClassName())) { isServiceRunning = true; } } return isServiceRunning; } }
来源:即时通讯网 - 即时通讯开发者社区!
轻量级开源移动端即时通讯框架。
快速入门 / 性能 / 指南 / 提问
轻量级Web端即时通讯框架。
详细介绍 / 精编源码 / 手册教程
移动端实时音视频框架。
详细介绍 / 性能测试 / 安装体验
基于MobileIMSDK的移动IM系统。
详细介绍 / 产品截图 / 安装体验
一套产品级Web端IM系统。
详细介绍 / 产品截图 / 演示视频
引用此评论
引用:hc111 发表于 2019-09-24 16:48 总结的很好,现在真的很难保活
引用:elan 发表于 2019-11-28 20:08 正文第一个超链错了
引用:yangqingyuan 发表于 2020-09-29 10:52 只能尝试看看效果,要做保活真的是难上加难
精华主题数超过100个。
连续任职达2年以上的合格正式版主
为论区做出突出贡献的开发者、版主等。
Copyright © 2014-2024 即时通讯网 - 即时通讯开发者社区 / 版本 V4.4
苏州网际时代信息科技有限公司 (苏ICP备16005070号-1)
Processed in 0.156250 second(s), 44 queries , Gzip On.