How to invoke an activity from background services when arrives a notification? - android

I want to check notifications from background receivers or services.
The notification is shown, but it should also invoke an activity.
MainActicityClass
Here I have created the alarm class which would call broadcast manager at specific interval
public class MainActivity extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
Intent alarm = new Intent(this.context, AlarmReceiver.class);
boolean alarmRunning = (PendingIntent.getBroadcast(this.context, 0, alarm, PendingIntent.FLAG_NO_CREATE) != null);
if(alarmRunning == false) {
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.context, 0, alarm, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent);
}
}
Alarm Receiver Class
This is the broadcast class to invoke from back ground
public class AlarmReceiver extends BroadcastReceiver {
public AlarmReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, MyListenerServices.class);
context.startService(background);
}
}
MyListener
This is subclass of notificationlistener services
Its reads any incoming notification but unable to read the notification from inactive class
Integrate class read any kind of incoming notification from background
public class MyListenerServices extends NotificationListenerService{
public MyListenerServices() {
}
private boolean isRunning;
private Context context;
private Thread backgroundThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(myTask);
}
private Runnable myTask = new Runnable() {
public void run() {
// Do something here
Log.d("MSG", "ServiceRunning");
StatusBarNotification[] statusBarNotifications = getActiveNotifications();
Log.d("MSG", "New Object2 "+statusBarNotificationsArray);
if (statusBarNotifications.length > 0) {
Log.d("MSG", "New Object "+statusBarNotifications.length);
//
Intent i = new Intent(context, AutomaticCameraActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
// }
// }catch (Exception e){
// Log.d("MSG",e.getMessage());
}
stopSelf();
}
};
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
Notification mNotification=sbn.getNotification();
Log.v("MSG"," Notification"+ mNotification);
}
#Override
public void onDestroy() {
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning) {
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
Any help would be appreciated
Thanks in advance

Create a pending intent
Intent resultIntent = new Intent(this, ResultActivity.class);
//Change ResultActivity by your activity you want invoke
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
More information in Create Notification

Related

Action buttons in notification are showing but when pressed not working

I am using a service to start the mediaplayer as soon as the notification is shown and then stop the service when the action button is pressed. The service starts fine. But the service doesn't stop on clicking the action button.
This is my notification builder
public NotificationCompat.Builder getReminderNotification(String title,String message,PendingIntent intent1){
return new NotificationCompat.Builder(getApplicationContext(),reminderChannelID)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_medicine)
.setColor(getResources().getColor(R.color.colorPrimary))
.setOngoing(true)
.addAction(R.drawable.ic_arrow_back,"OK",intent1);
}
public void cancelNotification() {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(1); // Notification ID to cancel
}
public void startMyService(){
startService(new Intent(this, TimerService.class));
}
public void stopMyService(){
stopService(new Intent(this,TimerService.class));
}
This is my reminder receiver:
public class ReminderReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
Intent newIntent = new Intent(context,DismissReminderReceiver.class);
newIntent.putExtra("action","stop");
PendingIntent intent1 = PendingIntent.getBroadcast(context,0,newIntent,0);
Bundle extras = intent.getExtras();
String title=extras.getString("title");
String message=extras.getString("message");
NotificationCompat.Builder builder = notificationHelper.getReminderNotification(title, message,intent1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(new Intent(context.getApplicationContext(),TimerService.class));
}else {
notificationHelper.startMyService();
}
notificationHelper.getManager().notify(1, builder.build());
}}
This is my code to dismiss the notification
public class DismissReminderReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Here");
Bundle extras = intent.getExtras();
String action = extras.getString("action");
System.out.println(action);
if (action.equals("stop")) {
NotificationHelper notificationHelper = new NotificationHelper(context);
notificationHelper.stopMyService();
notificationHelper.cancelNotification();
}
}}
And this is my service:
public class TimerService extends Service {
public Context context = this;
public Handler handler = null;
public Runnable runnable = null;
MediaPlayer mediaPlayer;public TimerService(){}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
System.out.println("Service Started");
mediaPlayer=MediaPlayer.create(context, Settings.System.DEFAULT_RINGTONE_URI);
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
mediaPlayer.start();
}
};
handler.postDelayed(runnable,0);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
handler.removeCallbacks(runnable);
mediaPlayer.stop();
}}
I also don't see where you register the receiver - if you're doing it in the manifest, make sure it's there with a matching action (and the receiver stanza is there to begin with).

Using AlarmManager to activate and deactivate silence mode

