使用Service Android的KeyGuard锁定

时间:2013-01-11 08:36:04

标签: java android pattern-matching android-service

我有活动,其中我正在使用http://code.google.com/p/android-lockpattern/此库模式设计进行键锁,成功锁定活动按钮内的屏幕。但是当我实施一项服务以在一段时间后在后台执行相同的过程时。

问题是,当我从activity启动服务以执行锁定功能时,它会继续给我空指针

以下是我的主要活动代码。

package com.example.lockscreen_test;

import group.pals.android.lib.ui.lockpattern.LockPatternActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

     public class MainActivity extends Activity {
private static final int _ReqCreatePattern = 0;
// this is your preferred flag
private static final int _ReqSignIn = 1;
String pattern;
public Button btn_show_lock;
protected Object mHandler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (lockService.flag == false) {
        CreateNewPattern();
    }
    btn_show_lock = (Button) findViewById(R.id.button1);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void compare(View v) {
    lockScreen();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case _ReqCreatePattern:
        if (resultCode == RESULT_OK) {
            pattern =   data.getStringExtra(LockPatternActivity._Pattern);
            lockService.doNow = true;
        }
        break;
    case _ReqSignIn:
        if (resultCode == RESULT_OK) {
            // signing in ok
        } else {
            // signing in failed
        }
        break;
    }
}

public void lockScreen() {
    // startService(new Intent(this, lockService.class));

    try {
        Intent intent = new Intent(MainActivity.this,
                LockPatternActivity.class);
        intent.putExtra(LockPatternActivity._Mode,
                LockPatternActivity.LPMode.ComparePattern);
        intent.putExtra(LockPatternActivity._Pattern, pattern);
        startActivityForResult(intent, _ReqSignIn);
        Log.w("Locked", "ScreenLock");
    } catch (Exception e) {
        Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG)
                .show();
    }
}

public void CreateNewPattern() {
    // startService(new Intent(this, lockService.class));

    Intent intent = new Intent(MainActivity.this, LockPatternActivity.class);
    intent.putExtra(LockPatternActivity._Mode,
            LockPatternActivity.LPMode.CreatePattern);
    startActivityForResult(intent, _ReqCreatePattern);
    lockService.flag = true;
    startService(new Intent(this, lockService.class));
}

}

我的服务代码

package com.example.lockscreen_test;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;

import com.example.lockscreen_test.R.drawable;

public class lockService extends Service {

MainActivity main;

Notification _foregroundNotification;

final int _notification_id = 1;
public static Boolean flag = false;
public static Boolean doNow = false;

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    main = new MainActivity();
    // main.CreateNewPattern();
    // startForeground();

    Log.w("created", "Services !");
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    // main.lockScreen();
    if (doNow == true) {
        RepeatProcess();
    }
    return Service.START_REDELIVER_INTENT;
}

@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    Log.w("Destroyed", "Services destroyed!");
    super.onDestroy();
}

void startForeground() {

    int notificationIcon = drawable.ic_menu_chat_dashboard;
    String notificiationTickerText = "Service Started...";
    long notificationTimestamp = System.currentTimeMillis();
    _foregroundNotification = new Notification(notificationIcon,
            notificiationTickerText, notificationTimestamp);
    String titletext = "Sample Service";
    String bodytext = "Does lock ";

    Intent myactivity = new Intent(this, MainActivity.class);
    PendingIntent startmyactivitypendingintent = PendingIntent.getActivity(
            this, 0, myactivity, 0);
    _foregroundNotification.setLatestEventInfo(this, titletext, bodytext,
            startmyactivitypendingintent);
    startForeground(_notification_id, _foregroundNotification);
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

void RepeatProcess() {
    int delay = 5000; // delay for 5 sec.

    int period = 10000; // repeat every 10 sec.

    Timer timer = new Timer();

    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            main.lockScreen();
            System.out.println("done");

        }

    }, delay, period);

}

}

my menifest xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lockscreen_test"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="13"
    android:targetSdkVersion="17" />

<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.lockscreen_test.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service android:name=".lockService" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </service>

    <activity
        android:name="group.pals.android.lib.ui.lockpattern.LockPatternActivity"
        android:configChanges="orientation|screenSize|keyboard|keyboardHidden" />
</application>

下面是我的logcat错误我不知道为什么它一直给我空指针错误

AndroidRuntime(1683): FATAL EXCEPTION: Timer-001-11 08:29:31.689:
AndroidRuntime(1683): java.lang.NullPointerException
AndroidRuntime(1683): at   com.example.lockscreen_test.MainActivity.lockScreen(MainActivity.java:75)

AndroidRuntime(1683): at com.example.lockscreen_test.lockService$1.run(lockService.java:85)

AndroidRuntime(1683): at java.util.Timer$TimerImpl.run(Timer.java:284)

1 个答案:

答案 0 :(得分:0)

尝试更改lockScreen()方法,如下所示:

public void lockScreen() {
            // startService(new Intent(this, lockService.class));
            if(pattern != null){
                try {
                    Intent intent = new Intent(MainActivity.this,
                            LockPatternActivity.class);
                    intent.putExtra(LockPatternActivity._Mode,
                            LockPatternActivity.LPMode.ComparePattern);
                    intent.putExtra(LockPatternActivity._Pattern, pattern);
                    startActivityForResult(intent, _ReqSignIn);
                    Log.w("Locked", "ScreenLock");
                } catch (Exception e) {

                }
            }
            else{
                Log.w("Locked", "Pattern Is Null here");                    
            }
}

编辑:

在Manifest中更改您的活动声明,如下所示:

    <activity
        android:name="com.example.lockscreen_test.MainActivity"
        android:configChanges="orientation|keyboardHidden"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

感谢。