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....
Related
I want to start service on reboot of the device.
First I used broadcast receiver.It worked on my android phone having version 7. But I want to implement it on Xixun controller which is android based having version 4.0.3
Broadcast receiver did not work. I have gone through reading that, for API levels below 26, one should use WakefulBroadcastReceiver. When I did that, it worked on my phone but not on Xixun controller.
The process to reboot Xixun controller is just to power on and power off using supply.I have also used power intent of broadcast receiver. But it didn't work because device is batteryless.
What would be reason behind my service is not working?
[manifest receiver]
Following is service code
package com.example.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast myToast =Toast.makeText(this,"service started",Toast.LENGTH_LONG);
myToast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
myToast.setDuration(Toast.LENGTH_LONG);
myToast.show();
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
When I used broadcast receiver, codes are same except basic syntax.
I want to repeat some sort of code on a particular time only i.e at xx:02,xx:17,xx:32,xx:47
i tried using AlarmManager class that brodcast a pending intent.
My problem is that- the following code runs fine on HTC desire 816 and Samsung Galaxy Grand neo but not Gionee M2.
MainActivity.java
package com.example.alarmexample;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int newmin=0;
SimpleDateFormat f= new SimpleDateFormat("dd-MM-yy HH:mm");
long current= System.currentTimeMillis();
String d= f.format(current);
String time[]=d.split(":");
int min = Integer.parseInt(time[1]);
if(min>=0 && min<=2)
{
newmin=2-min;
}
else if(min<=17)
{
newmin=17-min;
}
else if( min<=32)
{
newmin=32-min;
}
else if(min<=47)
{
newmin=47-min;
}
else
{
newmin=62-min;
}
long newtime= current+(newmin * 60 * 1000);
Intent intent = new Intent(this,MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, newtime, 15*60*1000 , pendingIntent);
Toast.makeText(this, "Alarm set in " + newmin + " miniuts",
Toast.LENGTH_LONG).show();
}
}
MyBroadcastReceiver.java
package com.example.alarmexample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context
.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
Output on HTC desire 816 and Samsung Galaxy Grand Neo is-
Time | result
xx:02 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:17 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:32 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:47 | toast showing message "Time is up!!!!." with 2 Second vibration
But on Gionee M2 -
Time | result
xx:00 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:02 | nothing happens
xx:17 | nothing happens
xx:20 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:32 | nothing happens
xx:40 | toast showing message "Time is up!!!!." with 2 Second vibration
xx:47 | nothing happens
Why the behavior is different when have a same peace of code..
Is am doing something wrong? or anything else..
please tell me, thanks in advance.
Use setExact(int, long, PendingIntent) if you want to have the alarm fired exactly at specified interval.
The cause of your trouble is that you are using a API call to the AlarmManager that is defined as inexact. If you look at the documentation for setInexactRepeating(int, long, long, PendingIntent) you will find this passage.
Your alarm's first trigger will not be before the requested time, but
it might not occur for almost a full interval after that time. In
addition, while the overall period of the repeating alarm will be as
requested, the time between any two successive firings of the alarm
may vary. If your application demands very low jitter, use one-shot
alarms with an appropriate window instead; see setWindow(int, long,
long, PendingIntent) and setExact(int, long, PendingIntent).
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.
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 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