Service unable to send sms through build-in app - android

I have an application with only a service. Following is my code of the service, it is unable to call the device's build-in sms app.
public class smsservice extends Service {
private static final String TAG = "MyService";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "Service created.");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "Service started.");
try {
String sb = (String) intent.getSerializableExtra("dest1");
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", sb);
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Log.d("slog", "onDestroy()");
super.onDestroy();
}
}
I have include the permission in the manifest file
<uses-permission android:name="android.permission.SEND_SMS" />
Is there something I am missing or is it even possible

I have an application with only a service
First, I hope you have a plan for something to run your service. By default, nothing in your app will ever run.
Second, I hope that you can afford security guards. Since you have no activity, the only way anything will ever cause your service to run is if your service is exported. Unless you have some special tricks in mind, this means that any app can ask your service to send an SMS. If this gets exploited, your users may come after you, with guns and knives and so forth.
Third, there is no requirement for an Android device to support sending an SMS via ACTION_VIEW, let alone using some undocumented Intent extras. Use ACTION_SEND or ACTION_SENDTO.
it is unable to call the device's build-in sms app.
If you look at LogCat, I am guessing that you will see an error message mentioning that you need to add FLAG_ACTIVITY_NEW_TASK to the Intent to be able to start it from a service. You need to call addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) on the Intent, before calling startService().
That is because popping up an activity in the middle of whatever the user is doing usually is inappropriate. You do not know if the user is doing something with their device, when all of a sudden, your activity takes over the foreground. Users may also come after you with guns and knives for interrupting their game, their movie, their navigation instructions, etc. Hence, you should hire some security guards.
I have include the permission in the manifest file
That is for sending an SMS via SmsManager. You should not need it for ACTION_SEND or ACTION_SENDTO.

Related

Where do Toast.makeText().show() messages go in an Activity-less service?

I have a MyServiceClass defined as follows:
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
If I call startService(new Intent(getBaseContext(), MyService.class)); from an activity class in the same package/app/APK, then I can see the Toast message.
But if I put this class in an application with no activity whatsoever (that is, service-only application) by simply tying it to boot receiver:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, com.example.tutorialspoint7.noactivity.MyService.class));
}
}
Then, when the service starts, I no longer see the message.
I can restart the service on demand via Package Browser:
I understand that if there is no activity to provide a UI, then those messages don't really have where to be displayed. My questions, though, are:
Is there a default place where I can find these messages? (e.g. log file, buffer, LogCat, etc.)
Can I redirect these messages to the home screen current screen?
Why isn't the Android Studio framework display a warning when it sees/builds an APK that contains Toast.makeText().show() messages that have nowhere to be displayed?
The Toast messages are not related to your activity, but it a service on the Android UI which can be accessed by any application/activtiy. A simple glance at the source code would tell you that.
So if you pass the application context by getApplicationContext(), it will display from an activity-less application too.
FYI:
The toast is not bound to the UI of your activity. If you display a toast from your activity and then minimize it(press home), the toast remains on the home screen.
No, you cannot see toast messages that didnt get displayed because they were not enqued in the service itself.
Regarding android studio warning, I'm not sure why it doesn't report it, you could raise an issue regarding the same. But I had read that android developers suggest using the application context in all instances, even when an activity context is available. Sorry i cannot find the source from where I read this.
Use getApplicationContext() to access an activity-free context

Creating a periodical service in Android

