android利用广播和服务实现一个杀不死的流氓应用

1.创建一个android工程
2.创建两个service类OneService和TwoService
3.在MainActivity中开启两个service;
Intent one = new Intent(this, OneService.class);
startService(one);
Intent two = new Intent(this, TwoService.class);
startService(two);
好了准备工作做完了,直接上代码,下面是OneService中的代码
/**
 * 循环监听是否有新消息
 */
public class OneService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
//在这里注册一个广播,用来监听另外一个service的状况
IntentFilter filter = new IntentFilter();
filter.addAction("com.hnzs.zsoa.service.TwoService");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 接受到广播会调用onReceive方法,在这里重新开启TwoService
Intent in = new Intent(OneService.this, TwoService.class);
startService(in);
}
};
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Intent in = new Intent();
in.setAction("com.hnzs.zsoa.service.OneService");
sendBroadcast(in);
unregisterReceiver(receiver);
}


}
下面是TwoService中的代码。
/**
 * 守护进程
 * @author yh
 * @date 2016-8-9
 */
public class TwoService extends Service {
private BroadcastReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("com.hnzs.zsoa.service.OneService");
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("My", "收到广播");
Intent in=new Intent(TwoService.this,OneService.class);
startService(in);
}


};
registerReceiver(receiver, filter);
}

@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
Intent in=new Intent();
in.setAction("com.hnzs.zsoa.service.TwoService");
sendBroadcast(in);
unregisterReceiver(receiver);
}

}

好啦,这就写成了一个简单的流氓进程,其实原理很简单,就是两个服务互相开启对方。

你可能感兴趣的:(Android开发,Android)