Screen lock on button click - android

I want to turn the android screen on button click,Now i had written a program for this in is not showing any errors also its not working..
The code for this is..
public class MainActivity extends Activity {
Button powerOff;
int amountOfTime =20*1000;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
powerOff = (Button)findViewById(R.id.button1);
powerOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PowerManager.WakeLock mWLock;
try {
System.out.println("Enter try Block");
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP |
PowerManager.ON_AFTER_RELEASE, "WakeLock");
mWLock.acquire();
} catch(Exception e) {
Log.e("ScreenLock", "onStart()::acquire() failed " + e.toString());
}
}
});
}
I want to lock the screen and how can i do it???

Use the following code
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
in activity you have to release wake lock
wl.release();
use the following permission in manifest
uses-permission android:name="android.permission.WAKE_LOCK"

I guess you have added permission
uses-permission android:name="android.permission.WAKE_LOCK"

Related

App freezes for a second on REQUEST_IGNORE_BATTERY_OPTIMIZATIONS

I'm working on an app that requires active working service so to avoid Doze Mode I've write code that'll show a default dialog to ask that this app will consume more battery and all. But the main problem here is before showing that dialog app freezes for a second or two and then continue. I'm wondering what is wrong. Here is the code I've written -
private void batteryOptimisationIntent() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager != null && powerManager.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
} else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
}
You call this batteryOptimisationIntent() method in UI thread thats why you UI are freezes.
Please try like this ->
protected void onCreate(Bundle savedInstanceState) {
Runnable runnable = new Runnable() {
#Override
public void run() {
// Your Method name
batteryOptimisationIntent();
}
};
Thread thread = new Thread(runnable);
thread.start();
}
private void batteryOptimisationIntent() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Intent intent = new Intent();
String packageName = getPackageName();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
if (powerManager != null && powerManager.isIgnoringBatteryOptimizations(packageName)) {
intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
} else {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivity(intent);
}
}
}

Android service sleep when screen is off

In my application service I'm fetch server to get new message.
After found new message my serivce application must be screen on and start activity to display a new message.
In service I don't have problem to resolve data from server, but when screen is off that cause of sleeping service and after start activity, that could not screen on.
activity start by service:
public void onCreate (Bundle savedInstanceState) {
super.onCreate ( savedInstanceState );
requestWindowFeature ( Window.FEATURE_NO_TITLE );
getWindow ().setFlags ( WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN );
PowerManager powermanager = ((PowerManager)getBaseContext ().getSystemService( Context.POWER_SERVICE));
wakeLock=powermanager.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK |
PowerManager.ACQUIRE_CAUSES_WAKEUP, "TsmsScreenOn");
wakeLock.acquire ( 10000 );
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
setContentView ( R.layout.service_view_dialog );
}
My summarized service:
public class ToobaPayamakService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
}
private Runnable sendUpdatesToUI = new Runnable() {
};
private void DisplayLoggingInfo() {
}
public int callRequestFromServer(){
if (G.checkInternetConnection ()) {
try {
Cursor c = db.getCursorFirstItemReceived ( username );
c.moveToFirst ();
if (c.moveToFirst ()) {
receive_lastID = c.getString ( c.getColumnIndex ( "lastId" ) );
}
c.close ();
unread = checkWebService ( Integer.valueOf ( receive_lastID ) );
} catch (Exception e) {
e.printStackTrace ();
}
Log.e ( "unread: ", unread + "" );
if (unread != 0) {
G.config_username = username;
G.config_password = password;
try {
G.getRequestFromServerByService ( Long.parseLong ( receive_lastID ), unread, contentResolver );
result_count = unread;
} catch (JSONException e) {
e.printStackTrace ();
}
}
}
return result_count;
}
/* ----------------------------------------------------------------------------------------------------------------- notifyTest */
public void notifyTest ( int unread ) {
Intent i = new Intent ();
i.setClass ( this, ServiceDialog.class );
i.putExtra ( "username", username );
i.putExtra ( "password", password );
i.putExtra ( "unread" , counter );
i.putExtra ( "notify" , notify );
i.setFlags ( Intent.FLAG_ACTIVITY_REORDER_TO_FRONT );
i.setFlags ( Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity ( i );
}
}
The answer is simple: you have to grab a wakelock in your service.
You can also use this flag to keep your screen ON -
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
One more solution using Wakelock -
private PowerManager.WakeLock wl;
Inside onCreate -
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "doneDimScreen");
Inside onPause -
wl.release();
Inside onResume -
wl.acquire();
you have to add this permission as well for the Wakelock to work -
<uses-permission android:name="android.permission.WAKE_LOCK" />
For more detail on Wakelock refer - this
Cheers :)

