How to receive LocalBroadcast in android service - java

I am trying to make an app in which I have a receiver which sends out a broadcast:
public class PhoneStateReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
try {
System.out.println("Receiver start");
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
Intent callIntent = new Intent("INCOMING_CALL");
callIntent.putExtra("number", incomingNumber);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
//Toast.makeText(context,"Call Received State",Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
//Toast.makeText(context,"Call Idle State",Toast.LENGTH_SHORT).show();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
I also have a service running and I want to capture the broadcast in that service, I have tried the following but it does not work:
public class NotifierService extends Service
{
...//something goes here
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
LocalBroadcastManager.getInstance(this).registerReceiver(lbReceiver, new IntentFilter("INCOMING_CALL"));
return START_STICKY;
}
private BroadcastReceiver lbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals("INCOMING_CALL"))
{
//do something
}
}
};
Can someone please tell me the correct way to receive a broadcast in a service, if it is not possible to receive a broadcast then what else can i use ?
[UPDATE]
This is how my service is declared in the manifest
<service
android:name=".NotifierService"
android:enabled="true"
android:exported="true"
>
</service>

Related

Android Java Notification

This code isn't working for me it should make notification every 2 sec the app runs with no errors and then after 2 sec keeps giving me messages you're app has stopped working.
I added these codes:
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name="NotificationService" android:exported="false"/>
<receiver android:name="BootReceiver">
<intent-filter>
<action android:name="com.company.app"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
MainActivity.java
startActivity(new Intent(this,NotificationService.class));
NotificationService.java
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer=new Timer();
mTimer.schedule(timerTask,2000,2*1000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
}catch (Exception e){
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
Log.e("log","Running");
notifiy();
}
};
#Override
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
}catch (Exception e){
e.printStackTrace();
}
Intent intent=new Intent("com.company.app");
intent.putExtra("your value","torestore");
sendBroadcast(intent);
}
public void notifiy(){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("RSSPullService");
Intent mIntent=new Intent(Intent.ACTION_VIEW, Uri.parse(""));
PendingIntent pendingIntent=PendingIntent.getActivity(getBaseContext(),0,mIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
Context context=getApplicationContext();
Notification.Builder builder=new Notification.Builder(context)
.setContentTitle("T")
.setContentText("M")
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
;//.setSmallIcon();
Notification notification=builder.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notification);
}
}
BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Service stops","ohhhhhhh");
context.startService(new Intent(context,NotificationService.class));
}
}

Service if BroadcastReceiver running then do nothing in Android

I'm new at Android,
so please excuse my low experience.
I need this service to check if BroadcastReceiver is running or not every period of time.
If it's running then I want it to do nothing, but if not running I want it to run it.
In this code the service run the receiver every 20 sec, but it didn't check if receiver running or not, so every 20 sec I will get new receiver and the running receiver.
Any idea to solve this problem please?
Receiver.java
public class Receiver extends BroadcastReceiver
{
int numberr =0;
private static final String TAG = "RestartServiceReceiver";
#Override
public void onReceive(Context context, Intent intent) {
int delay = 0;
int period = 10000;
Timer basic_timer = new Timer();
basic_timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
Log.e("view", ""+numberr );
numberr++;
}
}, delay, period);
}
}
Service1.java
public class Service1 extends Service {
public Service1() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int delay = 0;
int period =20000;
Timer basic_timer = new Timer();
basic_timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
sendBroadcast(new Intent("run"));
}
}, delay, period);
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Toast.makeText(this, "Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
I think u just forget to register the receiver in menifest.
try to add this beside service in menifest~
<receiver android:name=".Receiver">
<intent-filter>
<action android:name="run" />
</intent-filter>
</receiver>
<service ...
ps. make sure your service has been started . or try to call this in your activity
startService(new Intent(this, Service1.class));

Android BroadcastReceiver in Service giving null pointer exception when sending broadcast to it

I have a broadcast receiver in my service, and when I send a broadcast to it from my activity to stop the service for example, I get the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.content.BroadcastReceiver.onReceive(android.content.Context, android.content.Intent)' on a null object reference
Here is my Service class:
public class PhraseService extends Service{
public static List<Phrase> phrases;
private Context context;
private static final String PHRASE_SERVICE_BROADCAST_ID = "com.cryogenos.safephrase.PHRASE_SERVICE_BROADCAST_ID";
private BroadcastReceiver command_broadcast_receiver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
this.context = getApplicationContext();
LocalBroadcastManager.getInstance(this).registerReceiver(command_broadcast_receiver, new IntentFilter(PHRASE_SERVICE_BROADCAST_ID));
Log.i("COS", "STARTED SELF");
/* Handle any command sent by the app here */
command_broadcast_receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("COS", "CALLED?");
try {
String command = intent.getStringExtra("command");
/* Based on the command given, perform an action */
switch (command) {
case "RESTART RECOGNIZER":
break;
case "STOP":
Toast.makeText(context, "Phrase Listener Stopped", Toast.LENGTH_SHORT).show();
stopSelf();
break;
}
}
catch (Exception e){}
}
};
Intent notif_intent = new Intent(this, Home.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, notif_intent, 0);
Notification notif = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Phrase Listener")
.setContentText("Listening for Phrases")
.setContentIntent(pi)
.build();
startForeground(34994, notif);
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(command_broadcast_receiver);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {return null;}
}
Here is the activity from where I'm sending the broadcast from:
public class SettingsModel {
private Context context;
private static final String PHRASE_SERVICE_BROADCAST_ID = "com.cryogenos.safephrase.PHRASE_SERVICE_BROADCAST_ID";
private LocalBroadcastManager local_broadcast_manager;
public SettingsModel(Context context) {
this.context = context;
local_broadcast_manager = LocalBroadcastManager.getInstance(context);
}
public void handleSwitch(SettingsSwitch settings_switch, boolean status){
switch (settings_switch){
case POWER:
if(status) {
Intent i = new Intent(context, PhraseService.class);
context.startService(i);
}
else{
Intent i = new Intent(PHRASE_SERVICE_BROADCAST_ID);
i.putExtra("command", "STOP");
local_broadcast_manager.sendBroadcast(i);
}
break;
case VIBRATE:
break;
case RING:
break;
case TIMER:
break;
}
}
}
My service is suppose to be continuously running, and only when I tell it, it should stop. This is why I have set it up as a foreground service. The problem here is that I keep getting an error when I try to broadcast to it.
You are registering your brodcastreceiver before initializing it. So try to move the registration after initialization as below:
/* Handle any command sent by the app here */
command_broadcast_receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("COS", "CALLED?");
try {
String command = intent.getStringExtra("command");
/* Based on the command given, perform an action */
switch (command) {
case "RESTART RECOGNIZER":
break;
case "STOP":
Toast.makeText(context, "Phrase Listener Stopped", Toast.LENGTH_SHORT).show();
stopSelf();
break;
}
}
catch (Exception e){}
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(command_broadcast_receiver, new IntentFilter(PHRASE_SERVICE_BROADCAST_ID));
Also, your SettingsModel is not an activity since it does not extend Activity.

