Taking a class that extends BroadcastReceiver alone - android

There are many examples of classes that extend BroadcastReceiver to be activated from another class through intent. Class is also extending from BroadcastReceiver that are activated in an event such as a received text message. My question is how to activate a class that extends BroadcastReceiver when you reach a specified time, for example 8:20 a.m. without an intent. Do not know if I explained.

As mentioned in this question:
Android Alarm Manager with broadcast receiver registered in code rather than manifest
You will need to use a pendingintent for this. I am not sure why you don't want to use an intent - could you explain further?

I have a project where I have a unique class called AlarmReceiver and I want to display a toast at a given time, or 9:01 pm example. Specifically, the class is as follows:
package org.secure.sms;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
int mSec = calendar.get(Calendar.MINUTE);
if((mHour == 9 && mSec == 1) {
Toast.makeText(context, "Alarm Receiver message", Toast.LENGTH_SHORT).show();
}
}
}

Related

How to get the battery level in background and announce it?

In my app, I want to get the battery level in the background because I want to announce it in the text to speech when the battery level is low or when the battery is full or at any level. I have used the broadcast receivers and can get the battery level but don't know how to get it in the background.
Anyone can help?
The thing that you want to achieve can be done via intent Service, if you dig in the docs you can find it yourself, here is the link Intent Service, This type of intent can be fired in the background and can be used to perform various simple operations such as yours, because they don't have any interface but rather just operations executed in background.
Also here is a video guide Background Services which you can use for yourself to get battery percentage and announce it after a certain condition
Edit 2:
(Nothing Required in XML as this is a background process/operation)
This is a code to get the battery percentage and announce it using Text to speech in broadcast receiver,
MainActivity.java
package com.example.text_to_speech;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent=new Intent(this,myBackgroundProcess.class);
intent.setAction("BackgroundProcess");
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,intent,0);
AlarmManager alarmManger= (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManger.setRepeating(AlarmManager.RTC_WAKEUP,0,10,pendingIntent);//change this time based on your liking which will fire the intent
}
}
customerclass- myBackgroundProcess.java
package com.example.text_to_speech;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.Locale;
import static android.content.Context.BATTERY_SERVICE;
public class myBackgroundProcess extends BroadcastReceiver {
private TextToSpeech mTTS;
#Override
public void onReceive(Context context, Intent intent) {
mTTS = new TextToSpeech(context.getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
int result = mTTS.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
} else {
BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
if(batLevel==100 || batLevel<=10 || batLevel==50)
speak(context,batLevel);
}
} else {
Log.e("TTS", "Initialization failed");
}
}
});
}
public void speak(Context context, int batlevel)
{
mTTS.setPitch(10);
mTTS.setSpeechRate(1);
String text=String.valueOf(batlevel);
mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
In Android Manifest Register the receiver and add intent filter to it as shown below (below application tag)
<receiver android:name=".myBackgroundProcess"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="BackgroundProcess"/>
</intent-filter>
</receiver>

How can I do something after Elapsed Time in Android?

I am new in programming.
I want to turn off wifi after 2h (I know how to turn it off) in the background
I googled and found out, that the Elapsed Real Timer is needed for that. I have also find this code and implemented it (this is the only code I have in my class) This class is called when the user selects something from a spinner dropdown:
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.widget.Toast;
/**
* Wird aufgerufen, wenn eine Zeit von der dropdown liste gewählt wurde
*/
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender); // 1*1000 --> 1s * 3600 --> 1h * 2 --> 2h
Toast.makeText(getApplicationContext(), "Das ist ein Text", Toast.LENGTH_SHORT).show();
}
}
Is the code until yet fine? And how can I turn wifi off after the elapsed timer?
And does this the elapsed timer only one time or is this like an interval?
Sorry for my english
Thanks
EDIT:
I did the steps, mentioned in the answer of "Deb" and it is still nothing happening
Here the code
Step 1: "Make a BroadcatReceiver extending WakefulBroadcastReceiver"
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.widget.Toast;
public class BroadCastReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
new BackgroundService(); // Step 4
}
}
Step 2: Make a service extending IntentService Class
Step 3: In your service inside onHandleIntent() write your code for switching the wifi off or on.
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.view.View;
import android.widget.Toast;
public class BackgroundService extends IntentService {
public BackgroundService() {
super("BackgroundService");
}
#Override
protected void onHandleIntent(Intent intent) {
wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(false);
} else {
wifiManager.setWifiEnabled(true);
}
}
Step 4: Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2 (the code is already in step 1)
Manifest file (receiver, service and permissions for wifi)
<manifest ..... ..... ....>
<application>
.....
<receiver android:name=".BroadCastReceiver" ></receiver>
<service android:name=".BackgroundService" android:exported="false"></service>
</application>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
</manifest>
EDIT 2
The class where I am executing startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SpinnerTimeOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).toString().equals("Zeit auswählen") || parent.getItemAtPosition(position).toString().equals("Select Time")){
//onNothingSelected(parent);
;
} else if (parent.getItemAtPosition(position).toString().equals("30min")){
startActivity(new Intent(SpinnerTimeOnItemSelectedListener.this, ElapsedRealtimeAlarm.class));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Wenn es einen ElapsedRealTimeAlarm gibt, soll er gecancelt werden
// Ansonsten nichts
;
}
}
ElapsedRealtimeAlarm's onCreate()
public class ElapsedRealtimeAlarm extends Activity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
Toast.makeText(getBaseContext(), "ElapsedRealTimeAlarm wurde aufgerufen", Toast.LENGTH_SHORT).show(); // just to check, that he called this class
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, BroadCastReceiver.class), 0);
long firstTime = SystemClock.elapsedRealtime(); // elapsedRealTime --> Zeit seitdem booten.
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime+2000, 10, mAlarmSender);
}
}
Make a BroadcatReceiver extending WakefulBroadcastReceiver .
Make a service extending IntentService Class.
In your service inside onHandleIntent() write your code for switching the wifi off or on.
Now go back to your BroadcastReceiver class and there inside onReceive() call your service that you made in step 2.
Your line of code
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, // die 2h (1*1000*3600*2) werden von der Bootzeit(firstTime) dazugerechnet
firstTime, 1*1000*3600*2, mAlarmSender);
This is responsible for running an alarmmanager repeatedly after every 2hrs.But if u want the alarm manager to run only once replace am.setRepeating() with am.set().
Your Code
PendingIntent mAlarmSender = PendingIntent.getService(ElapsedRealtimeAlarm.this,
0, new Intent(ElapsedRealtimeAlarm.this, ElapsedRealtimeAlarm.class), 0);
Replace PendingIntent.getService with the PendingIntent.getBroadcast and pass the reference of your BroadcastReceiver class you made in step 1
NOTE :Do not forget to write the receiver and service in your manifest otherwise it won't work
Update:
Inside your BroadcastReceiver's onReceive() call the service like this
Intent service=new Intent(context,BackgroundService.class);
startWakefulService(context, service);
this will call the onHandleIntent().
Update 2:
Replace getBaseContext() with this and change the PendingIntent.getService as
Intent i=new Intent(this, BroadCastReceiver.class);
PendingIntent alarmIntent=PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
Do the following it will usefull to you
Create a service that turn wifi & other operations
Create a broadcast receiver inside that onReceive method call the service
Create a pending intent and alarm for a time which you want ,when alarm time period eleapses then trigger the broadcast receiver.

