android.intent.action.ALARM_CHANGED - android

I need to set alarm icon in status bar, without a notification. It works when application is running, but after finishing an application, the receiver does not respond on "ALARM_CHANGED", only on "BOOT_COMPLETED".
Need to set alarm icon after user turns off alarms in build-in Alarm Clock.
Thanks.
manifest:
<receiver android:name=".Alarm.AlarmInitReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ALARM_CHANGED" />
</intent-filter>
</receiver>
AlarmInitReceiver.java:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
Toast.makeText(context, "Alarm on", Toast.LENGTH_SHORT).show();
setStatusBarIcon(true);
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setStatusBarIcon(true);
enableReceiver(true);
}
protected void enableReceiver(boolean enable) {
ComponentName receiver = new ComponentName(mContext, AlarmInitReceiver.class);
PackageManager pm = mContext.getPackageManager();
pm.setComponentEnabledSetting(receiver,
(enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
public static void setStatusBarIcon(boolean enabled)
{
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", enabled);
mContext.sendBroadcast(alarmChanged);
}
}

The solution is:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
if (intent.getExtras().getBoolean("alarmSet") == false) {
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", true);
context.sendBroadcast(alarmChanged);
}
}
}
}

Related

How to launch an app when the screen unlocks?

I have tried this code but it's not working. Does anybody have any different solution? I have tried many ways like the below one from Stack Overflow but none of them is working.
manifest.xml
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
screenreceiver
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Intent intent = new Intent();
intent.setClass(context, ScreenLockActivity.class);
startActivity(intent);
}
}
}
To listen to screen on/off, your app should run by time and register Broadcast receiver to OS programmatically.
ScreenOnOffService.java
public class ScreenOnOffService extends Service {
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.i("ScreenOnOffService", "onCreate: ");
IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
}
public void onDestroy() {
super.onDestroy();
Log.i("ScreenOnOffService", "onDestroy: ");
unregisterReceiver(ScreenOnReceiver.newInstance());
// startService(new Intent(this,ScreenOnOffService.class));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
ScreenOnReceiver.java
public class ScreenOnReceiver extends BroadcastReceiver {
public static final String TAG = "ScreenOn";
public static volatile ScreenOnReceiver screenOn;
public static ScreenOnReceiver newInstance() {
if (screenOn == null) {
screenOn = new ScreenOnReceiver();
}
return screenOn;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("hieuN", "intent: " + intent.getAction());
// do work. start activity.
}
}
Start service in activity
Intent service = new Intent(this, ScreenOnOffService.class);
startService(service);

Restarting the app when power button is clicked even after the app is killed from recent application tray

I am new android I want to implement in my that when I press power button I need to open the app but the app is killed in the background from recent app tray. I am trying all the solutions which I got but I didnt get solution
MainActivity.class
public class MainActivity extends ActionBarActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
/*Toast.makeText(getApplicationContext(),"main Activity run",Toast.LENGTH_SHORT).show();
intent = new Intent(new Intent(getBaseContext(), PowerService.class));
startService(intent);*/
// /* new Handler().post(new Runnable() {
// #Override
// public void run() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
// }
// });
//*/
// Intent notificationIntent = new Intent(this, PowerService.class);
// PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//
//
//
}
#Override
protected void onStart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onStart",Toast.LENGTH_SHORT).show();
super.onStart();
}
#Override
protected void onResume() {
Toast.makeText(getApplicationContext(),"inside mainactivity onResume",Toast.LENGTH_SHORT).show();
super.onResume();
}
#Override
protected void onRestart() {
Toast.makeText(getApplicationContext(),"inside mainactivity onRestart",Toast.LENGTH_SHORT).show();
super.onRestart();
}
#Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(),"inside mainactivity onDestroy",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
protected void onStop() {
Toast.makeText(getApplicationContext(),"service run",Toast.LENGTH_SHORT).show();
Intent intent = new Intent(new Intent(MainActivity.this, PowerService.class));
startService(intent);
Toast.makeText(getApplicationContext(),"inside mainactivity onStop",Toast.LENGTH_SHORT).show();
super.onStop();
}
}
Service.class
public class PowerService extends Service {
BroadcastReceiver mReceiver;
IntentFilter filter;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
cpuWakeLock.acquire();
registerReciver();
return Service.START_STICKY;
}
public class LocalBinder extends Binder {
PowerService getService() {
return PowerService.this;
}
}
#Override
public boolean onUnbind(Intent intent) {
System.out.println("inside powerservice onUnbind");
Toast.makeText(getApplicationContext(),"inside powerservice onUnbind",Toast.LENGTH_SHORT).show();
return super.onUnbind(intent);
}
#Override
public void onRebind(Intent intent) {
System.out.println("inside powerservice onRebind");
Toast.makeText(getApplicationContext(),"inside powerservice onRebind",Toast.LENGTH_SHORT).show();
super.onRebind(intent);
}
#Override
public void onStart(Intent intent, int startId) {
System.out.println("inside powerservice onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
//unregisterReceiver(mReceiver);
//registerReciver();
System.out.println("inside powerservice onDestroy");
Toast.makeText(getApplicationContext(),"inside powerservice ondestroy",Toast.LENGTH_SHORT).show();
startService(new Intent(this, PowerService.class));
super.onDestroy();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
/*registerReciver();
startService(new Intent(this,PowerService.class));*/
Toast.makeText(getApplicationContext(),"inside powerservice onTaskRemoved",Toast.LENGTH_SHORT).show();
/*Intent broadcastIntent = new Intent(this,AppReciever.class);
sendBroadcast(broadcastIntent);
super.onTaskRemoved(rootIntent);*/
/* Intent restartServiceTask = new Intent(this,PowerService.class);
restartServiceTask.setPackage(getPackageName());
PendingIntent restartPendingIntent =PendingIntent.getService(getApplicationContext(), 1,restartServiceTask, PendingIntent.FLAG_ONE_SHOT);
AlarmManager myAlarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
myAlarmService.set(
AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + 1000,
restartPendingIntent);
startService(new Intent(this,PowerService.class));*/
super.onTaskRemoved(rootIntent);
}
public void registerReciver()
{
filter= new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_LOCKED_BOOT_COMPLETED);
mReceiver = new AppReciever();
registerReceiver(mReceiver, filter);
}
}
BroadcastReciever
public class AppReciever extends BroadcastReceiver {
public static boolean wasScreenOn = true;
public void onReceive(final Context context, final Intent intent) {
Log.e("LOB", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
Toast.makeText(context,"inside ACTION_SCREEN_OFF",Toast.LENGTH_SHORT).show();
//Log.e("LOB","wasScreenOn"+wasScreenOn);
Log.e("Screen ", "shutdown now");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.e("Screen ", "awaked now");
Toast.makeText(context,"inside ACTION_SCREEN_ON",Toast.LENGTH_SHORT).show();
Intent i = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Log.e("LOB", "userpresent");
Toast.makeText(context,"inside ACTION_USER_PRESENT",Toast.LENGTH_SHORT).show();
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
wasScreenOn = true;
// Log.e("LOB","wasScreenOn"+wasScreenOn);
}
else if(intent.getAction().equals(Intent.ACTION_LOCKED_BOOT_COMPLETED))
{
Toast.makeText(context,"inside ACTION_LOCKED_BOOT_COMPLETED",Toast.LENGTH_SHORT).show();
Log.e("LOB", "userpresent");
Intent ii = new Intent(context, MainActivity.class); //MyActivity can be anything which you want to start on bootup...
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(ii);
}
/* Log.v("##%#%#", "Power button is pressed.");
Toast.makeText(context, "power button clicked",Toast.LENGTH_LONG).show();*/
}
}
Manifestfile
package="com.benayah.app.sampleapp">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".PowerService"
android:enabled="true"
android:exported="false"
android:stopWithTask="false"
android:process=":my_process"
>
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
</service>
</application>
Please let me know where I am going wrong in my code and I need to run the service in background to check for the screen on even after the app is killed in background because now when I killed app I couldn't restart my app but if I didn't kill the it is working fine
Use following might be helpfull...
***in Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent= new Intent(context, ActivitySample.class);
context.startActivity(intent);
}
}
You below might be helpfull...
In Manifest
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"></action>
<action android:name="android.intent.action.SCREEN_ON"></action>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
<action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
</intent-filter>
public class MyReceiver extends BroadcastReceiver {
static int countPowerOff=0;
private Activity activity=null;
public MyReceiver (Activity activity)
{
this.activity=activity;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.v("onReceive", "Power button is pressed.");
Toast.makeText(context, "power button clicked", Toast.LENGTH_LONG)
.show();
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
{
countPowerOff++;
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
if(countPowerOff==5)
{
Intent i =new Intent(activity,NewActivity.class);
activity.startActivity(i);
}
}
}
And,
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
MyReceiver mReceiver = new MyReceiver (this);
registerReceiver(mReceiver, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
The only way i know to monitor the power button is by listening to the ScreenOn and ScreenOff events. So you can try to write a service that is listening to ScreenOn or ScreenOff and then each time that this event is firing you can launch the desired app.
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);
}
}
Service:
public class ScreenOnOffService extends Service {
private ScreenOnOffReceiver mScreenReceiver;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
registerScreenStatusReceiver();
}
#Override
public void onDestroy() {
unregisterScreenStatusReceiver();
}
private void registerScreenStatusReceiver() {
mScreenReceiver = new ScreenOnOffReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(mScreenReceiver, filter);
}
private void unregisterScreenStatusReceiver() {
try {
if (mScreenReceiver != null) {
unregisterReceiver(mScreenReceiver);
}
} catch (IllegalArgumentException e) {}
}
}
Manifest:
<service android:name="com.benayah.app.sampleapp.ScreenOnOffService" />
BroadcastReceiver:
(here you need to put the package name of the app that you want to launch)
in my example i put your package name: com.benayah.app.sampleapp
public class ScreenOnOffReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.d("StackOverflow", "Screen Off");
startApp(context);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.d("StackOverflow", "Screen On");
startApp(context);
}
}
private void startApp(Context context) {
PackageManager pm = context.getPackageManager();
Intent launchIntent = pm.getLaunchIntentForPackage("com.benayah.app.sampleapp");
context.startActivity(launchIntent);
}
}