In my program, I am getting 2 dates from user. First date is for activating silence mode and the second date is deactivating it. For handling this issue, I have tried to use 2 different AlarmManager and 2 different BroadcastReceiver but I couldn't achieve it.
I can activate silence mode at the first date but I couldn't deactivate it. This a part of my code:
public class AddEvent extends AppCompatActivity {
private static PendingIntent silenceActivatorPendingIntent;
private static PendingIntent silenceDeactivatorPendingIntent;
private static AlarmManager manager1;
private static AlarmManager manager2;
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent silenceActivatorIntent = new Intent(this, SilenceModeActivator.class);
Intent silenceDeactivatorIntent = new Intent(this, SilenceModeDeactivator.class);
silenceActivatorPendingIntent = PendingIntent.getBroadcast(this, 0, silenceActivatorIntent, 0);
silenceDeactivatorPendingIntent = PendingIntent.getBroadcast(this, 0, silenceDeactivatorIntent, 0);
manager2 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager1 = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
}
public void addEvent(View view) {
GregorianCalendar targetStartDate = new GregorianCalendar(startYear, startMonth, startDay, startHour, startMinute, 0);
GregorianCalendar targetEndDate = new GregorianCalendar(endYear, endMonth, endDay, endHour, endMinute, 0);
manager1.set(AlarmManager.RTC_WAKEUP, targetStartDate.getTimeInMillis(), silenceActivatorPendingIntent);
manager2.set(AlarmManager.RTC_WAKEUP, targetEndDate.getTimeInMillis(), silenceDeactivatorPendingIntent);
}
public static void stopAlarm1() {
manager1.cancel(silenceActivatorPendingIntent);
}
public static void stopAlarm2() {
manager2.cancel(silenceDeactivatorPendingIntent);
}
}
addEvent is my button clicker method.
Silence Mode Activator:
public class SilenceModeActivator extends BroadcastReceiver {
#Override
public void onReceive(final Context context, Intent intent) {
activateSilentMode(context);
AddEvent.stopAlarm1();
}
public void activateSilentMode(Context context) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
context.startActivity(intent);
}
mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
}
}
Silence Mode Deactivator:
public class SilenceModeDeactivator extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
deactivateSilentMode(context);
AddEvent.stopAlarm2();
}
public void deactivateSilentMode(Context context) {
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
// Check if the notification policy access has been granted for the app.
if (!mNotificationManager.isNotificationPolicyAccessGranted()) {
Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
context.startActivity(intent);
}
mNotificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
}
}
Do you have any idea about how I can fix this?
Thanks in advance.

starting BroadcastReceiver from Service when app destroy?

i have a probleme with BroadcastReceiver & Service in my application
.......
i have an
* activity ( MainActivity )
* service ( NotifyService )
* Receiver ( NotifyBroadcast )
service start from activity and then the receiver start from service
everything is good when my app was open , but when i clear it (destroyed) ,receiver stop doing its job ( just a toast message )
here is my code :
MainActivity ..
if( !NotifyService.ServiceIsRun){
NotifyService.ServiceIsRun=true;
startService(new Intent(this, NotifyService.class));
}
NotifyService ..
public class NotifyService extends Service {
public static boolean ServiceIsRun=false;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Timer t = new Timer();
if(ServiceIsRun){
t.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.e("broadService", "hello from Service"+i +"new :"+lastnew +"article :"+lastarticle);
i++;
Intent intent = new Intent( "com.latestBabiaNews" );
sendBroadcast(intent);
}
},
//Set how long before to start calling the TimerTask (in milliseconds)
0,
//Set the amount of time between each execution (in milliseconds)
20000);
}
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
NotifyBroadcast ..
public class NotifyBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
final Bundle bundle = intent.getExtras();
if (intent.getAction().equalsIgnoreCase("com.latestBabiaNews")){
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
}
And in my Manifest ..
<service android:name=".NotifyService"></service>
<receiver android:name=".NotifyBroadcast">
<intent-filter>
<action android:name="com.latestBabiaNews"></action>
</intent-filter>
</receiver>
..........
finally i can show the Toast message when app was app was opened , but when i clear it i can't show anything !
To prevent service kill use it as foreground service. To perform it as foreground use this (inside Service class):
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
fg();
}
private void fg() {
Intent intent = launchIntent(this);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getResources().getString(R.string.app_alias))
.setContentText(getResources().getString(R.string.app_alias))
.setContentIntent(pIntent);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mBuilder.setSmallIcon(someicon);
} else {
mBuilder.setSmallIcon(someicon);
mBuilder.setColor(somecolo);
}
noti = mBuilder.build();
noti.flags = Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
startForeground(_.ID, noti);
}
to stop, this:
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
stopForeground(true);
}
EDIT
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class MyBroadCast extends WakefulBroadcastReceiver {
public static final String INTENT_FILTER = "ru.ps.vm.BRTattva";
#Override
public void onReceive(Context ctx, Intent intent) {
Toast.makeText(context,"hello from Broadcast",Toast.LENGTH_SHORT).show();
}
}
To start use this:
public static void startbyalarm(Context ctx, long nexttime, boolean autoStart, SharedPreferences settings) {
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
Intent intent = new Intent(MyBroadcastReceiver.INTENT_FILTER);
if (autoStart)
intent.putExtra(_.AUTOLOADSERVICE,true);
PendingIntent pi = PendingIntent.getBroadcast(ctx, _.intentalarmindex, intent, PendingIntent.FLAG_CANCEL_CURRENT);
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion < android.os.Build.VERSION_CODES.KITKAT){
am.set(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
if (currentapiVersion < android.os.Build.VERSION_CODES.M) {
am.setExact(AlarmManager.RTC_WAKEUP, nexttime, pi);
} else {
am.setExactAndAllowWhileIdle(wakeup?AlarmManager.RTC_WAKEUP:AlarmManager.RTC, nexttime, pi);
}
}
//or use repeating:
//am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}

How to begin a receiver function programmatically in android?

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;
}
}