How to use Elapsed Real Time in Android?

I want to develop an app. The app has a spinner dropdown. The dropdown has 3 option (30min, 1h, 2h). When for example 30min is pressed I want to start an elapsed Real Time for 30min and after that I want to turn off wifi, that means after 30min the wifi should be turned off.
The logcat shows me a NullPointer Exception.
Here is my code
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.SystemClock;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SpinnerTimeOnItemSelectedListener extends Activity implements AdapterView.OnItemSelectedListener {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
if(parent.getItemAtPosition(position).toString().equals("Zeit auswählen") || parent.getItemAtPosition(position).toString().equals("Select Time")){
onNothingSelected(parent);
} else if (parent.getItemAtPosition(position).toString().equals("30min")){
Intent intent = new Intent(SpinnerTimeOnItemSelectedListener.this, ConnectionManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(SpinnerTimeOnItemSelectedListener.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME, firstTime, 5000, pendingIntent);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// Wenn es einen ElapsedRealTimeAlarm gibt, soll er gecancelt werden
// Ansonsten nichts
;
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
And in this class the wifi should be managed (turned on/off)
public class ConnectionManager extends BroadcastReceiver {
/**
*
* #param context The Context in which the receiver is running.
* #param intent The Intent being received.
*/
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "I'm running", Toast.LENGTH_SHORT).show();
}
}
Error of the logcat:
07-24 17:35:17.503 5430-5430/com.falkenherz.abusufean.batterycooler E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.falkenherz.abusufean.batterycooler, PID: 5430
java.lang.NullPointerException
at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:104)
at android.app.PendingIntent.getService(PendingIntent.java:522)
at com.example.ali.turnoffwifi.SpinnerTimeOnItemSelectedListener.onItemSelected(SpinnerTimeOnItemSelectedListener.java:42)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:956)
at android.widget.AdapterView.access$200(AdapterView.java:49)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:920)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
The error is on this line:
PendingIntent pendingIntent = PendingIntent.getBroadcast(SpinnerTimeOnItemSelectedListener.this, 0, intent, 0);
How can I fix this problem?
Thanks
Here is little bit concept problem:
elapsedRealtime() and elapsedRealtimeNanos() return the time since the system was booted, and include deep sleep. This clock is guaranteed to be monotonic, and continues to tick even when the CPU is in power saving modes, so is the recommend basis for general purpose interval timing.
check : http://developer.android.com/reference/android/os/SystemClock.html
and here your task you can done with the Chronometer class. You can bind it to SystemClock.elapsedRealtime() using setBase(). Another way could be if you use Handler inside an Activity and using the sendEmptyMessageDelayed() method with value 1000*60*30(30 minutes) to update your timer.
Or if you Want to use pending intent Then you have to
1)getcurrenttime in Millis using calenderinstance
2)convert 30 minutes to millis and
3) Total millis =currenttimeinmillis+30minutes in millis
then set your Total millis to alarm manager object
also check :android service using SystemClock.elapsedRealTime() instead of SystemClock.uptimeMillis() works in emulator but not in samsung captivate?
Thats it....