I'm trying to create a periodical service where I can validate certain values stored on my mobile with the data I have on my API Server. If a user's password gets changed or if the user gets deleted the API Server should send a response back so the mobile app knows the user should be signed out. The request/response is not the problem. Just having issues getting the service periodically.
MyService.class:
public class MyService extends IntentService {
private static final String TAG = "MyService";
public MyService() {
super("MyService");
}
#Override
protected void onHandleIntent(Intent intent) {
// Normally we would do some work here, like download a file.
// For our sample, we just sleep for 5 seconds.
try {
Thread.sleep(5000);
Log.d(TAG,"loop service");
} catch (InterruptedException e) {
// Restore interrupt status.
Thread.currentThread().interrupt();
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
}
Inside the onCreate of another random class:
Context mContext = getApplicationContext();
Intent i= new Intent(mContext, MyService.class);
i.putExtra("KEY1", "Value to be used by the service");
mContext.startService(i);
The service does start (it shows me the Log.d), how do I continue from here to get it restarted or to make it start after certain time?
First things first: IntentService is designed only to execute a queue of tasks off the main thread. So you must create a new one every time you want to check for updates: for that see Alarm Manager
But this is not necessarily the best way to do it. Instead of you polling the server for changes, try the push notifications approach.

Can't get embedded BroadcastReceiver to work

This is for a GPS. I have a parent class with an embedded receiver class, and a separate LocationTrackingService class that handles the GPS stuff. I need to Broadcast the mileage traveled to update the UI, but the broadcast is never received. This is the only BroadcastReceiver in the project. I guess I could set a timer to have my ServiceConnection check every couple of seconds and grab the new mileage, but that's bad coding.
Nothing is in the Manifest because I'm registering and unregistering dynamically.
public class Parent
{
GPSReceiver gpsreceiver;
public class EmbeddedReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent)
{
Bundle extras = intent.getExtras();
if (extras != null) {
distance = extras.getDouble(LocationTrackingService.UPDATE_MILEAGE_MESSAGE);
}
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
gpsReceiver = new EmbeddedReceiver();
}
private void gpsStart()
{
if (gpsReceiver != null) {
intentFilter = new IntentFilter();
intentFilter.addAction("don't know what goes here");
LocalBroadcastManager.getInstance(this).registerReceiver(gpsReceiver, intentFilter);
}
}
private void gpsStop()
{
if (gpsReceiver != null) {
LocalBroadcastManager.getInstance(this).unregisterReceiver(gpsReceiver);
}
}
}
public class LocationTrackingService extends Service
{
private LocalBroadcastManager broadcaster;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
broadcaster = LocalBroadcastManager.getInstance(this);
return START_STICKY;
}
.... code
private void sendResult(String message)
{
Intent i = new Intent("ParentActivity");
i.setAction("ParentActivity");
if (message != null) {
i.putExtra(message, mileageRunningTotal);
}
broadcaster.sendBroadcast(i);
}
}
When I follow the code into LocalBroadcastManager, on line 215 it does mActions.get(intent.getAction() to get an ArrayList<ReceiverRecord>, and it's null, but I don't know why.
I appreciate any help you can give.
Broadcasts work in such a way that the action acts as a trigger for the receiver. In other words, there are tons of broadcasts being sent around throughout your phone at any given time, the goal of the receiver is to catch the broadcast with the corresponding action when it flies by. It will let all other broadcasts continue through without interruption. Once it finds the one it is looking for, it will receive it and perform the onReceive() functionality.
Though an action can be any string key you care for it to be, it is advised to add in your package name. This gives specificity to your broadcast and allows your broadcast to be more easily managed in the barrage of broadcasts that your phone is sending. This is important as broadcasts can be sent between applications. It makes it so you avoid the following scenario
Application A sends out a system broadcast with action "SOME_ACTION" which we have no interest in. Application B will also be sending out a local broadcast with action "SOME_ACTION" which we are awnt to receive. We will setup Receiver 1 to look for and receive the action "SOME_ACTION" from Application B. However, because of conflicting actions, when Application A sends out a broadcast of "SOME_ACTION", we will inappropriately receive it in Receiver 1 and perform our onReceive() functionality as though we had just received a local broadcast from Application B.
Following recommended convention, you avoid the above situation by doing the following
Instead of setting your action as "SOME_ACTION", it would be set to "com.app_b.package.SOME_ACTION". That way when the broadcast action "com.app_a.package.SOME_ACTION" passes by, it won't be confused for our action and will be allowed to pass.
There may be other reasons for using package name, and this may not be the best of them, but to the best of my knowledge this is the reasoning behind the convention.
I cant see the declaration for the broadcaster object.
broadcaster.sendBroadcast(i);
Is it a Local Broadcast Manager instance?
If not it won't work.

Android: Re-invoke application if task manager kill

Application thread get close if its killed by task manager. Need to re-invoke application as though its killed by other application or task manager. Any idea?
You have to run background service with START_STICKY command.
Just extends Service and override onCommand like this :
#Override
public int onStartCommand(Intent intent,int flags,int startId) {
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
Like this your Service is restart when it's close (by system or anything else)
You just have now check on your service (onCreate for example) if application is running or not and launch it again if not. I suppose PackageManager let you check this or simply put a static boolean is_alive to see if your activity is always running.
Regards
Jim
Bug in Android 2.3 with START_STICKY
I needed to keep alive a Service with all my forces. If the service is running anytime you can pop the UI.
onDestroy()
it will re-launch.
Can't be uninstalled the app, because it has a Device Administrator.
It is a kind of parental control, the user knows it is there.
Only way to stop is to remove the Device Admin, and uninstall it, but removing Device Admin will lock the phone as Kaspersky how it does.
There are a loot of braodcast receivers, such as boot finshed, user presen, screen on, screen off... , many other, all starting the service, you can do it with UI too. Or in the service check if your activity alive , visible, if not, than pop it.
I hope you will use with good reason the info!
Edit: Restart service code snippet:
// restart service:
Context context = getApplicationContext();
Intent myService = new Intent(context, MyService.class);
context.startService(myService);
Edit2: add spippet to check if the service is running in ... a load of Broadcasts
public static boolean isMyServiceRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(service.service.getClassName())) {
Log.d("myTag", "true");
return true;
}
}
Log.d("myTag", "false");
return false;
}
Edit3 other service start:
public static void startTheService(Context context) {
Intent myService = new Intent(context, MyService.class);
context.startService(myService);
}
Dont't forget Android 2.3 bug: do the logic for initialization in
#Override
public void onCreate()
and not in:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
While look at Google IO official product source code I have found the following
((AlarmManager) context.getSystemService(ALARM_SERVICE))
.set(
AlarmManager.RTC,
System.currentTimeMillis() + jitterMillis,
PendingIntent.getBroadcast(
context,
0,
new Intent(context, TriggerSyncReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT));
URL for code
You can start a sticky service and register an alarm manager that will check again and again that is your application is alive if not then it will run it.
You can also make a receiver and register it for <action android:name="android.intent.action.BOOT_COMPLETED" /> then you can start your service from your receiver. I think there should be some broadcast message when OS or kills some service/application.
Just to give you a rough idea I have done this and its working
1) register receiver
Receiver Code:
#Override
public void onReceive(Context context, Intent intent) {
try {
this.mContext = context;
startService(intent.getAction());
uploadOnWifiConnected(intent);
} catch (Exception ex) {
Logger.logException(ex);
Console.showToastDelegate(mContext, R.string.msg_service_starup_failure, Toast.LENGTH_LONG);
}
}
private void startService(final String action) {
if (action.equalsIgnoreCase(ACTION_BOOT)) {
Util.startServiceSpawnProcessSingelton(mContext, mConnection);
} else if (action.equalsIgnoreCase(ACTION_SHUTDOWN)) {
}
}
Service Code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Logger.logInfo("Service Started onStartCommand");
return Service.START_STICKY;
}
I prefer doing nothing in onStartCommand because it will get called each time you start service but onCreate is only called 1st time service is started, so I do most of the code in onCreate, that way I don't really care about weather service is already running or not.
according to #RetoMeyer from Google, the solution is to make the app "sticky".
for this, you must establisH START_STICKY in your intent service management.
check this reference from developer android
Yes, Once memory low issue comes android os starts killing application to compensate the required memory. Using services you can achieve this, your service should run parallely with your application but see, some of the cases even your service will be also killed at the same time. After killing if memory is sufficient android os itself try to restart the application not in all the cases. Finally there is no hard and fast rule to re-invoke your application once killed by os in all the cases it depends on os and internal behaviours.

