Hello I created Broadcast Receiver in the Service class to receive application notifications but it doesn't receive any intents from Notification. When I make the broadcast receiver static, the problem is solved but at this time I cannot access the elements of the non-static upper class. I have to solve this without making it static.
My Code:
public class BackgroundService extends Service {
private final int TASK_DELAY = 0;
private final int TASK_PERIOD = 5 * 1000;
int NOTIFICATION_ID = 1;
private Context context;
private NotificationCompat.Builder builder;
private NotificationManager notificationManager;
private static Timer timer;
private PendingIntent test;
private int runRate;
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//User pressed a notifiacition button
Log.w(TAG, "onReceive: Recived" );
}
// constructor
public MyReceiver(){
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public static Timer getTimer() {
return timer;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service has been started!", Toast.LENGTH_SHORT).show();
context = getApplicationContext();
timer = new Timer();
runRate = 0;
builder = new NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_dialog_alert)
.setContentTitle("KolBoost")
.setContentText("Arkaplan servisi etkinleştirildi!")
.setAutoCancel(false)
.setPriority(NotificationCompat.PRIORITY_HIGH);
MyReceiver myReceiver = new MyReceiver();
IntentFilter filter = new IntentFilter();
Intent close = new Intent(getBaseContext(), BackgroundService.class);
close.setAction("CLOSE_SERVICE");
PendingIntent closeServiceIntent = PendingIntent.getBroadcast(getBaseContext(), 0, close, 0);
Intent i2 = new Intent(getBaseContext(), BackgroundService.class);
i2.setAction("BOOST_MEMORY");
PendingIntent boostIntent = PendingIntent.getBroadcast(getBaseContext(), 0, i2, 0);
Intent launch = new Intent(getBaseContext(),BackgroundService.class);
launch.setAction("OPEN_MANAGER");
PendingIntent contentIntent = PendingIntent.getBroadcast(getBaseContext(), 0, launch, 0);
builder.setContentIntent(contentIntent);
builder.addAction(0, "Clear Memory", boostIntent);
builder.addAction(0, "Exit", closeServiceIntent);
notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(getBaseContext(), MainActivity.class);
test = PendingIntent.getActivity(getBaseContext(), NOTIFICATION_ID, notificationIntent, PendingIntent.FLAG_NO_CREATE);
//I'm adding actions to intentFilter.
filter.addAction(close.getAction());
filter.addAction(i2.getAction());
filter.addAction(launch.getAction());
//Registering Receiver with intentFilter
registerReceiver(myReceiver,filter);
super.onCreate();
}
#Override
public void onDestroy() {
timer.cancel();
notificationManager.cancelAll();
Log.d(TAG, "onDestroy: Destroyed");
super.onDestroy();
}
}
Related
I try to app runs in background and service listens if screen on app launch on lock screen, we can do android 9 and 9- but we cant achieve android 9+, We use JobIntentService for android 9+ it runs sometimes how can we do that??
YourService.java extend JobIntentService
public class YourService extends JobIntentService {
public static final int JOB_ID = 1;
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, YourService.class, JOB_ID, work);
}
#Override
protected void onHandleWork(#NonNull Intent intent) {
Log.e("çalıştı","çalıştı job");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0)
.build();
Log.e("Myservice","myservice jobbbbb");
startForeground(1, notification);
}
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
//#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
Log.e("ekran", "açıldı");
if(intent.getAction().equals("android.intent.action.SCREEN_ON") ){
wasScreenOn = true;
Log.e("evet screen on","evet screen on");
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, i, 0);
try {
pendingIntent.send();
Log.e("pendingIntent","pendingIntent");
} catch (PendingIntent.CanceledException e) {
e.printStackTrace();
Log.e("printStackTrace","printStackTrace");
}
}
Intent startServiceIntent = new Intent(context, MyService.class);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
context.startForegroundService(startServiceIntent);
Log.e("Myservice","myservice receicer en alt");
}
else {
context.startService(startServiceIntent);
Log.e("Myservice","myservice receicer en dahaaaa alt");
}
YourService.enqueueWork(context, new Intent());
}
}
MyService.java
public class MyService extends Service {
MainActivity mainActivity = new MainActivity();
MyReceiver myReceiver = new MyReceiver();
public MyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
// do your jobs here
// startForeground();
//return super.onStartCommand(intent, flags, 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("Haydi Kurtuluşa")
//.setContentText(input)
.setSmallIcon(R.drawable.more)
.setContentIntent(pendingIntent)
.setNumber(0) // bildirim simgesinin 1 diye gösterilip gösterilmemesini sağlar
.build();
Log.e("Myservice","myservice onstartcommand");
startForeground(1, notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
Log.e("service destroy","service destroy");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("ilkk", true);
editor.commit();
super.onDestroy();
}
}
This code is in MainActivity
final Window win= getWindow();
win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
// win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setTurnScreenOn(true);
setShowWhenLocked(true);
}
// REVEIRVER
// bu dinliyor eğer ekran açılırsa tak MyReceiver classa gönderiyor.
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
myReceiver =new MyReceiver();
registerReceiver(myReceiver,screenStateFilter);
Log.e("geldi3","geldi3");
Log.e("burada ","geldi");
I made an Android app that should play a sound when event is received, it works when app is in focus, but when the app is closed/collapsed sound doesnt play, only standard notification.
How to start a sound/music that is placed inside the app when app with the foreground service?
Main activity:
public class MainActivity extends AppCompatActivity {
private Intent alarmServiceIntent;
private ServiceConnection sConn;
private boolean bound;
private boolean alarm = false;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
alarmServiceIntent = new Intent(this, AlarmService.class);
sConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
ContextCompat.startForegroundService(this, alarmServiceIntent);
}
private void playAlarm() {
bindService(alarmServiceIntent, sConn, BIND_AUTO_CREATE);
}
public void stopAlarm(View v) {
if (sConn != null ) {
unbindService(sConn);
}
if(alarmServiceIntent != null) {
stopService(alarmServiceIntent);
}
}
//here is the method to receive event and call playAlarm
}
Alarm service:
public class AlarmService extends Service{
private final String CHANNEL_ID = "ID";
private final String CHANNEL_NAME = "NAME";
private IBinder mBinder = new MyBinder();
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
play();
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
onStop();
return super.onUnbind(intent);
}
#Override
public void onCreate() {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
}
else
{
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("TITLE")
.setSmallIcon(R.mipmap.icon)
.setContentIntent(pendingIntent)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
new NotificationCompat.Builder(this, CHANNEL_ID);
}
startForeground(619, notification);
return START_REDELIVER_INTENT;
}
public void play() {
if(player == null) {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}
Log.v("ALARM", "play: 12345");
player.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
);
player.setVolume(2,2);
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
player.setLooping(true);
player.start();
}
class MyBinder extends Binder {
AlarmService getService(){
return AlarmService.this;
}
}
}
You should override onDestroy method and call stop there.
#Override
public void onDestroy() {
player.stop();
}
So, im working on making daily notifications for my app. And it works somehow, but the problem is that everytime i start the app or restart, it starts a notification randomly. Its just really frustating.
I've been going trough the code many times, and i just cant see why its happens
So here is everything that have to do with notifications
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public NavigationView navigationView;
private NotificationManagerCompat notificationManager;
SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Notifications
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
SetNotification();
}
public void SetNotification(){
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
Notification_reciever.java
public class Notification_Reciever extends BroadcastReceiver {
private NotificationManagerCompat notificationManagerCompat;
#Override
public void onReceive(Context context, Intent intent) {
Intent activityIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context,
0, activityIntent, 0);
notificationManagerCompat = NotificationManagerCompat.from(context);
Notification notification = new NotificationCompat.Builder(context,CHANNEL_1_ID)
.setSmallIcon(R.drawable.ic_face)
.setContentTitle("Your Daily Life Tip!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setCategory(NotificationCompat.CATEGORY_ALARM)
.setContentIntent(contentIntent)
.setStyle(new NotificationCompat.BigTextStyle()
.setSummaryText("Daily Notification"))
.setAutoCancel(true)
.setContentText(getlifetip(context))
.setColor(Color.parseColor("#EE3D33"))
.build();
notificationManagerCompat.notify(0, notification);
}
public String getlifetip(Context context){
//gets lifetip from jsonobject
}
MyService.java
public class MyService extends Service {
SharedPreferences preferences;
public MyService(){
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
SetNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null){
SetNotification();
}else Toast.makeText(this, "Intent was null", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags,startId);
}
public void SetNotification(){
preferences = getSharedPreferences("shared preferences", Context.MODE_PRIVATE);
if (GetNotificationsChecked()){
Intent notificationIntent =new Intent(this,Notification_Reciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
try{
manager.cancel(pendingIntent);
}catch (Exception ignored){}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, Integer.valueOf(preferences.getString("notificationsHour", "15"))) ;
calendar.set(Calendar.MINUTE, Integer.valueOf(preferences.getString("notificationsMinute", "00"))) ;
if (manager != null) {
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent);
}
}
}
public boolean GetNotificationsChecked(){
boolean i = preferences.getBoolean("notifications", true);
return i;
}
}
BootReciever.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context,MyService.class);
context.startService(i);
}
}
App.java
public class App extends Application {
public static final String CHANNEL_1_ID = "dailylifetip";
#Override
public void onCreate() {
super.onCreate();
CreateNotificationChannel();
}
private void CreateNotificationChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationChannel channel1 = new NotificationChannel(
CHANNEL_1_ID,
"Daily Life Tips",
NotificationManager.IMPORTANCE_HIGH
);
channel1.setDescription("This is the daily life tips channel");
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel1);
}
}
}
Manifest
<receiver android:name=".Notification_Reciever"/>
<service android:name=".MyService" android:enabled="true" android:exported="true"/>
The user selects the hour and minute of the day in an options menu, and is saved in preferences. And then should give an notification everyday on that time. And that works!. But everytime you open the app it randomly sends you a notifications, there is no errors.
I want to send push notifications in my app but after few minutes android kill my background service and notifications not showing. How to make background service which android will not close?
BackroundService.class
public Context context = this;
public android.os.Handler handler = new Handler();
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.e("Service", "Service crated!");
runnable = new Runnable() {
public void run() {
Log.e("Service", "Service is still running!");
Toast.makeText(context, "Service is still running", Toast.LENGTH_SHORT).show();
handler.postDelayed(runnable, 50000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
Log.e("Service", "Service started by user!");
}
AlarmReceiver.class
#Override
public void onReceive(Context context, Intent intent) {
int notificationId = intent.getIntExtra("ID", 0);
String message = intent.getStringExtra("TEXT");
String tittle = intent.getStringExtra("TITTLE");
Intent mainIntent = new Intent(context, BackgroundService.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, mainIntent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(context);
builder.setSmallIcon(R.drawable.finance43)
.setContentTitle(tittle)
.setContentText(message)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentIntent(contentIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setCategory(Notification.CATEGORY_MESSAGE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelId = "REMINDERS";
NotificationChannel channel = new NotificationChannel(channelId,
"Reminder",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
builder.setChannelId(channelId);
}
notificationManager.notify(notificationId, builder.build());
}
When I start app i see "Service is still running!" for about 1 hour.
I just followed the exact code in API Demo, but my service just won't start after I set the AlarmManager.
so my service is
public class CourseWatcherRefreshService extends Service {
private CourseDbAdapter mDbHelper;
private CourseWatcher watcher;
#Override
public void onCreate() {
Toast.makeText(this, "Watcher Refresh Service starts", Toast.LENGTH_SHORT).show();
mDbHelper = new CourseDbAdapter(this);
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mDbHelper.open();
Thread thread = new Thread(null, mTast, "CourseWatcherRefreshService");
thread.start();
super.onCreate();
}
#Override
public void onDestroy() {
mDbHelper.close();
super.onDestroy();
}
Runnable mTast = new Runnable() {
// some work
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Also in my AndroidManifest.xml, I put such code
<service
android:name=".CourseWatcherRefreshService"
android:process=":remote" >
</service>
And I use such code to toggle the AlarmManager
PendingIntent refreshIntent = PendingIntent.getActivity(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);
long firstTime = SystemClock.elapsedRealtime();
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTime, 30*1000, refreshIntent);
And the code above is almost the same with the AlartService example in API Demo, but my code won't work, I can't see any sign of my service starts to work.
You are using getActivity when you should be using getService. So change the PendingIntent line to
PendingIntent refreshIntent = PendingIntent.getService(NaviScreen.this, 0, new Intent(NaviScreen.this, CourseWatcherRefreshService.class), 0);
try this :
Intent updateIntent = new Intent()
updateIntent.setClass(NaviScreen.this, CourseWatcherRefreshService.class)
PendingIntent pendingIntent = PendingIntent.getService(this, 0, updateIntent, 0);