AlarmManager with Inner Class BroadcastReceiver

I am new to android. I was playing with the AlarmManager and had successufully go a piece of code running with the BroadcastReceiver as a separate class.
I am now trying to put the BroadcastReceiver as inner class but have no luck on firing the BroadcastReceiver. I had no idea what might have gone wrong after hours looking at the code...
Here is my code:
public class InnerService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(InnerBroadcastReceiver.class.toString());
Log.d("InnerService","InnerService starts!");
Log.d("InnerService","class : "+InnerBroadcastReceiver.class.toString());
this.registerReceiver(new InnerBroadcastReceiver(), filter);
scheduleTestAlarmReceiver(this);
}
public static void scheduleTestAlarmReceiver(Context context) {
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver start");
Intent receiverIntent = new Intent(context, InnerBroadcastReceiver.class);
receiverIntent.setAction("com.example.alarmmanagertest.InnerService$InnerBroadcastReceiver");
PendingIntent sender = PendingIntent.getBroadcast(context, 123456789,
receiverIntent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 1000, sender);
Log.d("scheduleTestAlarmReceiver", "scheduleTestAlarmReceiver complete");
}
private class InnerBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.d("InnerBroadcastReceiver","InnerBroadcastReceiver ALARM Manager fires success!");
}
}
}
It looks like the AlarmManager tried to fire the BroadcastReceiver every second but failed
Logcat:
V/AlarmManager(2439): waitForAlarm result :4
V/AlarmManager(2439): trigger ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP
UPDATE
I have tried to change the code for creating intent in onCreate() and scheduleTestAlarmReceiver() to intent = new intent("action_string") and it works. It seems that intent.setAction() is not working.
What will be the pros and cons for creating intent with and without context (Intent(Context packageContext, Class<?> cls) and Intent(String action))?
But I would still like to know why the above code failed. Can anyone explain?
True, it works!
Small changes in my code. Apk with AsyncTask (downloading file from web and parsing it). "OneMeeting" is my class from project.
public class MainActivity extends AppCompatActivity {
public static final String INPUT_FILE_URL = "https://.../";
private RecyclerView recyclerView;
private String getFilesDir;
private ArrayList<OneMeeting> meetingsArr = new ArrayList<>();
private BroadcastReceiver receiver;
private RefreshFile refreshFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getFilesDir = getFilesDir().getAbsolutePath();
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
meetingsArr.add(new OneMeeting("Launching..." , "", "", ""));
recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));
Intent alarmIntent = new Intent("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 111, alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 5, pendingIntent);
}
#Override
protected void onResume() {
super.onResume();
refreshFile = new RefreshFile();
IntentFilter filter = new IntentFilter("commaciejprogramuje.facebook.conferenceapplication.MainActivity$RefreshFile");
this.registerReceiver(refreshFile, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(refreshFile);
}
private class RefreshFile extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Refresh", Toast.LENGTH_LONG).show();
ParsePage refreshParsingPage = new ParsePage(new ParsePage.OnTaskCompletedListener() {
#Override
public void onTaskCompletedListener(ArrayList<OneMeeting> parsingResultArr) {
meetingsArr = parsingResultArr;
recyclerView.setAdapter(new MyAdapter(meetingsArr, recyclerView));
}
});
refreshParsingPage.execute(getFilesDir);
}
}
}

Categories

Resources