I have the main activity, that execute a service. In this service, I init a BroadcastReceiver (alarm).
Then I need send briadcast from the onReceive method of alarm broadcst, but doesn't work. But if I execute sendBroadcast() of other method in alarm, work perfectly.
See de code for explain me:
Activity (init service and get broadcastReceiver)
private final BroadcastReceiver abcd = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Intent in = getIntent();
//finish();
Log.d("sdasd", "onReceive: BROADCAST RECIBIDO!!!");
}
};
Service
alarm alarm = new alarm();
public void onCreate()
{
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.setAlarm(this, tiempo);
return START_STICKY;
}
Alarm.class
#Override
public void onReceive(Context context, Intent intent)
{
context.sendBroadcast(new Intent("xyz"));
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
}
public void setAlarm(Context context, int tiempo)
{
Log.e("TAG", "setAlarm: ");
context.sendBroadcast(new Intent("xyz"));
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), tiempo, pi); // Millisec * Second * Minute
}
In alarm.class, the sendBroadcast in serAlarm() is executed, but the sendBroadcast in onreceive, doesn't executed. And the toast work perfectly.
Why?
I guess, you need to regist BroadcastReceiver in Service.class.
You can regist BroadcastReceiver in 2 way;
AndroidManifest.xml use
<receiver android:name=".TestReceiver">
<intent-filter>
<action android:name="xyz"/>
</intent-filter>
</receiver>
Sourcecode :
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("xyz");
registerReceiver(abcd, intentFilter);
private final BroadcastReceiver abcd = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
//Intent in = getIntent();
//finish();
Log.d("sdasd", "onReceive: BROADCAST RECIBIDO!!!");
}
};
======
".TestReceiver" example: It is Java Class File
public class TestReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
}}
Related
I created an Android application to get all the call logs after the user ends the call. I used Broadcast Receiver to identify the changes then Run the service to get the information about the last call. But sometimes App is killed by the system after one or two days. I read the Broadcast Documentation, Android Service Documentation, and Android <OREO Restriction. Is there any way to keep the Call Broadcast Receiver all the time?
Is there any way to use work manager?
Is there any good approaches, please share here
Service class
public class CallReceiver extends BroadcastReceiver{
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, HammerService.class);
context.startForegroundService(startServiceIntent);
}
}
Service class
public class HammerService extends Service {
#Override
public void onCreate() {
super.onCreate();
IntentFilter ifilter = new IntentFilter();
ifilter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(receiver, ifilter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Hammer Service")
.setContentText(input)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
//do heavy work on a background thread
//stopSelf();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
String action = intent.getAction();
if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
//action for sms received
}
else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
runfirstTime(context,intent);
}
}
};
I can't seem these to get up and running:
public class BackgroundSyncService extends IntentService {
public BackgroundSyncService() {
super("SchedulingService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i("asd-service", "lol");
BackgroundSyncBroadcastReceiver.completeWakefulIntent(intent);
}
}
Second class:
public class BackgroundSyncBroadcastReceiver extends WakefulBroadcastReceiver {
private AlarmManager alarmManager;
private PendingIntent alarmIntent;
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, BackgroundSyncService.class);
startWakefulService(context, service);
}
public void setAlarm(Context context){
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, BackgroundSyncBroadcastReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
0, 5000, alarmIntent);
ComponentName receiver = new ComponentName(context, BackgroundSyncBroadcastReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
}
Third class:
public class BackgroundSyncBootReceiver extends BroadcastReceiver {
BackgroundSyncBroadcastReceiver service = new BackgroundSyncBroadcastReceiver();
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
service.setAlarm(context);
}
}
}
Manifest.xml:
<receiver android:name=".BackgroundSyncBroadcastReceiver"/>
<receiver android:name=".BackgroundSyncBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".BackgroundSyncService"/>
Your receiver for BOOT_COMPLETED will not be allowed to fire until your app has been manually started by the user one time. This is a security feature to prevent apps from running without the user knowing about them.
So, yeah, I forgot to start it from the acivity...
BackgroundSyncBroadcastReceiver service = new BackgroundSyncBroadcastReceiver();
service.setAlarm(this);
Stupid mistake.
I want to begin the receiver class by programmatically,I got some idea about how to start service programmatically and what is the difference between beginning service programmatically and receiver programmatically.Share your solutions and ideas.
If you add receiver in service and get data from your activity. I add Activity and Service class below.
This is your main activity when you get receive data from service.
public class YourActivity extends Activity {
private MyReceiver receiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this);
receiver = new MyReceiver();
IntentFilter filter = new IntentFilter(YourServices.ACTION);
manager.registerReceiver(receiver, filter);
if (!YourServices.isRunning) {
startService(new Intent(this, YourServices.class));
}
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals(YourServices.ACTION)) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 20 seconds after boot completed
cal.add(Calendar.SECOND, 20);
Log.v("background service", "STARTED////\\");
//
// Fetch every 1 hour
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
}
}
}
Here your service that send data when starting.
public class YourServices extends Service {
public static String ACTION = "your_action";
public static boolean isRunning = true;
private void broadcastData() {
Intent intent = new Intent(ACTION);
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
broadcastData();
return START_STICKY;
}
}
I need to update my app's contnent everyday and I use AlarmManager, BroadcastReceiver and IntentService for it.
I create AlarmManager object and setRepeating in the class that extends from Application class:
private void setRecurringAlarm(Context context) {
Intent intent = new Intent(AlarmReceiver.ACTION_ALARM);
AlarmManager alarms = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
final PendingIntent pIntent = PendingIntent.getBroadcast(this,
1234567, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarms.setRepeating(AlarmManager.RTC,
System.currentTimeMillis(), 10000, pIntent);
Toast.makeText(getApplicationContext(), "started", Toast.LENGTH_SHORT).show();
}
My BroadcastReceiver get's message successfully :
public class AlarmReceiver extends BroadcastReceiver {
private static final String DEBUG_TAG = "AlarmReceiver";
public static String ACTION_ALARM = "com.alarammanager.alaram";
#Override
public void onReceive(Context context, Intent intent) {
Intent downloader = new Intent(context, UpdateService.class);
downloader.setAction(Constants.UPDATE_SERVICE);
context.startService(downloader);
Toast.makeText(context, "Entered", Toast.LENGTH_SHORT).show();
}
}
But I also need to start IntentService from the BroadcastReceiver, but it don't started from onReceiver's method of BroadcastReceiver. My service:
<service android:name="com.services.UpdateService"
android:enabled="true">
<intent-filter>
<action android:name="com.service.UpdateService" />
</intent-filter>
</service>
And class for it.
public class UpdateService extends IntentService {
public UpdateService() {
super("UpdateService");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("UpdateService", "About to execute MyTask");
// new MyTask().execute();
Toast.makeText(getApplicationContext(), "updateService", Toast.LENGTH_SHORT).show();
}
// Sometimes overriding onStartCommand will not call onHandleIntent
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("asdasd", "here..!");
return super.onStartCommand(intent,flags,startId);
}
}
My question is why does it(IntentService) can't be invoked from BroadcastReceiver.
Called by the system every time a client explicitly starts the service
by calling startService(Intent), providing the arguments it supplied
and a unique integer token representing the start request. Do not call
this method directly.
If you do call then this is the preferred way:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent);
return START_REDELIVER_INTENT;
}
i have made a service in my project and i want to start the start after every 2mins. i am using the folowing code but its not working properly.
public class ScheduleSync extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent)
{
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartMyServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 60000*2, pending);
}
}
public class StartMyServiceReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "receive broadcast", Toast.LENGTH_LONG).show();
Log.d("StartMyServiceReceiver", "receive broadcast");
Intent service = new Intent(context, myservice.class);
context.startService(service);
}
}
kindly help me regarding this issue. when i see the taskmanager myservice is running at backend.
Why using AlarmManager?
Just use Thread.sleep(xxxx):
public class ScheduleSync extends BroadcastReceiver{
private Context context;
private void startOtherService(){
Intent i = new Intent(context, StartMyServiceReceiver.class);
context.startService(i);
}
#Override
public void onReceive(Context context, Intent intent)
{
this.context = context;
new Thread(new Runnable(){
public void run(){
try{
Thread.sleep(2*60*1000);
startOtherService();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}).start();
}
}