Trying to count number of times the phone is unlocked

i tired this a few months ago but failed.
what i'm trying to do is count the number of times the user unlocks his phone and show it on the screen but i'm getting vague numbers each time i unlock the phone.
my code is a follows.
My main activity oncreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(getApplicationContext(), LockService.class));
TextView ticker;
ticker = (TextView) findViewById(R.id.textView);
ticker.setText(String.valueOf(Tick.tick));
Log.e("but this is awesome ", String.valueOf(Tick.tick));
}
The Service class
public class LockService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
}
The BroadcastReceiver Class
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(final Context context, final Intent intent) {
Log.e("test", "onReceive");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
wasScreenOn = false;
Log.e("test", "wasScreenOn" + wasScreenOn);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
wasScreenOn = true;
Log.e("test", "wasScreenOn and user present" + wasScreenOn);
} else if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)) {
Tick.tick ++;
Log.e("test", "userpresent" + Tick.tick);
}
}
}
please help me understand what i'm doing wrong
I believe what's happening is this:
each time you open your activity, you call start service. So even if your service is already running, onStartCommand is being called. This way, you register your broadcast multiple times, and then when you unlock your device your counters are being incremented for each time you reciver has been registered.
You should do one of these options:
1. Define your recievers in your manifest so you won't have to deal with registration and unregisteration each time.
2. Register you recievers in your service onCreate instead onStartCommand. Also, make sure you unregister them in your service onDestroy.

how do i retrieve the incoming phone call's number while ringing and store it in a variable in android?

I am fairly new to android and I would like my app to be able to retrieve the phone number of caller while ringing and store it. How can I do this?
You need to use a BroadcastReceiver. It should look something like this:
public class CallReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
Intent i = new Intent(context, IncomingCallPopup.class);
i.putExtras(intent);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
context.startActivity(i);
}
}
Need to Extend BroadcastReceiver
public class CallReceiver extends BroadcastReceiver {
#Override
public final void onReceive(Context context, Intent intent){
try {
String state =intent.getStringExtra(TelephonyManager.EXTRA_STATE);
String number=intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
}
catch (Exception e) {
Log.e(TAG," Exception "+e);
}
}
}
you should register broadcast receiver and get the phone state and get incoming phone call number as:
public class CallReceiver extends BroadcastReceiver {
String state,number,message;
#Override
public void onReceive(Context context, Intent intent) {
state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if(state.equals(TelephonyManager.EXTRA_STATE_RINGING)){
number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
message = "phone is ringing";
Toast.makeText(context, "Incoming Call From:"+number, Toast.LENGTH_SHORT).show();
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
Toast.makeText(context, "Call Received", Toast.LENGTH_SHORT).show();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
message += "phone is idled";
Toast.makeText(context, "Idled", Toast.LENGTH_SHORT).show();
}
}
}

Categories