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);
}
}
}
}
Related
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));
I want to launch my application through dial pad.I am using the following code. For dial pad to launch application (in Broadcast receiver)
public class HiddenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
try{
// Toast.makeText(context,"Number Dialed",1).show();
Intent serviceIntent = new Intent(context,MainActivity.class);
serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(serviceIntent);
}
catch(Exception e)
{
Log.d(TAG, ""+e.getMessage());
}
While pressing key through dial pad I want to launch my main activity in which I used the following
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hidden_receiver);
//Intent call here
Intent intent=getIntent();
String message = intent.getStringExtra(MainActivity.TELEPHONY_SERVICE);
//text here
But when I press my code its dialed number disappear but neither dialer pad disappear nor MainActivity launches.
how can this issues be resolved?Help me out.....
Thanks.
Use the BroadcastReceiver as follows:
public class MyOutgoingCallHandler extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Extract phone number reformatted by previous receivers
String phoneNumber = getResultData();
if (phoneNumber == null) {
// No reformatted number, use the original
phoneNumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
}
if(phoneNumber.equals("1234")){ // DialedNumber checking.
// My app will bring up, so cancel the broadcast
setResultData(null);
// Start my app
Intent i=new Intent(context,MainActivity.class);
i.putExtra("extra_phone", phoneNumber);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Don't forget to register this receiver in your manifest
<receiver android:name="MyOutgoingCallHandler">
<intent-filter >
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
Also, include the permission:
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
Now, if you are ignoring the number checking in receiver, you'll get dialed number inside your MainActivity,
String phone=getIntent().getStringExtra("extra_phone");
if(!phone.equals(null)){
Toast.makeText(getBaseContext(), phone, Toast.LENGTH_LONG).show();
}
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.
I want to implement a minimal screen activity logger app. So, the application should run on the background (no user interaction) and it will log the screen on and off activities. I have started these codes, but it seems that I need to register my ScreenBroadcastReceiver broadcastreceiver. If I do it with the below code in main activity, it works. However, I do not want to register it in main because the user cannot launch the activity every time. So, where should i register my BroadcastReceiver so that the application works without user interaction?
oncreate in main activity
//I need to find another place to put these code, Where ???
//IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
//filter.addAction(Intent.ACTION_SCREEN_OFF);
//BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
//registerReceiver(screenOnReceiver, filter);
This is ScreenBroadcastReceiver, it will be triggered when the screen is on.
public class ScreenBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.w("OnReceive", "SCREEN IS ON");
}
}
}
This is the BootReceiver to run the program on the background itself.
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, ScreenListenerService.class);
context.startService(service);
//IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
//filter.addAction(Intent.ACTION_SCREEN_OFF);
//BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
//context.registerReceiver(screenOnReceiver, filter);
}
}
This is the manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name=".ScreenListenerService"></service>
<receiver android:name=".BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Update:
I added a service, but it does not work. Did i forget to add something? or what ?
public class ScreenListenerService extends Service {
public void OnCreate(){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver screenOnReceiver = new ScreenBroadcastReceiver();
registerReceiver(screenOnReceiver, filter);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
use Service for your purpose and do the same as you did in the activity.
Here's the deal, I've been working on making a simple screen locker app that mainly does the following:
removes the keygaurd
disables home and back buttons
runs whenever the screen goes ON after going OFF
runs at boot [not tested yet]
I've DONE MY HOMEWORK and used tons of links (especially on stackoverflow) and still so many problems
number 1 works perfectly :)
number 2 works but not as intended, when I press it, it open the dialog that asks the user for choosing a home application... I don't want that! I want to make a lock screen app, not a home app. (code is provided at the end)
number 3 works before unlocking the screen, but after that, the application doesn't know how to start itself automatically. I've implemented a Broadcast Receiver that is registered in code in the onCreat() method for the lock screen activity. I think this is the problem :S
number 4 this doesn't work at all!
I was testing with a service, but still not working :'(
Code
Manifest I'm sure I'm using the the right permissions, am I?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="himura.test.mylockertest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="9" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
<receiver
android:name=".EventsReciever"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service
android:enabled="true"
android:name=".UpdateService"/>
<activity
android:name=".LockPage"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
activity the layout is very simple, just one button to unlock :)
public class LockPage extends Activity {
private Button ublockButton;
#Override
public void onAttachedToWindow() {
//this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
super.onAttachedToWindow();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
///** FIRST THINGS FIRST, START THE SERVICE **/
//startService(new Intent(this, myService.class));
/** REGISTERING RECEIVER **/
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
BroadcastReceiver mReceiver = new EventsReciever();
registerReceiver(mReceiver, filter);
/** SETTING CONTENT VIEW**/
setContentView(R.layout.lockscreen);
/** REMOVING KEYGUARD RECEIVER **/
KeyguardManager keyguardManager = (KeyguardManager)getSystemService(KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();
/** NORMAL CODE **/
ublockButton = (Button)findViewById(R.id.bUnlock);
ublockButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
#Override
public void onBackPressed() {
// Don't allow back to dismiss.
return;
}
//only used in lockdown mode
#Override
protected void onPause() {
super.onPause();
Log.i("event","onPause");
// Don't hang around.
finish();
}
#Override
protected void onStop() {
super.onStop();
Log.i("event","onStop");
// Don't hang around.
finish();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return false;
}
}
Broadcast Receiver this handles 3 things, screen on/off and boot complete (or it should),,, I've been testing with Logs
public class EventsReciever extends BroadcastReceiver {
//works before unlocking
//after unlocking, keygaurd still off, but receiver has stopped
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent recievedIntent) {
Log.i("Check","[BroadCastReciever] onRecieve()");
if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
Log.i("Check","[BroadCastReciever] Screen went OFF");
} else if (recievedIntent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
Log.i("Check","[BroadCastReciever] Screen went ON");
Intent intent = new Intent(context, LockPage.class);
context.startActivity(intent);
}
else if(recievedIntent.getAction().equals(Intent.ACTION_BOOT_COMPLETED))
{
Intent intent = new Intent(context, LockPage.class);
context.startActivity(intent);
// Intent intent = new Intent(context, LockPage.class);
// context.startActivity(intent);
// Intent serviceLauncher = new Intent(context, UpdateService.class);
// context.startService(serviceLauncher);
// Log.v("TEST", "Service loaded at start");
}
}
}
Finally, the service doesn't do anything now, I was trying to use it to start the lock screen after it gets unlocked for the first time
public class myService extends Service{
#Override
public void onCreate() {
/** INITIALIZE RECEIVER **/
//RegisterReciever();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The standard pattern for implementing a Service is to create and run a new thread from onStartCommand
// to perform the processing in the background and stop the Service when it’s complete
//RegisterReciever();
return Service.START_STICKY;
}
/*private void RegisterReciever(){
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_BOOT_COMPLETED);
BroadcastReceiver mReceiver = new EventsReciever();
registerReceiver(mReceiver, filter);
}*/
}
more issues I've found on the internet includes the return of the status bar after turning the screen on (very bad)
in the native keyguard, there is the status bar, but it doesn't function, is there a way to do that?
isn't there a way to just make the locker activity, and tell the system that here u go, use this as the keyguard?
isn't there a way to just make the locker activity, and tell the system that here u go, use this as the keyguard?
If you create your own firmware, presumably there is a way to replace the keyguard with an alternative implementation, considering that most device manufacturers do it. You cannot replace the keyguard via the SDK.
to solve number 2 problem(remove Lock from Home application) remove below line from AndroidManifest.xml file
< category android:name="android.intent.category.HOME" />
Service:
BroadcastReceiver mReceiver=null;
int ReadingBlock = 100;
String PasswordType;
#Override
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);
mReceiver = new AutoStart();
registerReceiver(mReceiver, filter);
}
#Override
public void onStart(Intent intent, int startId) {
boolean screenOn = false;
try{
// Get ON/OFF values sent from receiver ( AEScreenOnOffReceiver.java )
screenOn = intent.getBooleanExtra("screen_state", false);
}catch(Exception e){}
if (!screenOn){
} else {
Intent RegularPassword = new Intent(getApplicationContext(), ScreenLock.class);
RegularPassword.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(RegularPassword);
}
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
Log.i("ScreenOnOff", "Service distroy");
if(mReceiver!=null)
unregisterReceiver(mReceiver);
}