how to set alarm when screen is off for android device? - java

Hi I want to set alarm notification when the mobile screen is off. My code is'
package com.my.timeout;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class ScreenON_OFF_ACTIVITY extends Activity
{
AlarmManager am;
private static final int REQUEST_CODE = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
onCreate1();
}
public void onCreate1() {
// initialize receiver
System.out.println("onCreate1 ");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
System.out.println("onCreate ");
}
#Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.screenOff) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");
} else {
// this is when onPause() is called when the screen state has not changed
System.out.println("this is when onPause() is called when the screen state has not changed ");
display_alarm();
}
super.onPause();
}
#Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.screenOff) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
System.out.println(" this is when onResume() is called when the screen state has not changed ");
}
super.onResume();
}
}
ScreenReceiver.java
package com.my.timeout;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class ScreenReceiver extends BroadcastReceiver
{
public static boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("onReceive ");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
System.out.println("SCREEN TURNED OFF on BroadcastReceiver");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
screenOff = false;
System.out.println("SCREEN TURNED ON on BroadcastReceiver");
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}
}
UpdateService.java
package com.my.timeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
public class UpdateService extends Service {
public void onCreate() {
super.onCreate();
// register receiver that handles screen on and screen off logic
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
System.out.println("Screen is off");
} else {
System.out.println("Screen is on");
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Now i want to set alarm when the screen has been go off. How can i do this.Can anybody tell me? thanks in advance.

Related

How to prevent a service from terminating?

MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends WearableActivity {
private TextView mTextView;
private static MainActivity instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
final TextView text = findViewById(R.id.text);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (text.getText().toString().equals("Started")) {
text.setText("Stoped");
stopService(new Intent(MainActivity.this,service.class));
} else {
text.setText("Started");
startService(new Intent(MainActivity.this,service.class));
}
}
});
}
public static MainActivity getInstance() {
return instance;
}
public void showToast(String toastMsg){
Toast.makeText(MainActivity.this, toastMsg, Toast.LENGTH_SHORT).show();
}
}
Service.java
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.MainThread;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class service extends Service {
private boolean started = false;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("serviceTest", "Service started by user.");
start();
return START_STICKY;
}
#Override
public void onDestroy() {
//Toast.makeText(this, "Service destroyed by user.", Toast.LENGTH_LONG).show();
Log.i("serviceTest", "Service destroyed by user.");
stop();
super.onDestroy();
}
private Timer timer;
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
if(started) {
start();
}
Log.i("serviceTest", "ServiceCalled!");
}
};
public void start() {
if(timer != null) {
return;
}
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, 0, 10000);
}
public void stop() {
timer.cancel();
timer = null;
}
}
The code runs okay for about 13 or 14 times (i.e. the timer keeps on running for about 13 or 14 times) but suddenly the service stops and onDestroy is called.
Also, during debugging, I have noticed one strange condition: If I delete/comment the onDestroy() method form the code then the service runs always. It never closes on its own. (it only closes upon user input, which is fine)
Please suggest a solution so that the services do not get killed/ destroyed. Or if the OS/ System kills it, then the service starts again on its own.
Thnx
You will have to turn that background service into a foreground service, because of the limitations called Background Execution Limits that started from android Oreo.
Please check out this link for more better understanding: https://developer.android.com/about/versions/oreo/background

How can i create a broadcast receiver?

This is my first time using the stackoverflow
I am creating a chat program but only coding the broadcast receiver and receiving message notification left. I created an exampleapp for my intent but it only works when app is open. How can i simply create a broadcast receiver?
I am not getting error
My MainActivity:
package com.example.backgroundservice;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.widget.Toast;
import com.example.backgroundservice.R;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, BackgroundService.class));
Toast.makeText(this, "Intent Başladı!", Toast.LENGTH_LONG).show();
}
}
(I did not added my other codes because i am getting error and i can not solve because i am coding on android)
My Intent:
import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
//handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}```

Media Player not playing sound properly in Android on charger connection

