admin 管理员组

文章数量: 1184232

随时随地阅读更多技术实战干货,获取项目源码、学习资料,请关注源代码社区公众号(ydmsq666)

要实现自动关机的功能需要手机有root权限,如果手机有root权限,运行该程序时,会提示该应用正在申请获取root权限,选择运行即可实现关机。代码如下:

activity:

package com.home.automaticshutdown;
import java.io.DataOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AutomaticShutdownActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Button closeBtn = (Button) findViewById(R.id.main_btn_close);
		closeBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				shutdown();
			}
		});
	}
	/**
	 * 关机的方法,需要手机有root权限
	 */
	private void shutdown() {
		try {
			Process process = Runtime.getRuntime().exec("su");
			DataOutputStream out = new DataOutputStream(
					process.getOutputStream());
			out.writeBytes("reboot -p\n");
			out.writeBytes("exit\n");
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


本文标签: 关机 系统 编程