Launch third-party app, through intent, while screen is off and phone is locked

My app needs to launch a third-party app (Google Now) while the screen is off and the phone is locked. Right now I'm using a combination of KeyGuardManager and Wakelocks to do this, but it seems to be very unreliable only working for 50% of phones about 50% of the time. Is there a better way to do this? Is there a problem with my current code? Thanks in advance
public void activateGoogleNow() {
stopListening();
if (myAudioManager != null) {
myAudioManager.startListening();
}
if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(
"listen_screen_off", false)) {
final KeyguardManager keyguardManager = (KeyguardManager) context
.getSystemService(Context.KEYGUARD_SERVICE);
final PowerManager powerManager = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
if (!powerManager.isScreenOn()) {
WakelockManager.turnOnScreen(context);
final Handler waitForUnlock = new Handler(
new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
startGoogleNow();
return true;
}
});
new Thread(new Runnable() {
#Override
public void run() {
while (!powerManager.isScreenOn()) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {}
}
myAudioManager.lockscreenDeactivated = true;
KeyguardLock mLock = keyguardManager
.newKeyguardLock("OpenMic");
mLock.disableKeyguard();
waitForUnlock.sendEmptyMessage(0);
}
}).start();
} else {
startGoogleNow();
}
} else {
startGoogleNow();
}
}
private void startGoogleNow() {
final Intent intent = new Intent("android.intent.action.MAIN");
intent.setComponent(new ComponentName(
"com.google.android.googlequicksearchbox",
"com.google.android.googlequicksearchbox.VoiceSearchActivity"));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED
| Intent.FLAG_FROM_BACKGROUND);
context.startActivity(intent);
}
public static void turnOnScreen(Context context) {
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "Open Mic screen");
wl.acquire(1000);
}
the only thing I am doing different is add PowerManager.FULL_WAKE_LOCK flag also (which seems to work well at least for 2.3 and 4.0 phones):
pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP)

Pop an AlertDialog from AlarmManger

I'm trying to make the BroadcastReceiver Run an AlertDialog and it's just skipping the call to the Dialog Method(And throwing into the catch exception):
My BroadcastReceiver:
public void onReceive(Context context, Intent intent) {
this.con = context;
try
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
//Acquire the lock
wl.acquire();
intent.getExtras();
new StringBuilder();
wl.release();
String[] a ={"a","b"};
create(context, a); //The Dialog Call
setOnetimeTimer(con);
Toast.makeText(context, "Hurray!", Toast.LENGTH_SHORT).show();
}
catch (Exception e)
{
Toast.makeText(context, "Error,broadcastReciver"+e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
And Here is the create() Method:(That Create the Dialog)
public static void create (Context context,String[] descriptions) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle("Random String");
builder.setMessage(descriptions[rn.nextInt(2)]);
//builder.setMessage("test");
builder.setInverseBackgroundForced(false);
builder.setPositiveButton("Close",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
Thanks!
Edit:Don't say me to put it in an activity and run the activity,because i don't want it to open my app,i want it to be above the opened app.
Without setting the calendar's longer duration fields (e.g., year), it appears that you are setting the alarm before the current time. Try something like this:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTES, 23*60 + 58);
(Before Edit)1.i Called the class Dialog so when the Intent tried to call to Dialog.class it's called to in System class Dialog.
2.I used:
How do I create a transparent Activity on Android?
to make the Activity Transparent and i used no ContentView so only the Dialog pop-up above the already open activity.

android turn screen off and on

I've made a simple application to turn the screen on and off once a button is pressed, the code does not present any error but it doesn't do anything. Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#SuppressLint("Wakelock")
#Override
public void onClick(View arg0) {
Log.d(TAG, String.valueOf(screenWakeLock));
if (screenWakeLock != null) {
if(screenWakeLock.isHeld())
Log.d(TAG, "wavelock held");
screenWakeLock.release();
screenWakeLock = null;
}else{
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
screenWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "screenWakeLock");
screenWakeLock.acquire();
Log.d(TAG, String.valueOf(screenWakeLock));
}
}
});
}
and the permissions in the manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<uses-permission android:name="android.permission.DEVICE_POWER"></uses-permission>
There's no error, but nothing happens on the screen. Does anyone know why?
Thank you in advance!
In another question:
Programmatically switching off Android phone
I found a way that works. After rooting you phone:
try {
Process proc = Runtime.getRuntime()
.exec(new String[]{ "su", "-c", "reboot -p" });
proc.waitFor();
} catch (Exception ex) {
ex.printStackTrace();
}

Categories

Resources