I am new to software developing and i am trying to make an application that will play a sound when it charges. The first time i connect it to the charging cable, it plays the sound two times, which is not expected. Also, when i connect and disconnect the cable too quick, it also plays it twice.
Does anyone know the solution to this problem?
package com.mccharginggimmick;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.os.BatteryManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
IntentFilter intentFilter;
BroadcastReceiver broadcastReceiver;
MediaPlayer mediaPlayerOff;
MediaPlayer mediaPlayerOn;
boolean playedOnceOn;
boolean playedOnceOff;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
View decorView = getWindow().getDecorView();
int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
decorView.setSystemUiVisibility(uiOptions);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging){
onCharge();
}
else{
onDisconnect();
}
}
};
MainActivity.this.registerReceiver(broadcastReceiver, intentFilter);
}
public void onCharge(){
if(!playedOnceOn){
imageView.setVisibility(View.INVISIBLE);
mediaPlayerOn = MediaPlayer.create(this, R.raw.btnon);
mediaPlayerOn.start();
mediaPlayerOn.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOn.stop();
playedOnceOn = true;
playedOnceOff = false;
}
});
}
}
public void onDisconnect(){
if(!playedOnceOff){
imageView.setVisibility(View.VISIBLE);
mediaPlayerOff = MediaPlayer.create(this, R.raw.btnoff);
mediaPlayerOff.start();
mediaPlayerOff.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayerOff.stop();
playedOnceOff = true;
playedOnceOn = false;
}
});
}
}
}
define isCabelConnected inside class
boolean isCabelConnected = false;
then in your onClick
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
boolean isFullCharged = status == BatteryManager.BATTERY_STATUS_FULL;
if(isCharging && !isCabelConnected){
onCharge();
isCabelConnected = true;
} else if (isFullCharged && isCabelConnected){
onCharge();
}
else{
onDisconnect();
isCabelConnected = false;
}
this code will make a sound when cable connected and another sound when full charge

Android Bluetooth Discovery not working

I am trying to list bluetooth devices available periodically. The idea is to run the startDiscovery() fuction every 4 secs and list the visible devices.
package com.neondude.cupid;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
public class MainActivity extends Activity {
Timer mTimer;
private ListView listView;
private ArrayList<String> mDeviceList = new ArrayList<String>();
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> BTArrayAdapter;
Handler mHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
BTArrayAdapter = new ArrayAdapter<String>(this,R.layout.list_view);
listView.setAdapter(BTArrayAdapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
private void startTimer(){
mTimer = new Timer();
mTimer.scheduleAtFixedRate(new Mytask(), 4000, 1000 * 5);
}
class Mytask extends TimerTask {
#Override
public void run(){
mHandler.post(new Runnable(){
#Override
public void run(){
find();
}
});
}
}
public void find(){
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
mBluetoothAdapter.startDiscovery();
registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
mBluetoothAdapter.startDiscovery();
}
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
short rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI,Short.MIN_VALUE);
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress() + "\n" + rssi);
BTArrayAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
I have included the startDiscovery() function in the timertask handler. But when i do this , the devices and not listed in my listView.
You should check if the bluetooth is on, and ask the user to turn on if is off:
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else{
startTimer();
}
You could start the timer onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (resultCode == RESULT_OK) {
// The user turn on the bluetooth
startTimer();
}
}
}
The startTimer() function is never called, therefore the timerTask does not begin.

How to keep IOIO connected when android screen goes off?

I am using the following code with IOIO to act as a motion detector, the problem is the IOIO is disconnected whenever my phone screen goes off! I do not want the screen to stay on all the time to keep the IOIO connected!
any solution please?
package com.LookHin.ioio_pir_motion_sensor;
import ioio.lib.api.AnalogInput;
import ioio.lib.api.DigitalOutput;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
import ioio.lib.util.IOIOLooper;
import ioio.lib.util.android.IOIOActivity;
import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends IOIOActivity {
private ToggleButton toggleButton1;
private TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButton1);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_about:
//Toast.makeText(getApplicationContext(), "Show About", Toast.LENGTH_SHORT).show();
Intent about = new Intent(this, AboutActivity.class);
startActivity(about);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
class Looper extends BaseIOIOLooper {
private DigitalOutput digital_led0;
private AnalogInput deigital_input;
int i = 0;
private float InputStatus;
#Override
protected void setup() throws ConnectionLostException {
digital_led0 = ioio_.openDigitalOutput(0,true);
deigital_input = ioio_.openAnalogInput(45);
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "IOIO Connect", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void loop() throws ConnectionLostException {
try{
digital_led0.write(!toggleButton1.isChecked());
InputStatus = deigital_input.getVoltage();
runOnUiThread(new Runnable() {
#Override
public void run() {
textView1.setText(String.format("%.02f",InputStatus)+" v.");
if(InputStatus >= 3.0){
textView1.setBackgroundColor(Color.RED);
if (i == 0){
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
i = 1;
};
}else{
textView1.setBackgroundColor(Color.TRANSPARENT);
i = 0;
}
}
});
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
#Override
protected IOIOLooper createIOIOLooper() {
return new Looper();
}
}
Option 1) Lock the screen so it always stays awake
public void onCreate(Bundle savedInstanceState) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
Option 2) Fix your response to onPause().
When the screen goes off the onPause() method is called and you should handle it as otherwise your activity will be closed.
#Override
protected void onPause() {
// Your code
super.onPause();
}
The onPause() normally calls the ioio.disconnect() so this should be overrode.
IOIOService let´s you run your code on the background even if application goes to the background.

Categories

Resources