Locked and Unlocked detection in background - android

I'm working on an Android app in which I need to detect when user locked and unlocked, not the screen on/off. So, that I can perform certain action according locked and unlocked. But I'm unable to achieve my goal.
I declare a broadcast inside a service, register the service and receiver inside the manifest and also actions.
It's working fine, when app is open. As the app goes in background it's stop working.
public class UseService extends Service {
#Nullable
Vibrator vibr;
MediaPlayer audi;
//This is Service Class
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(receiver, filter);
}
//Broadcast Receiver
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (action.equals(Intent.ACTION_SCREEN_OFF) && myKM.inKeyguardRestrictedInputMode())
{
vibr.vibrate(500);
if( action.equals(Intent.ACTION_SCREEN_ON) && !myKM.inKeyguardRestrictedInputMode() )
{
vibr.vibrate(5000);
}
}
}
};
//************************Started*************
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
audi=MediaPlayer.create(UseService.this, R.raw.start);
Toast.makeText(UseService.this, "The Service Has Been Started",Toast.LENGTH_SHORT).show();
return START_STICKY;
}
//*******************OnDestroy****************
#Override
public void onDestroy() {
Toast.makeText(UseService.this, "The Service is Destroyed",Toast.LENGTH_SHORT).show();
unregisterReceiver(receiver);
}
}
Main Activity
public class MainActivity extends AppCompatActivity {
Vibrator vibr;
Button btns;
//this is MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btns=(Button)findViewById(R.id.btn);
vibr=(Vibrator) getSystemService(VIBRATOR_SERVICE);
btns.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(getApplicationContext(), UseService.class);
startService(intent);
}
});
}
#Override
protected void onPause() {
super.onPause();
}
}

Related

Cannot using BroadcastReceiver with LocalBroadcastManager

I have 1 activity and 1 service. The service will be started when the activity comes into background and will be stopped when the activity comes into foreground. When the service stops, I want to send an object from it to the activity by intent. Here is my code
MyActivity.java
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_WITH_RLM)) {
//I will get the object received by service here
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_lesson_ins);
localBroadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_WITH_RLM);
localBroadcastManager.registerReceiver(broadcastReceiver, intentFilter);
}
#Override
protected void onResume() {
super.onResume();
if (intent != null) {
stopService(intent);
}
}
#Override
protected void onPause() {
super.onPause();
if (intent != null) {
startService(intent);
}
}
#Override
protected void onStop() {
super.onStop();
localBroadcastManager.unregisterReceiver(broadcastReceiver);
}
MyService.java
private RecordLessonModel recordLessonModel;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//I code sth for handle recordLessonModel object
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent(MyActivity.ACTION_WITH_RLM);
intent.putExtra(MyActivity.RECORD_MODEL_NAME, Parcels.wrap(recordLessonModel));
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
The problem here is my broadcastReceiver in MyActivity cannot receive intent from service when my activity comes to foreground. I don't know why.
Thanks.
You should consider unregistering your broadcastReceiver into onDestory() instead of onStop()
because your brodcastReceiver is getting unregistered when activity goes background.
For more look at HERE

Wrong when register two receiver in an activity Android

I have an activity. It will be receive two variable from an service. In the service, I will send two variable to the activity by
// Send first variable
sendBroadcast(new Intent("first_one"));
// Send second variable
sendBroadcast(new Intent("second_one"));
Now, In the activity, I used bellow code to receive the data. There are
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(firstRec, new IntentFilter("first_one"));
registerReceiver(secondRec, new IntentFilter("second_one"));
}
#Override
protected void onPause() {
super.onPause();
if (firstRec != null) {
unregisterReceiver(firstRec);
firstRec = null;
}
if (secondRec != null) {
unregisterReceiver(secondRec);
secondRec = null;
}
}
private BroadcastReceiver firstRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK first");
}
};
private BroadcastReceiver secondRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK second");
}
};
However, I cannot print the log "OK second" when I called sendBroadcast(new Intent("second_one")); in the service. What is happen? How can I fix it? Thank you
UPDATE: my activity is an accept calling activity get from #notz
How can incoming calls be answered programmatically in Android 5.0 (Lollipop)?. Then I create an service as following
public class myService extends Service{
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent answerCalintent = new Intent(getApplicationContext(), AcceptCallActivity.class);
answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
answerCalintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(answerCalintent);
//Send the second command after 10 second and make the calling in background
new CountDownTimer(10000, 100) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sendBroadcast(new Intent("second_one"));
}
}.start();
return START_STICKY;
}
}
You should unregister your reсeiver in a method opposite to that in which you register it:
If you registered receiver in onCreate() - then you should unregister it in onDestroy().
But as i know, for most cases, the best practice is to register receiver in onResume() and unregister it in onPause().

Broadcast receiver is not working when app on foreground or active