Android BroadcastReceiver called multiple times

I'm new to android and i am trying to implement a broadcast receiver which will receive the broadcast whenever the hotspot is changed:
public class HotspotChangeReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
String action = intent.getAction();
if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {
Intent intent1 = new Intent();
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
// if (WifiManager.WIFI_STATE_ENABLED == state % 10) {
if(state == 13){
intent1.setAction("net.wecodelicious.intent.action.HOTSPOT_ENABLED");
context.sendBroadcast(intent1);
}
else{
intent1.setAction("net.wecodelicious.intent.action.HOTSPOT_DISABLED");
context.sendBroadcast(intent1);
}
Toast.makeText(context, "HOTSPOT Changed ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotChangeReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotChangeReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
also i've following classes to receive custom broadcasts:
public class HotspotEnabledReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
if("net.wecodelicious.intent.action.HOTSPOT_ENABLED".equals(intent.getAction())) {
Toast.makeText(context, "Hotspot Enabled ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
HotspotChangeReceiver.enable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotEnabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
HotspotChangeReceiver.disable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotEnabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
and broadcastreceiver when hotspot is disabled is following:
public class HotspotDisabledReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
if("net.wecodelicious.intent.action.HOTSPOT_DISABLED".equals(intent.getAction())) {
Toast.makeText(context, "Hotspot Disabled ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
HotspotChangeReceiver.enable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotDisabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
HotspotChangeReceiver.disable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotDisabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
also I'm enabling all receiver components in ManiActivity as followed:
public class MainActivity extends AppCompatActivity {
public static boolean isF = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
enableall();
}
public static void enableall(){
if(isF) {
HotspotChangeReceiver.enable();
HotspotEnabledReceiver.enable();
HotspotDisabledReceiver.enable();
isF=false;
}
}
I've registered them in manifest file:
<receiver android:name=".HotspotChangeReceiver" android:enabled="false">
<intent-filter>
<action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED"/>
</intent-filter>
</receiver>
<receiver android:name=".HotspotEnabledReceiver" android:enabled="false">
<intent-filter>
<action android:name="net.wecodelicious.intent.action.HOTSPOT_ENABLED"/>
</intent-filter>
</receiver>
<receiver android:name=".HotspotDisabledReceiver" android:enabled="false">
<intent-filter>
<action android:name="net.wecodelicious.intent.action.HOTSPOT_DISABLED"/>
</intent-filter>
</receiver>
But when i run the app and turn the hotspot on Toasts are displayed in following sequence:
Hotspot Changed
Hotspot Disabled
Hotspot Enabled
also when i turn the hotspot off following Toasts are displayed:
Hotspot Changed
Hotspot Disabled
Hotspot Changed
Hotspot Disabled
I hope someone recognizes the strange behavior and has a quick solution for it.I tried to find the solution but was unable to come up with any.Any help will be appreciated.
When you Enable and Disable, it is a State Change at the same time isn't it. I would either register Enable and Disable, or just State Change by itself only.

How to Lock/Unlock screen programmatically?

I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.
Below is the broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entered Broadcaste Reciever");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
System.out.println("SCREEN_OFF"+wasScreenOn);
wasScreenOn = false;
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", wasScreenOn);
context.startService(i);
System.out.println("jrkejhr keh");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
System.out.println("SCREEN_ON"+wasScreenOn);
}
}
And its entering to a service where i had written the intent action to go home is...
ShakeListener mShaker;
int amountOfTime = 0;
Context context1;
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
System.out.println("Enterd Service");
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
vibe.vibrate(100);
Intent goHome = new Intent();
goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
goHome.setAction("android.intent.action.MAIN");
goHome.addCategory("android.intent.category.HOME");
startActivity(goHome);
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.
Edit:
As some folks needs help in Unlocking device after locking programmatically,
I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
#Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".LockScreenActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:
FLAG_DISMISS_KEYGUARD
FLAG_SHOW_WHEN_LOCKED
FLAG_TURN_SCREEN_ON

Android 4.0 Device Admin Receiver not working

I'm trying to build a really simple app to wipe all the user data off a ICS device.
I've tried to create the app using the source code on http://developer.android.com/guide/topics/admin/device-admin.html
and
http://marakana.com/s/post/1291/android_device_policy_administration_tutorial
But I'm having an issue, no matter what I do, the broadcast receiver for prompting the user to allow admin does not appear!
Heres what I got so far if anyone can help with this issue.
Manifest:
<uses-sdk android:minSdkVersion="15" />
<application android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<activity android:name="com.CheckActivityService.CheckActivityServiceActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<receiver android:name=".mDeviceAdminReceiver"
android:label="device_admin" android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</manifest>
Activity:
public class CheckActivityServiceActivity extends Activity implements OnCheckedChangeListener{
/** Called when the activity is first created. */
static final int ACTIVATION_REQUEST = 1; // identifies our request id
DevicePolicyManager devicePolicyManager;
ComponentName deviceAdmin;
ToggleButton toggleButton;
static final String TAG = "DevicePolicyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toggleButton = (ToggleButton) super
.findViewById(R.id.toggle_device_admin);
toggleButton.setOnCheckedChangeListener(this);
Button btn = (Button) findViewById(R.id.wipeDataBtn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
wipeData();
}
});
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
deviceAdmin = new ComponentName(CheckActivityServiceActivity.this, mDeviceAdminReceiver.class);
}
/**
* Called when the state of toggle button changes. In this case, we send an
* intent to activate the device policy administration.
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (isChecked) {
// Launch the activity to have the user enable our admin.
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "My Boss told me to do this!!");
startActivityForResult(intent, ACTIVATION_REQUEST);
}
Log.d(TAG, "onCheckedChanged to: " + isChecked);
}
public void wipeData(){
devicePolicyManager.wipeData(ACTIVATION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVATION_REQUEST:
if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Administration enabled!");
toggleButton.setChecked(true);
} else {
Log.i(TAG, "Administration enable FAILED!");
toggleButton.setChecked(false);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Reciever:
public class mDeviceAdminReceiver extends DeviceAdminReceiver {
static final String TAG = "DeviceAdminReceiver";
void showToast(Context context, String msg) {
String status = "TEST";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
/** Called when this application is approved to be a device administrator. */
#Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
Toast.makeText(context, "Admin Enabeled",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onEnabled");
}
/** Called when this application is no longer the device administrator. */
#Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
Toast.makeText(context, "Admin Disabled",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onDisabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
super.onPasswordChanged(context, intent);
Log.d(TAG, "onPasswordChanged");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
super.onPasswordFailed(context, intent);
Log.d(TAG, "onPasswordFailed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
super.onPasswordSucceeded(context, intent);
Log.d(TAG, "onPasswordSucceeded");
}
}
If anyone can help me to get this to work, as I really can't figure out why the broadcast receiver isn't firing.
Figured out problem, kind of stupid of me.
needed to put the receiver in the element.

Categories

Resources