android service 教你打造不被杀死的service-------service进程守护


转载请标明出处:
http://blog.csdn.net/liuzg1220;
本文出自:【HugeBug的博客】


简介


相信做android的兄弟们经常会提出这样的要求,我们能不能让我们的程序在后台运行且不停的采集数据,我们给我的答案是能-------service可以做到这样的事,那我们能不能让我们后台运行的程序不要轻易被系统回收呢?----------这个有点难:下面我就正对如何不被系统回收提高service优先级来聊一聊。

方案

方案一:将service设置为前台service,这样的做会在前端弹出一个notification切是一直存在。具体实现在service中加上如下代码:

		
           <span style="font-size:14px;">Notification notification = new Notification(R.drawable.ic_lancher, "上传数据", System.currentTimeMillis());
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
             notification.setLatestEventInfo(this, "前端service", "前端service", pendingIntent);
             startForeground(1, notification);</span>

方法二:提高service的优先级,在AndroidManifest中设置android:priority="1000".

方法三:将应用做成系统应用,(这方法基本呵呵了),

上面的一和二当系统内存不足时还是会被系统回收,且在服务中手动杀掉服务就不会在自动启动,那可不可做到服务杀不掉呢?当然可以,双服务进程相互监听守护,教打造不被杀死的后台服务,通过aidl实现进程间的通信:

首先我们先看看效果图:



Service1

package com.lzg.strongservice.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.widget.Toast;

import com.lzg.strongservice.utils.Utils;

/**
 * 
 * @author henry
 *
 */
public class Service1 extends Service {
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				startService2();
				break;

			default:
				break;
			}

		};
	};

	/**
	 * 使用aidl 启动Service2
	 */
	private StrongService startS2 = new StrongService.Stub() {
		@Override
		public void stopService() throws RemoteException {
			Intent i = new Intent(getBaseContext(), Service2.class);
			getBaseContext().stopService(i);
		}

		@Override
		public void startService() throws RemoteException {
			Intent i = new Intent(getBaseContext(), Service2.class);
			getBaseContext().startService(i);
		}
	};

	/**
	 * 在内存紧张的时候,系统回收内存时,会回调OnTrimMemory, 重写onTrimMemory当系统清理内存时从新启动Service2
	 */
	@Override
	public void onTrimMemory(int level) {
		/*
		 * 启动service2
		 */
		startService2();

	}

	@Override
	public void onCreate() {
		Toast.makeText(Service1.this, "Service1 正在启动...", Toast.LENGTH_SHORT)
				.show();
		startService2();
		/*
		 * 此线程用监听Service2的状态
		 */
		new Thread() {
			public void run() {
				while (true) {
					boolean isRun = Utils.isServiceWork(Service1.this,
							"com.lzg.strongservice.service.Service2");
					if (!isRun) {
						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);
					}
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			};
		}.start();
	}

	/**
	 * 判断Service2是否还在运行,如果不是则启动Service2
	 */
	private void startService2() {
		boolean isRun = Utils.isServiceWork(Service1.this,
				"com.lzg.strongservice.service.Service2");
		if (isRun == false) {
			try {
				startS2.startService();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return (IBinder) startS2;
	}
}

Service2:

<strong><span style="font-size:14px;">package com.lzg.strongservice.service;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.widget.Toast;

import com.lzg.strongservice.utils.Utils;

/**
 * 
 * @author henry
 *
 */
public class Service2 extends Service {

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 1:
				startService1();
				break;

			default:
				break;
			}

		};
	};

	/**
	 * 使用aidl 启动Service1
	 */
	private StrongService startS1 = new StrongService.Stub() {

		@Override
		public void stopService() throws RemoteException {
			Intent i = new Intent(getBaseContext(), Service1.class);
			getBaseContext().stopService(i);
		}

		@Override
		public void startService() throws RemoteException {
			Intent i = new Intent(getBaseContext(), Service1.class);
			getBaseContext().startService(i);

		}
	};

	/**
	 * 在内存紧张的时候,系统回收内存时,会回调OnTrimMemory, 重写onTrimMemory当系统清理内存时从新启动Service1
	 */
	@Override
	public void onTrimMemory(int level) {
		startService1();
	}

	@SuppressLint("NewApi")
	public void onCreate() {

		Toast.makeText(Service2.this, "Service2 启动中...", Toast.LENGTH_SHORT)
				.show();
		startService1();
		/*
		 * 此线程用监听Service2的状态
		 */
		new Thread() {
			public void run() {
				while (true) {
					boolean isRun = Utils.isServiceWork(Service2.this,
							"com.lzg.strongservice.service.Service1");
					if (!isRun) {
						Message msg = Message.obtain();
						msg.what = 1;
						handler.sendMessage(msg);
					}
					try {
						Thread.sleep(1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
		}.start();
	}

	/**
	 * 判断Service1是否还在运行,如果不是则启动Service1
	 */
	private void startService1() {
		boolean isRun = Utils.isServiceWork(Service2.this,
				"com.lzg.strongservice.service.Service1");
		if (isRun == false) {
			try {
				startS1.startService();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		return START_STICKY;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return (IBinder) startS1;
	}

}</span></strong>


aidl

<span style="font-size:14px;">package com.lzg.strongservice.service;
interface StrongService{
	void startService();
	void stopService();
}</span>

源码下载





评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值