Broadcast Receiver onReceive method not called when screen/cpu goes off

I am working on an application that will notify me (by playing a ringtone) that battery level has reached certain level. Level is configurable. For this I have created an activity that starts a service which in turn registers a receiver for ACTION_BATTERY_CHANGED.
MyActivity -> MyService -> MyBrodcastReceiver [ACTION_BATTERY_CHANGED] -> onReceive() -> if(Battery Level <= MyValue) -> play ringtone
Everything works fine as long as screen is on but as soon as phone is locked and screen goes off or CPU sleeps the broadcast receiver’s onReceive method doesn’t get called and when I unlock phone again everything works. I verified this with logging.
Is it that onReceive method for ACTION_BATTERY_CHANGED gets called only when phone screen is on and stops when phone sleeps?
I even tried using Wake Lock in onReceive method but that didn’t work 
[I am testing with ICS (4.0.4)]
import android.app.Service;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class BatteryMeterService extends Service {
private BatteryStatusReceiver batteryStatusReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
batteryStatusReceiver = new BatteryStatusReceiver(null);
registerReceiver(batteryStatusReceiver, intentFilter);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(batteryStatusReceiver);
}
}
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import com.amol.bm.BatteryMeterUtility.NotificationInfo;
public class BatteryStatusReceiver extends BroadcastReceiver {
private BatteryMeterUtility batteryMeterUtility;
public BatteryStatusReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float fPct = (level / (float)scale) * 100;
int levelPct = (int)fPct;
boolean prefAlertLowBattery = sharedPrefs.getBoolean("prefAlertLowBattery", true);
if(prefAlertLowBattery) {
String prefAlertLowBatteryValue = sharedPrefs.getString("prefAlertLowBatteryValue", "20");
int lowBatteryValue = Integer.parseInt(prefAlertLowBatteryValue);
if(levelPct <= lowBatteryValue && iStatus != BatteryManager.BATTERY_STATUS_CHARGING) {
notificationInfo.icon = R.drawable.low_battery;
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "BM WakeLook");
wakeLock.acquire();
batteryMeterUtility.playAlertRingtone(alertRingtone);
wakeLock.release();
}
}
}
}
You should give WAKE_LOCK Permission to your service running in background so that even when the phone is Idle or goes off your service keeps on running. hope you got it let me know if unclear
Finally I used Alarm Manager with RTC_WAKEUP to solve this problem. http://developer.android.com/reference/android/app/AlarmManager.html

How to wake up my App Periodically

I want to make an functionality, like reminder, in Android.
I want to start-up my app/activity, when it is not running, or its UI is invisible.
It is some-thing like same as reminder, that wakes ups the app at desired time.
I have not worked with any type of background task or service,
so I haven't any idea that what to do,
or what type of classes or demos should be studied by me?
Can any one give me some suggestions with demos or tutorials links.
Thanks, in advance.
Hi use the following code. This is service. By using pending Intent with alarm manager you can open your UI at your needed time.
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
public class ScheduleCheckService extends Service{
private Timer timer;
final int REFRESH=0;
Context context;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
context=this;
//==============================================
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
}
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
void PendingIntentmethod()
{
Intent myIntent = new Intent(context, YOURCLASS.class);
pendingIntent = PendingIntent.getActivity(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
}
}
Start the service and stop the service when you want and also dont forget to register it in manifest file.
Have a look at the Android Service class.
http://developer.android.com/reference/android/app/Service.html
From this Service you can periodically start (using a TimerTask) an Intent to open your App or just set a Notification, from which the user can open the App with the desired Activity. I would prefer the second option, because he user doesn't want an Application just to be opened at some time.
Here is a simple Service Tutorial:
http://www.vogella.com/articles/AndroidServices/article.html

Categories

Resources