I am building app regarding battery indicator and i am using code from this post.
Getting battery status even when the application is closed
it is working fine when app is closed, but when an app is active or on foreground it did not work or did not send any broadcast.
This is main activity from i start service
public class Main extends Activity {
private MyService service;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (service == null) {
Intent i = new Intent(this, MyService.class);
startService(i);
}
finish();
}
}
Following is the service code.
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService", "onStartCommand");
// do not receive all available system information (it is a filter!)
final IntentFilter battChangeFilter = new IntentFilter(
Intent.ACTION_BATTERY_CHANGED);
// register our receiver
this.registerReceiver(this.batteryChangeReceiver, battChangeFilter);
return super.onStartCommand(intent, flags, startId);
}
private final BroadcastReceiver batteryChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
checkBatteryLevel(intent);
}
};
private void checkBatteryLevel(Intent batteryChangeIntent) {
// some calculations
final int currLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_LEVEL, -1);
final int maxLevel = batteryChangeIntent.getIntExtra(
BatteryManager.EXTRA_SCALE, -1);
final int percentage = (int) Math.round((currLevel * 100.0) / maxLevel);
if(percentage==100)
{
Intent intent = new Intent(getBaseContext(), Last.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(intent);
}
// do not forget to unregister
unregisterReceiver(batteryChangeReceiver);
} }
And when following activity start i did not receive any broadcast.
public class Last extends Activity {
Button btnCancel;
Uri notification;
Ringtone r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_last);
notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
btnCancel = (Button) findViewById(R.id.stopsound);
btnCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
r.stop();
}
});
} }
As I understood,
when you start application in first time, you see nothing, just service is started and a broadcast receiver is registered. When battery level will be changed, the method checkBatteryLevel() is calling and the broadcast receiver will be unregistered. As result you have never received a new changing of battery level.

Service that detects screen lock: "Unable to start service Intent"

I'm trying to catch when my device screen is turned off or on. I looked at this answer here. However I haven't quite figured it out. When I test it, I get a warning saying that the service wasn't able to be created: Unable to start service Intent... not found. I'm new to services so I was hoping someone could look over the code and see what I'm doing wrong. Here is my Receiver and Service:
public class MyReceiver extends BroadcastReceiver {
private boolean screenOff;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
screenOff = true;
Home.locked = true;
Log.i("screenstate", "off");
} else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("screenstate", "on");
}else if(intent.getAction().equals(Intent.ACTION_ANSWER)) {
}
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", screenOff);
context.startService(i);
}}
Service:
public class UpdateService extends Service {
BroadcastReceiver mReceiver;
Boolean isRunning;
Context context;
Thread backgroundThread;
#Override
public void onCreate() {
super.onCreate();
context = this;
isRunning = false;
// register receiver that handles screen on and screen off logic
Log.i("UpdateService", "Started");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_ANSWER);
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
isRunning = false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.i("screenON", "Called");
Toast.makeText(getApplicationContext(), "Awake", Toast.LENGTH_LONG)
.show();
} else {
Log.i("screenOFF", "Called");
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}}
Here is my main activity:
public class Home extends Activity {
static boolean locked = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(Home.this, UpdateService.class));
if(locked)
setContentView(R.layout.activity_home2);
else
showApps(null);
}
public void showApps(View v){
locked = false;
Intent i = new Intent(this, AppsList.class);
startActivity(i);
}}
Thanks in advance.
It looks like the service hasn't been declared in the manifest file. Add its declaration within the <application> tag:
<service android:name=".UpdateService"/>

Start android activity from receiver (inside running service)

I want to display an alert when a sms is received, so my idea is to start a new activity that launch the alertdialog.
My service starts with no problem, and starts receiver as well..
I can receive sms and display toast alerts fine.. but i'd like to show a custom alertdialog instead.
This is the activity that starts my service (ServiceExampleActivity ):
public class ServiceExampleActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStartService = (Button) findViewById(R.id.btnStart);
Button btnStopService = (Button) findViewById(R.id.btnStop);
btnStartService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StartMyService();
}
});
btnStopService.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
StopMyService();
}
});
}
private void StartMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
startService(myServiceIntent);
}
private void StopMyService() {
Intent myServiceIntent = new Intent(this, ServiceTest.class);
stopService(myServiceIntent);
}
}
This is my Service (ServiceTest):
public class ServiceTest extends Service {
private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
private BroadcastReceiver myBroadcastReceiver = null;
#Override
public void onCreate() {
super.onCreate();
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(ACTION);
this.myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
StartDialogActivity(context, intent);
}
};
this.registerReceiver(myBroadcastReceiver, theFilter);
}
#Override
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d("ServiceTest", "Started");
Toast.makeText(this, "Service started...", 3000).show();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
Toast.makeText(this, "Service destroyed...", 3000).show();
}
private void StartDialogActivity(Context context, Intent intent) {
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(dlgIntent);
}
}
And this is the activity i want to launch to display the alertdialog normally..
public class DialogActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
}
}
When it tries to start the activity, the app crashes..
Can you tell me were is the error..??
Like this, you want start activity from service
Intent dlgIntent = new Intent(context, DialogActivity.class);
dlgIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(dlgIntent );

Categories

Resources