Wednesday, July 10, 2013

How to unlock the Android Phone programmatically? | Code for start another activity when phone screen is lock | Alarm Manager in Android | Play Alarm in Android on scheduled time

Hello Friends,

I am Going to share very important and useful code for start your application when phone is lock. This demo will unlock your phone lock and start another activity class form first screen.

For this I am using Alarm manager which will start your application after every 10 second.


Intent intent = new Intent(this, NextActivity.class);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 12345,
    intent, PendingIntent.FLAG_CANCEL_CURRENT);
  AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
  /**
   * if you want start your application only one time un-comment below
   * line code and comment next line code
   */
  // am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
    1000 * 15, pendingIntent); 
 
 
And this is the code which will unlock your phone lock-
 
KeyguardManager km = (KeyguardManager) context
     .getSystemService(Context.KEYGUARD_SERVICE);
   final KeyguardManager.KeyguardLock kl = km
     .newKeyguardLock("MyKeyguardLock");
   kl.disableKeyguard();

   PowerManager pm = (PowerManager) context
     .getSystemService(Context.POWER_SERVICE);
   WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
     | PowerManager.ACQUIRE_CAUSES_WAKEUP
     | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
   wakeLock.acquire(); 
 
 

Full code

 

(A)MainActivity.java


package com.manish.nevigationapp;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  TextView text = (TextView) findViewById(R.id.textView1);
  text.setText("First Page");

  // Create a new PendingIntent and add it to the AlarmManager
  Intent intent = new Intent(this, NextActivity.class);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 12345,
    intent, PendingIntent.FLAG_CANCEL_CURRENT);
  AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
  /**
   * if you want start your application only one time un-comment below
   * line code and comment next line code
   */
  // am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
  am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
    1000 * 15, pendingIntent);
 }

} 
 

(B)activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout> 
 

(C)NextActivity.java


package com.manish.nevigationapp;

import java.io.IOException;

import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;

public class NextActivity extends Activity {
 private MediaPlayer mPlayer;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_next);

  Button stopAlarm = (Button) findViewById(R.id.stopAlarm);
  stopAlarm.setOnTouchListener(new OnTouchListener() {
   public boolean onTouch(View arg0, MotionEvent arg1) {
    mPlayer.stop();
    finish();
    return false;
   }
  });

  playSound(this, getAlarmUri());
 }

 private void playSound(Context context, Uri alert) {
  mPlayer = new MediaPlayer();
  try {
   // unlock screen
   KeyguardManager km = (KeyguardManager) context
     .getSystemService(Context.KEYGUARD_SERVICE);
   final KeyguardManager.KeyguardLock kl = km
     .newKeyguardLock("MyKeyguardLock");
   kl.disableKeyguard();

   PowerManager pm = (PowerManager) context
     .getSystemService(Context.POWER_SERVICE);
   WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
     | PowerManager.ACQUIRE_CAUSES_WAKEUP
     | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
   wakeLock.acquire();
   // start alarm
   mPlayer.setDataSource(context, alert);
   final AudioManager audioManager = (AudioManager) context
     .getSystemService(Context.AUDIO_SERVICE);
   if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
    mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
    mPlayer.prepare();
    mPlayer.start();
   }
  } catch (IOException e) {
   System.out.println("Unable to play!");
  }
 }

 // Get an alarm sound.

 private Uri getAlarmUri() {
  Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
  if (alert == null) {
   alert = RingtoneManager
     .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
   if (alert == null) {
    alert = RingtoneManager
      .getDefaultUri(RingtoneManager.TYPE_RINGTONE);
   }
  }
  return alert;
 }
} 
 

(D)activity_next.xml


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center" >
 
    <Button
        android:id="@+id/stopAlarm"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="stop alarm" />
 
</RelativeLayout> 
 

(E)AndroidManifest.xml


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

    <uses-sdk
        android:minSdkVersion="8"
        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.manish.nevigationapp.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>
        <activity android:name="com.manish.nevigationapp.NextActivity" />
    </application>

</manifest> 
 
 
Thanks!
Please put your suggestion and comment!

20 comments:

  1. Your code for unlocking the device programmatically works but have you tried pressing HOME button as soon as the device is unlocked? The device locks again and unlocks only if the user inputs the password.

    ReplyDelete
    Replies
    1. No No It never ask for password until you did not stop this app from setting option manually..

      Delete
    2. The device locks again and unlocks only if the user inputs the password.

      Delete
    3. Hi Manish,
      The device locks again after some time. Is it a temporary unlock we are doing?
      And now KeyguardLock is deprecated.

      Delete
    4. @Dinesh, it will unlock your phone until the app is running in your phone. And yes it is deprecated now, please check on android developer website if they have anything new.

      Delete
  2. Hi
    Manish...i am new to android..up to some extent i learned the topics by you...will u provide any information rgarding web services and google maps(finding static and dynamic location)

    ReplyDelete
    Replies
    1. I have many demo on my blog for Google map try them.
      And for web services see my post-
      http://www.androidhub4you.com/2012/09/consuming-rest-web-services-in-android.html

      http://www.androidhub4you.com/2012/09/consuming-ksoap-web-services-in-android.html

      Delete
  3. Hi Manish,
    Do you know how to lock and unlock an android phone(multiuser phone) using password and username?
    have you any idea? please help me

    ReplyDelete
    Replies
    1. Hi Hayfa!
      I don't have any idea about multiuser device infect still I did not see any device like that. Can you please tell me any device and brand name so I can try to help you?

      Delete
  4. Can u help me how to lock the screen on click of a button from the activity?

    ReplyDelete
    Replies
    1. please check this link hope it will help-
      http://stackoverflow.com/questions/4545079/lock-the-android-device-programatically

      Delete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Hi, Thanks for the tutorial first of all. But i tried this (unlock the screen) but it works only if there is no password/lock pattern enabled in phone settings. I installed my program on my device and when there is no lock pattern it works fine. but if there is the screen is not unlocked. Is it impossible to unlock a pattern locked screen or is there a workaround?

    Read more: http://www.androidhub4you.com/2013/07/how-to-unlock-android-phone.html#ixzz2sisOBUIc

    ReplyDelete
  7. Hi,Thanks for this code it is working fine ....can we run the camera in services ? if we can please provide link i am trying to create hidden camera .

    ReplyDelete
  8. i want to set screen password for stolen mobile using SMS (BroadcastReceiver, any idea please :) ?

    ReplyDelete
    Replies
    1. Yes sure you can. First you need to create a lock application.
      Seconed create a broadcast reciver inside that whic will know to app if sim card is change or device reboot. And then in background you can send a sms to any perticuler device or using web service you can activate the lock..

      Delete
    2. First : Thank you very much...
      second : may you clarify your answer please,or any help in code :) .

      Delete
    3. First : Thank you very much
      second : may you clarify your answer please,, any help in code :) :) .

      Delete