Home > Net >  How to keep the device awake?
How to keep the device awake?

Time:05-17

I am using a volley library in my app.and a json placeholder url for api call.i am measuring the time for response to come after an api call.i also want to keep the device or channel awake.which are the ways to implemnt this.

Main Activity Class -I tried to use Flag_keep_screen_on but still it didn't worked for me.

package com.example.volleydemo;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button Click;
    TextView responseText, timerText, timeLast;
    Date endTime;
    long startTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        endTime = Calendar.getInstance().getTime();
        Click = findViewById(R.id.button);
        Click.setOnClickListener(this);
        responseText = findViewById(R.id.textView);
        timerText = findViewById(R.id.textView2);
        timeLast = findViewById(R.id.textView3);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);


    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.button) {
            timerText.setVisibility(View.VISIBLE);
            timeLast.setVisibility(View.VISIBLE);
            startTime = System.currentTimeMillis();
            timeLast.setText("Request made at : "   getDate(startTime, "dd/MM/yyyy hh:mm:ss.SS"));


            int randomInt = ThreadLocalRandom.current().nextInt(1, 200);

            RequestQueue requestQueue;
            requestQueue = Volley.newRequestQueue(getApplicationContext());
            @SuppressLint("SetTextI18n") JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                    "https://jsonplaceholder.typicode.com/todos/"   randomInt,
                    null, response -> {
                try {

                    long elapsedTime = System.currentTimeMillis() - startTime;

                    timerText.setText("Request Completed within : "

                              convertSecondsToHMmSs(elapsedTime));

                    responseText.setVisibility(View.VISIBLE);
                    responseText.setText(" ID"   response.getString("id")   "\n Title-"  
                            response.getString("title")   "\n Completed-"  
                            response.getString("completed")   "\n User ID"
                              response.getString("userId")   "\n");

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }, error -> Log.d("myapp", "something went wrong"));
            requestQueue.add(jsonObjectRequest);
        }
    }
    @SuppressLint("DefaultLocale")
    public static String convertSecondsToHMmSs(long seconds) {
        long s = seconds % 60;
        long m = (seconds / 60) % 60;
        long h = (seconds / (60 * 60)) % 24;
        return String.format("%d Minute:d Second:d MilliSecond", h, m, s);
    }

    public static String getDate(long milliSeconds, String dateFormat) {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(milliSeconds);
        return formatter.format(calendar.getTime());
    }
}

XML CODE

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@ id/Click"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@ id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@ id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="@string/app_name"
        android:textStyle="bold"
        android:visibility="gone"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/button" />

    <TextView
        android:id="@ id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="@string/app_name"
        android:textStyle="bold"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@ id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@ id/textView3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="@string/app_name"
        android:textStyle="bold"
        android:visibility="gone"
        app:layout_constraintBottom_toTopOf="@ id/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@ id/textView2" />
</androidx.constraintlayout.widget.ConstraintLayout>

Manifest File- I have used wake lock permission here

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.volleydemo">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/Theme.VolleyDemo">
            <activity
                android:name=".MainActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

CodePudding user response:

You can try this

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyApp::MyWakelockTag");
wakeLock.acquire();

To release wake lock use wakelock.release()

Reference Keep the device awake https://developer.android.com/training/scheduling/wakelock

CodePudding user response:

Add Permission in Manifest

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

Code

override fun onCreate(savedInstanceState: Bundle?) {
    ............

     PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
     wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
    "MyApp::WakeLog");
     wakeLock.acquire();
}

 @Override
 public void onResume() {
   wakeLock.aquire();
 }

 @Override
 public void onDestroy() {
   wakeLock.release();
 }
  • Related