I am trying to make an app in Android Studio which sends a push notification every 15 seconds, using a service. The problem is that the mobiles I tested the code on acted really slowly when a notification pops up. When I use an emulator, it works fine. Does anyone know what makes this code really slow?
Thanks in advance!
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent i = new Intent(this, MyService.class);
startService(i);
}
}
MyService.java
public class MyService extends Service {
public MyService() {
}
public void showPushNotification (){
NotificationCompat.Builder pushbericht;
final int IDnummer = 123;
pushbericht = new NotificationCompat.Builder(this);
pushbericht.setAutoCancel(true);
pushbericht.setSmallIcon(R.drawable.icoontje);
pushbericht.setContentTitle("Poll App");
pushbericht.setContentText("Hoi");
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
pushbericht.setContentIntent(pendingIntent);
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(IDnummer, pushbericht.build());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 5; i++) {
long futureTime = System.currentTimeMillis() + 15000;
while (System.currentTimeMillis() < futureTime) {
synchronized (this) {
try {
wait(futureTime - System.currentTimeMillis());
showPushNotification();
} catch (InterruptedException e) {
}
}
}
}
}
};
Thread thread = new Thread(r);
thread.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Related
i am facing issue to start a service from fragment on a button click.
below is overview of Service class
public class FtpServiceDownload1 extends Service {
IBinder mBinder = new LocalBinder();
static String LOG_TAG = "Background Service 001";
private Handler customHandler = new Handler();
private Handler checkServiceHandler = new Handler();
long timeInMilliseconds = 0L;
long timeSwapBuff = 0L;
long updatedTime = 0L;
private long startTime = 0L;
public boolean isFtpConnected(){
if(ftpHelperObj!=null){
return ftpHelperObj.ftp.isConnected();
}
return false;
}
public FtpHelperObject ftpHelperObj;
//#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.e(LOG_TAG,"binded called");
return mBinder;
}
public class LocalBinder extends Binder {
public FtpServiceDownload1 getServerInstance() {
return FtpServiceDownload1.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TO DO WORK
return(START_NOT_STICKY);
}
String NOTIFICATION_CHANNEL_ID = "com.form.lasertrac.ftpquery";
String channelName = "My Background Service";
static Notification notification = null;
static NotificationChannel notificationChannel = null;
static NotificationManager notificationManager = null;
static NotificationCompat.Builder notificationBuilder = null;
int id = 1;
private void startMyOwnForeground(){
notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
notificationChannel.setLightColor(Color.BLUE);
notificationChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
notificationBuilder = new NotificationCompat.Builder(getApplicationContext(), NOTIFICATION_CHANNEL_ID);
notification = notificationBuilder.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher_lasertrac)
.setContentTitle("FTP Query in background.")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(id, notification);
}
void notifyNotification(String msg){
notificationBuilder.setContentText("FTP Check "+msg);
notificationBuilder.setContentTitle("FTP Check Service ");
Date d = Calendar.getInstance().getTime();
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(FunctionsHelper.onlyForTimeFormatterView.format(d)+" "+msg));
Notification notification = notificationBuilder.getNotification();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notificationManager.notify(id, notification);
}
}
and below code in my fragment to start service
btn_service_load_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent mIntent2 = new Intent(getContext(), FtpServiceDownload1.class);
getContext().bindService(mIntent2, mConnectionFtpQuery, getContext().BIND_AUTO_CREATE);
getContext().startService(mIntent2);
}
});
FtpServiceDownload1 mServiceFtpQueryService ;
boolean mBoundedFtpQuery ;
ServiceConnection mConnectionFtpQuery = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
Toast.makeText(getContext(), "Ftp Query Service is disconnected", Toast.LENGTH_LONG).show();
mBoundedFtpQuery = false;
mServiceFtpQueryService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Toast.makeText(getContext(), "Ftp Query service started", Toast.LENGTH_LONG).show();
mBoundedFtpQuery = true;
FtpServiceDownload1.LocalBinder mLocalBinder = (FtpServiceDownload1.LocalBinder) service;
mServiceFtpQueryService = mLocalBinder.getServerInstance();
}
};
my purpose is to start some service for particular work and stop it after work done.
when i click to start service, my application hangs and doesn't respond, if i call this service from my MainActivity class like below, it works
#Override
protected void onStart() {
super.onStart();
Intent mIntent2 = new Intent(this, FtpServiceDownload1.class);
bindService(mIntent2, mConnectionFtpQuery, BIND_AUTO_CREATE);
startService(mIntent2);
}
i need to start a service whenever the user wants, its the same service with only different input data. I tried with workmanager and using threads libraries, its important to say that is a long running task. Down below is my code
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startThread(View view){
Value1 = findViewById(R.id.Value1);
Value2 = findViewById(R.id.Value2);
String value1 = Value1.getText().toString();
String Value2 = Value2.getText().toString();
Intent service = new Intent(this, servicio.class);
service.putExtra("value1", value1);
service.putExtra("value2", value2);
startService(service);
service file
public class servicio extends Service {
private static final String TAG = "service";
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String rapida = intent.getStringExtra("value1");
String lenta = intent.getStringExtra("value2");
int value = Integer.parseInt(rapida);
int to = Integer.parseInt(lenta);
for (int i = value; i<to; i++){
Log.d(TAG, "number: " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Intent notificationintent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationintent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Counting")
.setContentText("from" + rapida + "to" + lenta)
.setSmallIcon(R.drawable.ic_android)
.setContentIntent(pendingIntent)
.build();
startForeground(new Random().nextInt(), notification);
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
i need to make to run multiple of this at the same time no matter with what.
I am trying to make a countdown timer screen that will keep counting down if I back out of the app or change screens or something. For some reason it keeps crashing saying that timeLeft is null. I can't figure out why it would be because I know the time variable in my Countdown class is there. Thanks for any help!
Countdown Activity
public class Countdown extends Activity {
public static String time;
public static String address;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_countdown);
Intent confIntent = getIntent();
time = confIntent.getStringExtra("time");
address = confIntent.getStringExtra("address");
LocalBroadcastManager.getInstance(this).registerReceiver(
new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
TextView textView= findViewById(R.id.t1);
String timeLeftString = intent.getStringExtra("timeSent");
int timeLeft = Integer.parseInt(timeLeftString);
if(timeLeft>0) {
textView.setText("You have " + timeLeft + " minutes left");
}
else{
textView.setText("Y'all outta time, see ya again soon!");
killIt();
}
}
}, new IntentFilter(CountdownService.ACTION_LOCATION_BROADCAST)
);
Intent toService = new Intent(this, CountdownService.class);
startService(toService);
}
#Override
protected void onResume() {
super.onResume();
TextView textView= findViewById(R.id.t1);
textView.setText("You have " + CountdownService.toSend + " minutes left");
}
#Override
protected void onPause() {
super.onPause();
}
public void killIt(){
stopService(new Intent(this, CountdownService.class));
}
}
Countdown Service
public class CountdownService extends Service{
public static int toSend=0;
public int time;
public static final String
ACTION_LOCATION_BROADCAST = CountdownService.class.getName() +
"LocationBroadcast";
public final String timeFromCD = Countdown.time;
public final String address = Countdown.address;
#Override
public void onCreate() {
super.onCreate();
time = Integer.parseInt(timeFromCD);
time = time*60000;
new CountDownTimer(time, 5000) {
public void onTick(long millisUntilFinished) {
int timeLeftInt = (int) Math.ceil((double) millisUntilFinished / 60000); //Whole number of minutes left, ceiling
sendBroadcastMessage(timeLeftInt);
toSend = timeLeftInt;
if(timeLeftInt == 5){
Notify("Not Done");
}
}
public void onFinish() {
sendBroadcastMessage(0);
Notify("done");
Response.Listener<String> response = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//creating a jsonResponse that will receive the php json
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(CountdownService.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
SpotAmountRequest spotAmountRequest = new SpotAmountRequest(address, "0", response);
RequestQueue queue = Volley.newRequestQueue(CountdownService.this);
queue.add(spotAmountRequest);
}
}.start();
}
private void sendBroadcastMessage(int timeSent) {
Intent intent = new Intent(ACTION_LOCATION_BROADCAST);
intent.putExtra("timeSent", timeSent);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void Notify(String doneness){
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, Map.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
if(doneness.equals("done")) {
Notification n = new Notification.Builder(this)
.setContentTitle("Time to leave!")
.setContentText("Your PrePark spot has expired, time to go home!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Vibrate for 500 milliseconds
v.vibrate(1000);
}
else{
Notification n = new Notification.Builder(this)
.setContentTitle("Ya got 5 minutes left in your PrePark spot!")
.setContentText("Better get going soon here")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pIntent)
.setAutoCancel(true)
.build();
notificationManager.notify(0, n);
}
}
}
You're storing an int value in the intent that you're broadcasting from the service, but you're then trying to get it out as a String where you receive the broadcast. Either change the receiver to use getIntExtra instead of getStringExtra, or convert the int to a String in the service before storing it in the intent.
Hello friends i am creating one android app App lock application in which user can lock the application for that i am using one background service which run in background always. My service is run fine in all device but in some new device like OPPO,Redme Mi and Lenovo Mobile there is one advace feature like user can clean all the running task from the cleaner and because of this advance features when user clean all the task my service also stop and app lock will not work so user need to go in application and manual start the service is there any solution to protect my service from this.
one of app lock have this kind of solution
https://play.google.com/store/apps/details?id=com.domobile.applock
This app service is start after the clean task i also want to do same for my application i tried many solution but not getting any result i my service code is as below
public class MyAppLockService extends Service {
public static int BuildV = 0;
public static final int NOTIFICATION_ID = 11259186;
private static boolean flag;
public static boolean isLauncher;
public static boolean isRunning;
public static ArrayList<String> locked_list;
public static String pack;
public static Thread th;
String currentHomePackage;
private boolean isRefreshedList;
boolean mAllowDestroy;
BroadcastReceiver mReciever;
private boolean mShowNotification;
UsageStatsManager mUsageStatsManager;
ActivityManager manager;
PowerManager pmanager;
SharedPreferences prefs;
public boolean run;
Timer f6t;
TimerTask tt;
class C02221 extends BroadcastReceiver {
C02221() {
}
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Utils.ACTION_UPDATE)) {
MyAppLockService.this.refreshList();
} else if (intent.getAction().equals(Utils.ACTION_STOP_SELF)) {
MyAppLockService.this.doStopSelf();
} else if (intent.getAction().equals(Utils.ACTION_REMOVE_APP)) {
MyAppLockService.this.removeAppFromLockedList(intent
.getStringExtra("packName"));
}
}
}
#SuppressLint("NewApi")
class C02232 extends TimerTask {
C02232() {
}
#SuppressLint("NewApi")
public void run() {
if (Utils.isScreenOn(MyAppLockService.this.pmanager)) {
MyAppLockService.this.isRefreshedList = false;
String current = "";
try {
current = Utils.getProcess(
MyAppLockService.this.mUsageStatsManager,
MyAppLockService.this.getApplicationContext());
} catch (Exception e) {
current = "";
}
if (current != null) {
if (MyAppLockService.flag
&& current
.equals(MyAppLockService.this.currentHomePackage)) {
if (MyAppLockService.this.prefs.getBoolean(
"immediately", true)) {
MyAppLockService.locked_list = new DBHelper(
MyAppLockService.this
.getApplicationContext())
.getApsHasStateTrue();
}
MyAppLockService.flag = false;
}
if (!current
.equals(MyAppLockService.this.currentHomePackage)
&& MyAppLockService.locked_list.contains(current)) {
Intent it;
if (MyAppLockService.BuildV >= 23) {
long endTime = System.currentTimeMillis();
UsageEvents usageEvents = MyAppLockService.this.mUsageStatsManager
.queryEvents(endTime - 10000, endTime);
Event event = new Event();
while (usageEvents.hasNextEvent()) {
usageEvents.getNextEvent(event);
}
if (current.equals(event.getPackageName())
&& event.getEventType() == 1) {
MyAppLockService.pack = current;
if (MyAppLockService.this.prefs.getBoolean(
"isPattern", false)) {
MyAppLockService.this
.confirmPattern(current);
} else {
it = new Intent(
MyAppLockService.this
.getApplicationContext(),
AppLockActivity.class);
it.setFlags(DriveFile.MODE_READ_ONLY);
MyAppLockService.this
.getApplicationContext()
.startActivity(it);
}
MyAppLockService.flag = true;
return;
}
return;
}
MyAppLockService.pack = current;
if (MyAppLockService.this.prefs.getBoolean("isPattern",
false)) {
MyAppLockService.this.confirmPattern(current);
} else {
it = new Intent(
MyAppLockService.this
.getApplicationContext(),
AppLockActivity.class);
it.setFlags(DriveFile.MODE_READ_ONLY);
MyAppLockService.this.getApplicationContext()
.startActivity(it);
}
MyAppLockService.flag = true;
}
}
} else if (!MyAppLockService.this.isRefreshedList) {
MyAppLockService.this.refreshList();
}
}
}
public MyAppLockService() {
this.run = true;
}
static {
BuildV = VERSION.SDK_INT;
}
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
this.prefs = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
this.manager = (ActivityManager) getApplicationContext()
.getSystemService("activity");
this.pmanager = (PowerManager) getApplicationContext()
.getSystemService("power");
if (BuildV >= 21) {
this.mUsageStatsManager = (UsageStatsManager) getApplicationContext()
.getSystemService("usagestats");
}
startNotification();
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.HOME");
this.currentHomePackage = getPackageManager().resolveActivity(intent,
Cast.MAX_MESSAGE_LENGTH).activityInfo.packageName;
this.mReciever = new C02221();
IntentFilter filter = new IntentFilter(Utils.ACTION_UPDATE);
filter.addAction(Utils.ACTION_STOP_SELF);
filter.addAction(Utils.ACTION_REMOVE_APP);
registerReceiver(this.mReciever, filter);
refreshList();
this.tt = new C02232();
this.f6t = new Timer();
this.f6t.schedule(this.tt, 500, 500);
super.onCreate();
Calendar cal = Calendar.getInstance();
Intent intent12 = new Intent(getBaseContext(),MyAppLockService.class);
PendingIntent pintent = PendingIntent.getService(getBaseContext(), 0, intent12, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),5, pintent);
}
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);
}
public void onDestroy() {
try {
this.f6t.cancel();
this.tt.cancel();
} catch (Exception e) {
e.printStackTrace();
}
Intent intent1 = new Intent("com.android.techtrainner");
intent1.putExtra("yourvalue", "torestore");
sendBroadcast(intent1);
}
public void refreshList() {
locked_list = new DBHelper(getApplicationContext())
.getApsHasStateTrue();
if (locked_list.size() == 0) {
doStopSelf();
}
this.isRefreshedList = true;
}
#SuppressLint({ "InlinedApi" })
private void startForegroundWithNotification() {
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,
Calculator_Activity.class), 0);
String title = getString(R.string.app_name);
String content = getString(R.string.app_name);
Builder nb = new Builder(this);
nb.setSmallIcon(R.drawable.ic_transparent);
nb.setContentTitle(title);
nb.setContentText(content);
nb.setWhen(System.currentTimeMillis());
nb.setContentIntent(pi);
nb.setOngoing(true);
nb.setPriority(0);
startForeground(NOTIFICATION_ID, nb.build());
}
private void startNotification() {
startForegroundWithNotification();
if (!this.mShowNotification) {
HelperService.removeNotification(this);
}
}
private void doStopSelf() {
this.mAllowDestroy = true;
unregisterReceiver(this.mReciever);
stopForeground(true);
stopSelf();
}
private void confirmPattern(String st) {
Intent pIntent = new Intent(getApplicationContext(),
ResetActivity.class);
pIntent.putExtra("isFromReset", true);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
12345, pIntent, DriveFile.MODE_READ_ONLY);
Intent intent = new Intent(LockPatternActivity.ACTION_COMPARE_PATTERN, null,
getApplicationContext(), LockPatternActivity.class);
intent.putExtra("packName", st);
intent.putExtra("isStealthMode", this.prefs.getBoolean(
AlpSettings.Display.METADATA_STEALTH_MODE, false));
intent.putExtra("isFromLock", true);
intent.setFlags(DriveFile.MODE_READ_ONLY);
intent.addFlags(Cast.MAX_MESSAGE_LENGTH);
intent.putExtra(LockPatternActivity.EXTRA_PENDING_INTENT_FORGOT_PATTERN, pi);
startActivity(intent);
}
private void removeAppFromLockedList(String packName) {
locked_list.remove(packName);
}
if there is any solution for it then please help me out thanks in advance
Restart the service when it's stopped i.e. System will call onDestroy() on service which is stopped.
set a variable in service class to check service is running or not.
let boolRuningService is a variable
Intent intent = new Intent(DashboardScreen.this, ServiceClass.class);
PendingIntent pintent = PendingIntent.getService(DashboardScreen.this, 0, intent, 0);
if(!ServiceClass.boolRuningService){
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);
}
I try to send data to server every 15 seconds so i used broadcast receiver and Android service but it did not work any more.I check Internet Connection Every 15 second and when connection is available it send data to server.
Test.java
public class Test extends AppCompatActivity {
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
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(), 15000, pendingIntent);
}
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, BackgroundService.class);
context.startService(background);
}
}
BackgroundService.java
public class BackgroundService extends Service {
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
internet();
System.out.println("call every 15 seconds");
Log.d("Background","Services run every 15 second");
stopSelf();
}
};
#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;
}
private void internet() {
Helper hp = new Helper(context);
if (hp.isonline() == true) {
System.out.println("net connect");
} else {
System.out.println("net not available");
}
}
}
}
Manifest.xml
<service android:name=".service.BackgroundService" />
<receiver android:name=".service.AlarmReceiver"></receiver>
hole code return in logcat print message only one time, not every 15 seconds.