使用手机关闭电脑

最近有需要远程关闭电脑的需求,
其实关闭电脑也很简单,JAVA执行"shutdown -s -t 60"即可
自己瞎捣鼓一个。
就是通过一个手机给本地手机(跟电脑在连得同一个局域网)发短信
本地手机请求服务端,执行关机指令,关机~
因为也不好做外网访问,所以只能找一个手机做中介了。
没用到什么技术,就是一个读取短信,以及联网请求,服务器端处理参数,执行关机命令。

如果有哪位大大知道怎么可以外网访问本地tomcat,还请不吝赐教(家里可以通过路由器架设虚拟服务器实现,公司不好弄)。


服务端代码很简单啦~

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String str = request.getHeader("shutdown");
		if (str != null) {
			if (str.equals("ok")) {
				Runtime run = Runtime.getRuntime();
				run.exec("shutdown -s -t 60");
			}
		}
	}


客户端代码,需要接受第三方短信触发~

Class GetSingalMsg
package com.nico.remoteshutdown;

import com.nico.util.RequestShutDown;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

public class GetSingalMsg extends BroadcastReceiver {
	@Override
	public void onReceive(Context ctx, Intent it) {
		if (it.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
			SmsMessage[] sms = getMessagesFromIntent(it);

			SmsMessage s = sms[0];
			if (s.getOriginatingAddress().equals("11223213123123")
					&& s.getDisplayMessageBody().equals("关机")) {
				RequestShutDown rsd = new RequestShutDown();
				rsd.execute();
			}
		}
	}

	public final SmsMessage[] getMessagesFromIntent(Intent intent) {
		Object[] messages = (Object[]) intent.getSerializableExtra("pdus");
		byte[][] pduObjs = new byte[messages.length][];
		for (int i = 0; i < messages.length; i++) {
			pduObjs[i] = (byte[]) messages[i];
		}
		byte[][] pdus = new byte[pduObjs.length][];
		int pduCount = pdus.length;
		SmsMessage[] msgs = new SmsMessage[pduCount];
		for (int i = 0; i < pduCount; i++) {
			pdus[i] = pduObjs[i];
			msgs[i] = SmsMessage.createFromPdu(pdus[i]);
		}
		return msgs;
	}
}



RequestShutDown 请求任务

package com.nico.util;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.os.AsyncTask;
import android.util.Log;

public class RequestShutDown extends AsyncTask<String, String, String> {

	@Override
	protected String doInBackground(String... str) {
		URL u;
		try {
			u = new URL(
					"http://localhost:8080/remoteshutdown/MainServlet");
			try {
				HttpURLConnection conn = (HttpURLConnection) u.openConnection();
				conn.setRequestProperty("shutdown", "ok");
				conn.connect();
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
finally
{
conn.disconnect();
}
		return null;
	}

}

猜你喜欢

转载自hellorheaven.iteye.com/blog/1997850
今日推荐