i am trying to receive notifications when the screen goes on or off. i registered a broad cast receiver as shown below.
but when i press the button on the top right on the edge, the receiver is called but the log statements shown in the code does not show.
please tell me know to correct it
code:
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
switch (action) {
case Intent.ACTION_SCREEN_ON:
Log.w(TAG, SubTag.msg("onReceive", "Intent.ACTION_SCREEN_ON"));
break;
case Intent.ACTION_SCREEN_OFF:
Log.w(TAG, SubTag.msg("onReceive", "Intent.ACTION_SCREEN_OFF"));
break;
default:
Log.w(TAG, SubTag.msg("onReceive", "UNHANDLED CASE"));
break;
}
}
update:
i registerd the rceiver in onstart as follows:
registerReceiver(this.mScreenReceiver, new IntentFilter(intent.ACTION_SCREEN_ON))
registerReceiver(this.mScreenReceiver, new IntentFilter(intent.ACTION_SCREEN_OFF))
It's not a permission, you should register your broadcast in the manifest. Inside the application tags in the manifest, write this code but first change the name to your broadcast class name
<receiver android:name=".your_class_name_here" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>
Update
Try this broadcast
private BroadcastReceiver ScreenActions = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("BroadcastReceiver", "Broadcast is called");
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("BroadcastReceiver", "Screen ON");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("BroadcastReceiver", "Screen OFF");
}
}
};
and inside your onStart() register it
registerReceiver(ScreenActions, new IntentFilter(Intent.ACTION_SCREEN_ON));
registerReceiver(ScreenActions, new IntentFilter(Intent.ACTION_SCREEN_OFF));
Related
manifest:
<receiver android:name=".BatteryFullReceiver" >
<intent-filter>
<action android:name="android.intent.action.BATTERY_OKAY" />
</intent-filter>
</receiver>
Broadcastreceiver:
public class BatteryFullReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// String intentAction = intent.getAction();
// if(Intent.ACTION_BATTERY_OKAY.equalsIgnoreCase(intentAction)){
Toast.makeText (context, "Battery Full", Toast.LENGTH_LONG).show ();
Speaker.tts.speak("Battery full ,you can disconnect the usb now", TextToSpeech.QUEUE_ADD, null);
}
// }
}
i tried with battery low and that works.but Battery ok is not working. sometimes i used those code that's why i use comment for checking.but nothing is working.please help !!!
You've misspelled the intent action:
android.intent.action.ACTION_BATTERY_OKAY
There's a full example in the docs http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#DetermineChargeState
I am trying to create an application that could respond when the power button is pressed. To be more specific, which would respond to it when pressed 2 or 3 times.
For now, I tried the following:
public class SMSKey extends BroadcastReceiver{
static int countPowerOff = 0;
private Activity activity = null;
public SMSKey(Activity activity){
this.activity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
countPowerOff++;
}else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
if(countPowerOff == 2){
Intent i = new Intent(activity, SMSOptions.class);
activity.startActivity(i);
}
}
}
}
and in my manifest:
<receiver android:name=".SMSKey">
<intent-filter >
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
<action android:name="android.intent.action.ACTION_SHUTDOWN"/>
</intent-filter>
</receiver>
finally in my MainActivty.java:
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
SMSKey mReceiver = new SMSKey(this);
registerReceiver(mReceiver, filter);
Even though this works, it only works for the 1st time, it won't work on the 2nd or 3rd attempt when the power button is pressed. Why is that so ??
And another question: as you can see, I am using this KeyPress event in my MainActivity, which means the application is to be open all the time. Is there any other way that I can implement this without getting into the MainActivity.
This is not even an Android problem. You never reset your countPowerOff variable after you have received the 3 key presses. Even after having done that you must consider adding an alarm that will reset your countPowerOff variable to zero after some small timeout. It will allow you to avoid situations where the user does not intend to interact with your application and just presses the button, but it still gets counted.
As to your second question, try implementing an IntentService.
Here is the solution
public class MyReceiver extends BroadcastReceiver {
private static int countPowerOff = 0;
public MyReceiver (){
}
#Override
public void onReceive(Context context, Intent intent){
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
Log.e("In on receive", "In Method: ACTION_SCREEN_OFF");
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
Log.e("In on receive", "In Method: ACTION_SCREEN_ON");
}
else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e("In on receive", "In Method: ACTION_USER_PRESENT");
if (countPowerOff >= 2)
{
countPowerOff=0;
Toast.makeText(context, "MAIN ACTIVITY IS BEING CALLED ", Toast.LENGTH_LONG).show();
Intent i = new Intent(context, About.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
}
}
}
}
I want to stop a running service when a usb is unplugged.
inside my activity onCreate I check the intent for its action
if (getIntent().getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "************** USB unplugged stopping service **********");
Toast.makeText(getBaseContext(), "usb was disconneced", Toast.LENGTH_LONG).show();
stopService(new Intent(this, myService.class));
} else {
init();
}
And inside my manifest I have another intent filter
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
And this intent filter as well which is being called.
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
But the detach is not being called.
Hmmm.. ACTION_USB_DEVICE_DETACHED is fired when a USB device (not the cable) is detached from the phone/tablet. This is not something you want.
I do not know if there is a straight forward API for detecting USB cable connections, but you can use ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED to accomplish your goal.
Use following filters for your receiver:
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
And in your receiver, you can check the state and implement the logic you want:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
switch(intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)) {
case 0:
// The device is running on battery
break;
case BatteryManager.BATTERY_PLUGGED_AC:
// Implement your logic
break;
case BatteryManager.BATTERY_PLUGGED_USB:
// Implement your logic
break;
case BATTERY_PLUGGED_WIRELESS:
// Implement your logic
break;
default:
// Unknown state
}
}
}
You need to register a BroadcastReceiver
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
Log.d(TAG, "************** USB unplugged stopping service **********");
Toast.makeText(getBaseContext(), "usb was disconneced",
Toast.LENGTH_LONG).show();
stopService(new Intent(this, myService.class));
}
};
IntentFilter filter = new IntentFilter();
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(receiver, filter);
I am new to android, I have created intent's like this -
<receiver android:name=".IncommigCallListener" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<receiver android:name=".OutgoingCallReciever" >
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
Now i created a service like this -
<service
android:name=".CallLogger"
android:exported="false"/>
Class CallLogger
public class CallLogger extends IntentService {
public CallLogger(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
System.out.println("service started");
}
}
I don't want to have any activity in my application, i just want to start the service so that it can work in background and receive PHONE_STATE and NEW_OUTGOING_CALL intent.
When i start this application, it doesn't log anything on PHONE_STATE or NEW_OUTGOING_CALL intent.
How can start service in background without using any activity ?
Edit :
public class OutgoingCallReciever extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
}
and
public class IncommigCallListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
String incommingCallNumber = incomingNumber;
System.out.println("incomming call : " + incomingNumber);
break;
}
}
}
Just start service in your BroadcastReceiver's onReceive method. As you are registering BroadcastReceiver in AndroidManifist, It will always listen for Broadcasts even if application is not running (OS will run it for you).
Example
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MyService.class);
context.startService(service);
}
}
EDIT
To start a service on Boot completed you can do something like this.
1) Add permission to your Manifist :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
2) Register your Broadcast Receiver with BOOT COMPLETE action.
<receiver android:name="com.example.BootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
3) In BootBroadcastReceiver.java:
public class BootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context, MyService.class);
context.startService(serviceIntent );
}
}
You should be able to do something like this in your receiver.
public class OutgoingCallReciever extends BroadcastReceiver {
#Override
public void onReceive(Context ctx, Intent intent) {
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Intent service = new Intent(context, CallLogger.class);
context.startService(service);
}
}
You need to create an intent and call startService() on it to "launch" the service.
Also for what it's worth you should get out of the habbit of System.out.println use Log.d(tag,msg) to print debugging information to the logcat. You can switch the d to other letters if you want to print in different channels.
Why nothing gets printed is only due to the problem that System.out.println does not work in Android! Where do you think the background process will "print" this thing?
You need to change that to Log.d(tag, msg) and then check your logcat to see the output! Otherwise I guess your code might be running properly.
Here is the scenario :
An activity is displayed(active). If a phone call comes, the activity should receive the intent (send the "incoming call screen" to the background/hide it from the display) and itself remain visible to the user. I dont necessarily want to suppress the incoming phone call as I have read in a lot of questions that it is not possible with public APIs.
All I want is to somehow make that android's default incoming call screen hidden by my activity on the top.
This behavior is only required when my activity is visible which is NOT EQUAL TO having a PHONE_STATE broadcast receiver to start my activity. The latter question has been answered a number of times on SO.
Please help me. I have been looking for directions for almost a day now.
Thanks for your time.
This is how I solved it :
Manifest.xml
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
...
<receiver android:name=".MyPhoneBroadcastReceiver">
<intent-filter android:priority="99999">
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
<activity android:name=".LockScreenActivity" android:noHistory="true" android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.ANSWER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
MyPhoneBroadcastReceiver.java
public void onReceive(final Context context, Intent intent) {
Bundle extras = intent.getExtras();
...
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
new Handler().postDelayed(new Runnable() {
public void run() {
Intent intentPhoneCall = new Intent("android.intent.action.ANSWER");
intentPhoneCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentPhoneCall);
}
}, 100);
}
}
}
LockScreenActivity.java - A regular activity class with UI that shows up saying your screen is locked. It covers 100% area of your screen i.e. no navigation/status bar. Also the HOME/MENU keys have been disabled. This is how I achieved that : How can I detect user pressing HOME key in my activity?
P.S. : The trick is not the main logic but a 100ms delay. Without it your custom(home) lock screen will be removed by the system default incoming call screen everytime you get a call on the phone!
Ya sanjana is right that code works for me.. but instead of giving postdelay 100msec give more then 1.5 sec.. Bcoz to start incoming screen needs 800 to 1000msec.. I copied her code only but modified a bit.. Try this works fine...
#Override
public void onReceive(final Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
final String incomingNumber = extras.getString("incoming_number");
Handler callActionHandler = new Handler();
Runnable runRingingActivity = new Runnable() {
#Override
public void run() {
Intent intentPhoneCall = new Intent("android.intent.action.ANSWER");
intentPhoneCall.putExtra("INCOMING_NUM", incomingNumber);
intentPhoneCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intentPhoneCall);
}
};
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
callActionHandler.postDelayed(runRingingActivity, 2000);
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
callActionHandler.removeCallbacks(runRingingActivity);
// setResultCode(Activity.RESULT_CANCELED);
}
}
}
Then use PhoneStateListener at receiver class side.. I used like this....
/*********** My receiver class onCreate() contains ************/
TelephonyManager telephony = (TelephonyManager)
getSystemService(getApplicationContext().TELEPHONY_SERVICE);
telephony.listen(myListener, PhoneStateListener.LISTEN_CALL_STATE);
class MyPhoneStateListener extends PhoneStateListener {
Activity curActivity;
public MyPhoneStateListener(Activity _curActivity){
this.curActivity = _curActivity;
}
public void onCallStateChanged(int state, String incomingNumber) {
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
Log.i("TEST APP", "Cal End");
curActivity.finish();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
Log.i("TEST APP", "Hello");
break;
case TelephonyManager.CALL_STATE_RINGING:
Log.i("TEST APP", "Calling...");
break;
}
}
}