How do I cancel all pending intents that are qued for intent Service

I have an intentservice that gets qued by the user and by my app automatically. I need to be able to kill all pending intents that are qued when the user logs out of my application, but I cannot seem to get that to work. I have tried stopService() and stopself(), but the intents continue to fire off the intentservice after the user has logged out. I would try to get the id of the intent but that is difficult as everytime the intentservice starts, the variable holding the intent id's is empty. Here is my intentservice code:
public class MainUploadIntentService extends IntentService {
private final String TAG = "MAINUPLOADINTSER";
private GMLHandsetApplication app = null;
private SimpleDateFormat sdf = null;
public boolean recStops = true;
public MainUploadIntentService() {
super("Main Upload Intent Service");
GMLHandsetApplication.writeToLogs(TAG,
"GMLMainUploadIntentService Constructor");
}
#Override
protected void onHandleIntent(Intent intent) {
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Started");
if (app == null) {
app = (GMLHandsetApplication) getApplication();
}
uploadData(app);
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Finished");
}
#Override
public void onDestroy() {
GMLHandsetApplication.writeToLogs(TAG, "onDestroy Started");
app = null;
stopSelf();
GMLHandsetApplication.writeToLogs(TAG, "onDestroy completed");
}
public void uploadData(GMLHandsetApplication appl) {
//All of my code that needs to be ran
}
Unfortunately, I don't think it's possible to accomplish that with the standard IntentService methods since it doesn't offer a way to interrupt it while it's already going.
There are a few options I can think of that you can try to see if they fit your need.
Copy the IntentService code to make your own modifications to it that would allow you to remove pending messages. Looks like someone had some success with that here: Android: intentservice, how abort or skip a task in the handleintent queue
Instead of copying all the IntentService code, you might also be able to Bind to it like a normal Service (since IntentService extends Service) so you can write your own function to remove pending messages. This one is also mentioned in that link.
Rewrite the IntentService as a regular Service instead. With this option, you'd have more control over adding and removing messages.
I had what sounds like a similar situation where I was using an IntentService, and I eventually just converted it to a Service instead. That let me run the tasks concurrently and also cancel them when I needed to clear them.
Here
When should I free the native (Android NDK) handles? is the HangAroundIntentService class that has the method cancelQueue().
The class also has the method
public static Intent markedAsCancelIntent(Intent intent)
that converts an intent into a cancel intent, and
public static boolean isCancelIntent(Intent intent).
The class is based on the open-sourced Google's code.
Just a thought but inside of your onhandleintent can you have an argument that checks to see if app is running if not then don't run the code? example. In the start of your app you could have a static var
boolean appRunning;
Next in your onhandle of the intent, when you set the appRunning to false, after an onPause or onDestroy of activity, you could wrap the onhandleintent code in a boolean:
protected void onHandleIntent(final Intent intent) {
if(MainActivity.appRunning){
...
}
}
Just a thought

Categories

Resources