转:http://www.asiteof.me/2011/02/wakelock-wifilock/
在android中,申请WakeLock可以使进程持续执行,即使进入睡眠模式,进程的执行也不间断,而且能保持屏幕常亮。
WifiLock跟WakeLock用法作用与WakeLock相同,不过前者是针对Wifi的而已。
SMS Backup中关于WakeLock以及WifiLock的代码如下:
private static void acquireWakeLock(Context ctx) {
if (sWakeLock == null) {
PowerManager pMgr = (PowerManager) ctx.getSystemService(POWER_SERVICE); //保持当前进程持续有效
sWakeLock = pMgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"SmsSyncService.sync() wakelock.");
WifiManager wMgr = (WifiManager) ctx.getSystemService(WIFI_SERVICE); //保持wifi有效
sWifiLock = wMgr.createWifiLock("SMS Backup");
}
sWakeLock.acquire();
sWifiLock.acquire();
}
用完一定要记得释放锁:
private static void releaseWakeLock(Context ctx) {
sWakeLock.release();
sWifiLock.release();
}
而且要注意在AndroidManifest.xml中注明wakelock权限的申请:
<uses -permission android:name="android.permission.WAKE_LOCK"/>
public class TestHandler extends Activity {
Button m_startbtn ;
Button m_endbtn;
MyThreadHandler m_threadHandler;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
System.out.println(Thread.currentThread().getId());
m_startbtn = (Button)findViewById(R.id.start);
m_startbtn.setOnClickListener(new StartOnClickListener());
new MyThread().start();
}
class StartOnClickListener implements OnClickListener
{
@Override
public void onClick(View v) {
//在主线程中获取子线程的message对象然后再发送
Message msg = m_threadHandler.obtainMessage(1,1,1,"主线程发消息了");
m_threadHandler.sendMessage(msg);
}
}
class MyThread extends Thread
{
@Override
public void run()
{
//创建该线程的Looper对象,用于接收消息
Looper.prepare();
//线程的looper创建的handler表示消息接收者是子线程
m_threadHandler = new MyThreadHandler(Looper.myLooper());
//循环从MessageQueue中取消息。
Looper.loop();
}
}
class MyThreadHandler extends Handler
{
public MyThreadHandler(Looper loop)
{
super(loop);
}
@Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
//消息处理
System.out.println("我是子线程的Handler,收到了消息:"+(String)msg.obj);
}
}
}
•