I'm building an application in which I use a service to create a background process. but I have a problem.
I use an EditText where the user enters a URL, then I will use that url in the service for check the connection to a website every X minutes. But if the user closes the application, the background process crash because the value of the EditText became Null, and logcat give me null pointer exceptions. I pass the value from the activity to the service with an intent, MainActivity code below:
public void onClickReadWebPage(View v)
{
if(address.getText().toString().trim().length() == 0)
{
Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
}
else
{
time = String.valueOf(address.getText());
i=new Intent(MainActivity.this,MyService.class);
p=PendingIntent.getService(MainActivity.this, 0, i, 0);
i.putExtra("Address", time);
//start the service from here //MyService is your service class name
startService(i);
}
and this is the service code:
#Override
public void onStart(Intent intent, int startId)
{
Address = intent.getStringExtra("Address");
DownloadWebPageTask task = new DownloadWebPageTask();
task.execute(Address);
if(report == "false")
{
//do my stuff
}
else
{
//do my stuff
}
}
Any suggestion?
Just save the value of ediText in SharedPreferences and then retrieve them in your service
.See
How to use SharedPreferences in Android to store, fetch and edit values
Also Problems using SharedPreferences on a Service (getPreferences doesn't exist on a service)
Related
I developed this app that needs to send data to Firestore when user press a button and ends when user stop it (by pressing another button). The data must be sent even if the user is doing other things or even if the user leavs the phone in standby for hours (so i need to avoid Doze and App Standby).
I used a service to achieve this and just one thing seems to work in the wrong way.
Service
public class MyService extends Service {
public static final String CHANNEL_ID = "ForegroundServiceChannel";
// vars declaration
private Date date = null;
// get every X seconds
public static final long DEFAULT_SYNC_INTERVAL = 60000;
private Runnable runnableService = new Runnable() {
#Override
public void run() {
class GetDataTask extends AsyncTask<String, Void, List<Data>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
if(getPositionData.isCancelled()){
return;
}
}
#SuppressLint({"MissingPermission", "HardwareIds"})
#Override
protected List<Data> doInBackground(String... v) {
// skipping get Timestamp code
// skipping get position code
myPos = new Data(position.getId(), latitude, longitude, timestamp);
// Insert data into Firebase
documentReference = firebaseFirestore.collection("data").document();
Map<String, Object> data = new HashMap<>();
data.put("lat", myPos.getLat());
data.put("date", myPos.getDate().toString());
documentReference.set(data).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.i("data", "data added.\n");
}
});
Toast.makeText(DataPollService.this, "" +
"ID: " + myPos.getImei()
+ " Latitude: " + myPos.getLat()
+ " Longitude " + myPos.getLng()
+ " Date: " + myPos.getDate()
, Toast.LENGTH_SHORT).show();
}
}
}, Looper.getMainLooper());
positionsList.add(myPos);
return positionsList;
}
protected void onPostExecute(List<Data> result) {
Position.getInstance().setPositions(result);
}
}
// RUN TASK
getPositionData = new GetDataTask();
getPositionData.execute(position.getId());
handler.postDelayed(runnableService, DEFAULT_SYNC_INTERVAL);
}
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String input = intent.getStringExtra("inputExtra");
createNotificationChannel();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0, notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText(input)
.setSmallIcon(R.drawable.ksurf)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
handler = new Handler();
handler.post(runnableService);
return START_NOT_STICKY;
}
// onBind
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
Log.d("show", "onDestroy");
handler.removeCallbacks(runnableService);
stopSelf();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(serviceChannel);
}
}
}
In MainActivity starting the service like this:
Intent serviceIntent = new Intent(this, MyService.class);
serviceIntent.putExtra("inputExtra", "run");
ContextCompat.startForegroundService(this, serviceIntent);
If I don't use the phone and let the app sending data in background, the data are not sent to Firebase until I open the app back again. The service is not stopped, I just need to open the app in order to send data to firebase!
I read about Firebase Cloud Messaging but I didn't understand if I need them for my purpose. What am I doing wrong?
The data must be sent even if the user is doing other things or even if the user leavs the phone in standby for hours (so i need to avoid Doze and App Standby).
Generally speaking, it is not a good idea to have your app running processes when in Doze or App Standby mode. The Android documentation even points out that Network access is suspended; and therefore, your process might not be guaranteed to run reliably or terminate over other apps that may have a higher priority.
The problem is that if I don't use app for like 1 hour (so phone is in standby) data on firebase are only added when I open the app again. It's like they are saved in cache and sent to DB when app is opened again.
According to the documentation, "Cloud Firestore supports offline data persistence. This feature caches a copy of the Cloud Firestore data that your app is actively using, so your app can access the data when the device is offline. You can write, read, listen to, and query the cached data. When the device comes back online, Cloud Firestore synchronizes any local changes made by your app to the Cloud Firestore backend."
The service is not stopped, I just need to open the app in order to send data to firebase! I read about Firebase Cloud Messaging but I didn't understand if I need them for my purpose.
A recommended solution would to ping your app from your server using Firebase Cloud Messaging when your client app goes into idle mode. This feature is useful when you need to send real-time downstream messages to your backend server or simply notify your client app that new data is available to sync (which may be what you're looking for).
You can refer to the above documentation for further details.
in every platform or language, there is a deferent way to connect to the firebase, so, please more information about the platform can help ??,
but you can check this link maybe his can to help you -> link
I have a service application. I need to send a string to any application (browser, word, ...wherever the keyboard cursor focused). How can I do this?
//onReceive of my service onStartCommand...
#Override
public void onReceive(Context context, Intent intent) {
String textToSend = intent.getStringExtra("data");
if(textToSend!=null && textToSend.length()>0) {
//Here I need send "textToSend" to another application
}else{
Toast.makeText(context, "Error! ", Toast.LENGTH_SHORT).show();
}
}
You can achieve it with Intents. Passing the string value in the URL, specifically: http://developer.android.com/training/sharing/send.html.
You can check this question for more info.
PROBLEM
As topic mention, I don't know why getBooleanExtra() java.lang.NullPointerException.
I understand that sometimes intent may not contains extras.
However, from the below code as you can see there is a default value for each getBooleanExtra() which is false.
So, that's the reason why I don't understand. please advice. thx!
SOME CODE FROM MY SERVICE CLASS
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand()->","Intent Service.... " + intent);
final boolean SLEEP_MODE_ON = intent.getBooleanExtra("SLEEP_MODE_ON",false);
final boolean SLEEP_MODE_OFF = intent.getBooleanExtra("SLEEP_MODE_OFF",false);
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
connectIfNecessary();
if (SLEEP_MODE_ON){
doSleepMode_on();
} else if (SLEEP_MODE_OFF) {
doSleepMode_off();
}
}
});
thread.start();
return START_STICKY;
}
EDIT as some ask Where I call My service?? First, from activity. Second, from broadcastReceiver
ACTIVITY in onCreate()
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Remove title bar
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
startService(new Intent(this,mqttPushService.class)); //Setup MQTT Service
}//END of onCreate()
BroadcastReceiver
public class SleepModeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent sleepModeIntent;
int broadcastID = intent.getIntExtra("BROADCAST_ID",0);
switch (broadcastID) {
case DataManager.BROADCAST_ID_SLEEP_MODE_START :
sleepModeIntent = new Intent(context, mqttPushService.class);
sleepModeIntent.putExtra("SLEEP_MODE_ON",true);
context.startService(sleepModeIntent);
break;
case DataManager.BROADCAST_ID_SLEEP_MODE_STOP :
sleepModeIntent = new Intent(context, mqttPushService.class);
sleepModeIntent.putExtra("SLEEP_MODE_OFF",true);
context.startService(sleepModeIntent);
break;
}
}
}
I ran into this recently. The issue is that even services can be killed and restarted by the system , thats why you have START_STICKY. Unlike when you start the service and you pass a valid intent, when the system restarts the service, the intent is null. I just check for a null intent before trying to extract any extras.
Here is the link to the official android developers blog.
http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
and here is the paragraph which basically says what I say above
START_STICKY is basically the same as the previous behavior, where the service is left "started" and will later be restarted by the system. The only difference from previous versions of the platform is that it if it gets restarted because its process is killed, onStartCommand() will be called on the next instance of the service with a null Intent instead of not being called at all. Services that use this mode should always check for this case and deal with it appropriately.
I've tested my android app successfully using Paypal Sandbox environment. I am about to release my app, so want to change the paypal configuration to 'PRODUCTION'
To do this, I've changed the following for production:
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_PRODUCTION;
private static final String CONFIG_CLIENT_ID = "my client id for production";
private static final String CONFIG_RECEIVER_EMAIL = "live-id#gmail.com";
Now when I try to make a payment using my another paypal account, I am getting error:
Login Failed
System error. Please try again later.
Same thing happens using the emulator with production settings.
My question is do I have to make any other changes to move from sandbox to production env?
Thanks
UPDATE 1
All the above settings are for the 'production' environment.
Using direct payment
I've noticed problems using paypal from my app when I name the String before onCreate so what I did was..
//When you want to initiate payment...
public void onBuyPressed(View pressed) {
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(valuez), "USD", iu);
PaymentActivity.ENVIRONMENT_LIVE);//etc
I dont know if "PRODUCTION" or "LIVE" makes a difference but give it a try.
I'm going to add more hope this helps this is what i did
get rid of all those paypal strings before onCreate and just when they get ready to pay have textbox with onClick is onBuyPressed...
public void onBuyPressed(View pressed) {
TextView inptP =(TextView)findViewById(R.id.WHATHEYAREBUYING);
String iu =inptP.getText().toString();
TextView inptt =(TextView)findViewById(R.id.WHATITCOST);
String it =inptt.getText().toString();
try{
double valuez =Double.parseDouble(it);
if(valuez> 0)
{
PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal(valuez), "USD", iu);
Intent intent = new Intent(this, PaymentActivity.class);
TextView id =(TextView)findViewById(R.id.MYPAYPALID);
String uname = id.getText().toString();
TextView iz =(TextView)findViewById(R.id.MYPAYPALEMAIL);
String insane = iz.getText().toString();
TextView name =(TextView)findViewById(R.id.MYCUSTOMERSNAME);
String custname = name.getText().toString();
Time now = new Time();
now.setToNow();
// comment this line out for live or set to PaymentActivity.ENVIRONMENT_SANDBOX for sandbox
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_LIVE);
// it's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, uname);
// Provide a payerId that uniquely identifies a user within the scope of your system,
// such as an email address or user ID.
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, custname);
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, insane);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
startActivityForResult(intent, 0);
}
else{
Toast.makeText(getApplicationContext(), "You haven't entered anything.",
Toast.LENGTH_LONG).show();
}} catch (NumberFormatException e) {
}}
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
//THINGS YOU WANT IT TO WHEN THE PAYMENT IS FINISHED GO BETWEEN HERE
//AND HERE
if (confirm != null) {
try {
Log.i("paymentExample", confirm.toJSONObject().toString(4));
// TODO: send 'confirm' to your server for verification.
// see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
// for more details.
} catch (JSONException e) {
Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.i("paymentExample", "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
}}
No need to put PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT for live.
This is my code which is working fine.
Declare these constants is class scope. NOTE: There are two client ids in page of your application in developer Paypal. One in "Test credentials" and The other under "Live credentials" that you should click on "show" link in order to see it. Select client id of "Live credentials" if you want to release your application.
private static final String PAYPAL_CLIENT_ID = "YOUR-CLIENT-IT";
private static final String PAYPAL_RECEIVER_EMAIL = "YOUR-EMAIL";
Then define service in onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// start Paypal service
Intent intent = new Intent(this, PayPalService.class);
// live: don't put any environment extra
// sandbox: use PaymentActivity.ENVIRONMENT_SANDBOX
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_PRODUCTION);
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, PAYPAL_CLIENT_ID);
startService(intent);
}
When user hit a button following method will run:
private void openDonateBtnPressed(BigDecimal donation) {
PayPalPayment payment = new PayPalPayment(donation, "USD", "Donation");
Intent intent = new Intent(this, PaymentActivity.class);
// comment this line out for live or set to PaymentActivity.ENVIRONMENT_SANDBOX for sandbox
intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, PaymentActivity.ENVIRONMENT_PRODUCTION);
// it's important to repeat the clientId here so that the SDK has it if Android restarts your
// app midway through the payment UI flow.
intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, PAYPAL_CLIENT_ID);
// Provide a payerId that uniquely identifies a user within the scope of your system,
// such as an email address or user ID.
intent.putExtra(PaymentActivity.EXTRA_PAYER_ID, "<someuser#somedomain.com>");
intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, PAYPAL_RECEIVER_EMAIL);
intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);
startActivityForResult(intent, 0);
}
and this is onActivityResult():
#Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
if (confirm != null) {
try {
Toast.makeText(RateTheAppActivity.this, R.string.rate_donation_received, Toast.LENGTH_LONG).show();
Log.d(TAG, confirm.toJSONObject().toString(4));
} catch (JSONException e) {
Log.e(TAG, "an extremely unlikely failure occurred: ", e);
}
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.d(TAG, "The user canceled.");
}
else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
Log.e(TAG, "An invalid payment was submitted. Please see the docs.");
}
}
I am trying to start a dream service. Currently, this is my code:
#SuppressLint("NewApi")
public class DreamLockService extends DreamService {
private static final String TAG = "DreamLockService";
public Utility utilObj = new Utility();
//private Button btnExit;
private Button btnlogin;
private EditText lgPass;
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
// Exit dream upon user touch
setInteractive(true);
// Hide system UI
setFullscreen(true);
// Set the dream layout
setContentView(R.layout.lockservice);
//setClickListener();
Toast.makeText(this, "Lock Service Created", Toast.LENGTH_LONG).show();
}
//Use this for initial setup, such as calling setContentView().
#Override
public void onDreamingStarted() {
super.onDreamingStarted();
// Exit dream upon user touch
setInteractive(true);
// Hide system UI
setFullscreen(true);
// Set the dream layout
setContentView(R.layout.lockservice);
Toast.makeText(this, "Lock Service Created", Toast.LENGTH_LONG).show();
}
//Your dream has started, so you should begin animations or other behaviors here.
public void onDreamingStopped()
{
super.onDreamingStopped();
}
//Use this to stop the things you started in onDreamingStarted().
public void onDetachedFromWindow()
{
super.onDetachedFromWindow();
}
}
I was unable to start the dream service from another activity. This is what I used:
Intent tempLock = new Intent(MainActivity.this, DreamLockService.class);
//DreamLockService test = new DreamLockService();
startService(tempLock);
I don't understand why it didn't work. How can a dream service be started from another activity?
To start a Dream service from our own app, please try this.
IBinder binder = ServiceManager.getService("dreams");
Parcel data = Parcel.obtain();
data.writeInterfaceToken("android.service.dreams.IDreamManager");
Parcel reply = Parcel.obtain();
try {
if (binder != null)
binder.transact(1, data,reply, Binder.FLAG_ONEWAY);
else
Log.e("TAG", "dreams service is not running");
} catch (RemoteException e) {
e.printStackTrace();
}
To use this, your app should be system app and should have dream permissions in the Manifest file and enable dream setting in Settings.
I tried this and it is working.
You can start the currently selected screen saver using this code:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.android.systemui", "com.android.systemui.Somnambulator");
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
Just need to make sure that your dream service is set and enabled.
Did you include it in your manifest and have an <intent-filter> that matches your action?
If it's ok, then try with:
startService(new Intent(this, DreamLockService.class));
An excellent Services tutorial: http://www.vogella.com/articles/AndroidServices/article.html#scheduleservice_startauto
UPDATE:
As it seems you are not sure if your service is running, you can use this solution found here:
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}