手机锁屏功能的实现

所谓的手机锁屏就是启动一个Service
锁屏后的屏幕:
[img]
手机锁屏功能的实现
[/img]
package com.amaker.lockscreen;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
 

public class RemoteLockScreenService extends Service {
 EditText et;
 WindowManager wm;
 View v;
 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }
 
 boolean check(){
  String password = et.getText().toString();
  //这里先暂时把密码写成静态,
  if(password.equals("7758520")){
   return true;
  }else{
   return false;
  }
 }
 @Override
 public void onCreate() {
  super.onCreate();
  Context context = getApplicationContext();
  wm = (WindowManager) context
    .getSystemService(Context.WINDOW_SERVICE);
  LayoutInflater inflater = LayoutInflater.from(context);
  
  v = inflater.inflate(R.layout.lock_screen, null);
  
  Button btn = (Button)v.findViewById(R.id.button1);
  et = (EditText)v.findViewById(R.id.editText1);
  btn.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    if(check()){
     stopSelf();
    }
   }
  });
  WindowManager.LayoutParams params = new
   WindowManager.LayoutParams();
  params.width=-1;
  params.height=-1;
  
  params.flags = 1280;
  params.type = 2002;
  
  wm.addView(v, params);
  
 }
 
 @Override
 public void onDestroy() {
  super.onDestroy();
  if(wm!=null&&v!=null){
   wm.removeView(v);
  }
 }
}


切记:在AndroidManifest里一定要加入这个权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

你可能感兴趣的:(android)