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.
Related
I am trying to build an application which checks for notification files on a server, every hour. I used the alarm manager class to implement this. But I am unable to implement the automatic start on reboot part. I want that the alarm should run periodically after reboot. Can some one please tell me how to go about doing it.
This is my MyAlarmReceiver Class.
package com.example.quickstart;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.example.quickstart.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, NotificationService.class);
// i.putExtra("username", username);
context.startService(i);
}
}
This is my NotificationBootReceiver Class.
package com.example.quickstart;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class NotificationBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Construct an intent that will execute the AlarmReceiver
Intent i = new Intent(context, MyAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every every half hour from this point onwards
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pIntent);
// alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
// AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
AndroidManifest file looks like this(it's not the complete manifest file but the relevant parts)
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".NotificationBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
The notifications are working fine, but what I want is the start notifications automatically on reboot feature. When i reboot the notification feature does not work,i.e, the alarm does not go off. And also the android documentation says (this only works if the app has already been launched by the user at least once) , is there a way to set the alarm automatically on reboot without launching the app. Any help appreciated. Thanks in advance
Documentation link android devs link
(Go to: Start an alarm when the device restarts)
No it isn't possible to set the alarms without starting the app even once. Once the app has been started the alarms can be triggered.
I have read the document http://www.javacodegeeks.com/2012/08/android-broadcast-receiver-enable-and.html,
I think the Broadcast receiver AlarmManagerBroadcastReceiver will keep run even if I exit the app,
In order to stop the Broadcast receiver, I have to run the app again and click Disable Broadcast Receiver button, right?
<LinearLayout 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:orientation='vertical'>
<Button
android:layout_width='fill_parent'
android:layout_height='wrap_content'
android:padding='#dimen/padding_medium'
android:text='#string/start_repeating_alarm'
android:onClick='startRepeatingAlarm'
tools:context='.EnableDisableBroadcastReceiver' />
<Button
android:layout_width='fill_parent'
android:layout_height='wrap_content'
android:padding='#dimen/padding_medium'
android:text='#string/cancel_alarm'
android:onClick='cancelAlarm'
tools:context='.EnableDisableBroadcastReceiver' />
<Button
android:layout_width='fill_parent'
android:layout_height='wrap_content'
android:padding='#dimen/padding_medium'
android:text='#string/enable_broadcast_receiver'
android:onClick='enableBroadcastReceiver'
tools:context='.EnableDisableBroadcastReceiver' />
<Button
android:layout_width='fill_parent'
android:layout_height='wrap_content'
android:padding='#dimen/padding_medium'
android:text='#string/disable_broadcast_receiver'
android:onClick='disableBroadcastReceiver'
tools:context='.EnableDisableBroadcastReceiver' />
</LinearLayout>
<resources>
<string name='app_name'>EnableDisableBroadcastReceiver</string>
<string name='enable_broadcast_receiver'>Enable Broadcast Receiver</string>
<string name='disable_broadcast_receiver'>Disable Broadcast Receiver</string>
<string name='start_repeating_alarm'>Start Repeating Alarm</string>
<string name='cancel_alarm'>Cancel Alarm</string>
<string name='menu_settings'>Settings</string>
<string name='title_activity_enable_disable_boradcast_receiver'>EnableDisableBoradcastReceiver</string>
</resources>
package com.code4reference.enabledisablebroadcastreceiver;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = 'onetime';
#Override
public void onReceive(Context context, Intent intent) {
//You can do the processing here update the widget/remote views.
StringBuilder msgStr = new StringBuilder();
//Format time.
Format formatter = new SimpleDateFormat('hh:mm:ss a');
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_SHORT).show();
}
}
package com.code4reference.enabledisablebroadcastreceiver;
import com.example.enabledisablebroadcastreceiver.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class EnableDisableBroadcastReceiver extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method gets called when 'Start Repeating Alarm' button is pressed.
* It sets the repeating alarm whose periodicity is 3 seconds.
* #param view
*/
public void startRepeatingAlarm(View view)
{
AlarmManager am=(AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);
//After after 2 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 4 , pi);
Toast.makeText(this, 'Started Repeating Alarm', Toast.LENGTH_SHORT).show();
}
/**
* This method gets called when 'cancel Alarm' button is pressed.
* This method cancels the previously set repeating alarm.
* #param view
*/
public void cancelAlarm(View view)
{
Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
Toast.makeText(this, 'Cancelled alarm', Toast.LENGTH_SHORT).show();
}
/**
* This method enables the Broadcast receiver registered in the AndroidManifest file.
* #param view
*/
public void enableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, 'Enabled broadcast receiver', Toast.LENGTH_SHORT).show();
}
/**
* This method disables the Broadcast receiver registered in the AndroidManifest file.
* #param view
*/
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, 'Disabled broadcst receiver', Toast.LENGTH_SHORT).show();
}
}
The broadcastreceiver should be fired, though it's technically not "running".
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();
}
}
}
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
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