i am writing a bluetooth app communicating with a bluetooth module. Actually it works very well. But i want the connection to stay established also while the app is in background and other apps are used, so that another activity like incoming sms or something else can trigger my app in background to send messages to my device.
Until now i am very confused how to do this. Can anyone give me advice?
I also checked this: Background Bluetooth App - Threading? but it doesn't help me.
Here is my code so far:
http://pastebin.com/C7Uynuan
Side information: there is a connect button, which establishs the connection and then there are 3 other buttons sending different messages to my device.
In OnResume i reconnect to my device, but this should be not necessary when having a stable connection.
Thanks,
progNewfag
EDIT: Now i am pretty sure that i need to use an IntentService, but not sure how.
You Have to learn the service first
Here is the Example of Service
Create a new Class and Name it for Exmaple: MyService
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
return Null;
}
#Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startId) {
// For time consuming an long tasks you can launch a new thread here...
// Do your Bluetooth Work Here
Toast.makeText(this, " Service Started", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
Now in your main activity you can start the service through this code
startService(new Intent(this, MyService.class));
For Stopping the service put this code in MainActivity
stopService(new Intent(this, MyService.class));
See this Post
Connection between Activity and Service
Also See this link
http://www.javacodegeeks.com/2014/01/android-service-tutorial.html
http://examples.javacodegeeks.com/android/core/service/android-service-example/
EDIT:
Example: Communication between Activity and Service using Messaging
http://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/
Related
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
I am trying to create a softphone application that can receive and make calls with a users credentials. I have everything working but the issue I am having now is keeping the user logged in, or registered, to the SIP Client. I have read many articles to keep the Wifi connection alive while I am trying to connect. I added some code I got from another program and even that doesn't work.
What I really need is a way for the phone to stay registered all the time. I know it can be done because of apps like Linphone and Bria. Does anyone have any suggestions.
Here is my onNetworkChangeReceiver which listens for network changes. Please let me know if this code is garbage and if you have any suggestions please let me know
import com.zxd.activity.util.PhoneState;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
public class OnNetworkChangeReceiver extends WakefulBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PhoneState phoneState = PhoneState.getInstance();
// This is the Intent to deliver to our service.
Intent service = new Intent(context, OnNetworkChangeListener.class);
if(phoneState.threadIntent != null){
WakefulBroadcastReceiver.completeWakefulIntent(phoneState.threadIntent);
}
phoneState.setThreadIntent(intent);
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, service);
}
}
PS: This receiver gets android.net.conn.CONNECTIVITY_CHANGE
This is the OnNetworkChangeListener
import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import com.zxd.activity.SipManager;
public class OnNetworkChangeListener extends IntentService{
private static String TAG = "OnNetworkChangeListener";
private static Intent i;
public OnNetworkChangeListener() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
i = intent;
SipManager sipManager = SipManager.getInstance();
sipManager.onNetworkChange();
}
#Override
public void onDestroy(){
super.onDestroy();
if(i != null){
WakefulBroadcastReceiver.completeWakefulIntent(i);
}
}
}
I used this for my app. But in the end, that damage my battery.
Android Developer Docs:
Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER);
Have you tried to use WifiLock?
For my solution I looked at linphone. They are an open-source softphone application and they have a great way to implement a KeepAlive Service and KeepAlive Handler. This has worked for me
Did you try using a WakeLock? Also have a look at the PowerManager class.
Hope this helps.
I am starting and stopping a service from an activity calling startSertice()/stopService() (when user select/deselect a check box and service is not bounded). Every thing is working fine even though the activity that starts the service is closed. In "Running apps" I'm able to see 1 processes, 1 service running. But when I kill the application, using Task manager kind of application, the process is getting killed and service is not working though the running apps showing 0 processes, 1 service. How to make the service working in such situations? I observed the same in some other security applications like Avast with 0 processes, 1 service, while service working properly. Please help me out on this.
Following is the activity on click method
#Override
public void onClick(View arg0) {
boolean value = checkBox.isChecked();
if(value){
// start the service
startService(new Intent(this, MyService.class));
Toast.makeText(this, "Background service started", Toast.LENGTH_SHORT).show();
} else {
stopService(new Intent(this, MyService.class));
Toast.makeText(this, "Background service stopped", Toast.LENGTH_SHORT).show();
}
}
Following is the service class:
public class MyService extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate(){
super.onCreate();
Log.d("######Service","Service created successfully");
}
#Override
public int onStartCommand(Intent intent, int flags, int stardId){
Log.d("######Service","Service started successfully");
IntentFilter powerButtonIntentFilter = new IntentFilter();
powerButtonIntentFilter.addAction("android.intent.action.SCREEN_ON");
this.registerReceiver(pbReceiver, powerButtonIntentFilter);
Log.d("#######","Power button register registered");
return START_STICKY;
}
#Override
public void onDestroy(){
Log.d("######Service","Service destroyed successfully");
this.unregisterReceiver(pbReceiver);
Log.d("#######","Power button register un-registered");
super.onDestroy();
}
}
Everything is working fine in ideal case. SCREEN ON action is being listened by the broadcast receiver properly even when the activity that starts the service is closed. I am able to see the app running in settings. But when I force kill the process using Task Manager kind of applications, processes is getting killed and in running apps I am able to see 0 process, 1 service running. Though the service is running after force killing the app from Task manager, broadcast receiver is not listening to the SCREEN ON action. Please help me out on this.
Thanks, JK
Hi i'm trying to make an app which can be run in background and does not go to PAUSE mode.
I have read about services and tried to do that,but dint actually get how to use Service to do so.
Please help me out with services or any other way to to run an application in background.
To create a application to run in the background of other current activities, one needs to create a Service. The Service can run indefinitely (unbounded) or can run at the lifespan of the calling activity(bounded).
Please note that a Service has a different lifecycle than activities therefore have different methods. But to begin a service in the application a call to startService() which envokes the service onCreate() method and onStart() beginning running the service.
https://thenewcircle.com/s/post/60/servicesdemo_using_android_services
Source
http://thenewcircle.com/static/tutorials/ServicesDemo.zip
Music File
http://thenewcircle.com/static/tutorials/braincandy.m4a
service class extends Service{
//service methods
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
player = MediaPlayer.create(this, R.raw.braincandy);
player.setLooping(false); // Set looping
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
It works perfect, i have tested this also.
http://developer.android.com/reference/android/app/Service.html
Android: How to periodically send location to a server
keep application running in background
Pls let me know if still ur facing any problem :)
Try something like below.
The following code start new activity.
Intent intent = new Intent(MainActivity.this, AppService.class);
startService(intent);
// This function is used to hide your app
hideApp(getApplicationContext().getPackageName());
System.out.println("Inside of main");
}
private void hideApp(String appPackage) {
ComponentName componentName = new ComponentName(appPackage, appPackage
+ ".MainActivity");
getPackageManager().setComponentEnabledSetting(componentName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
So basically do your task whatever you want to do in AppService class
and in manifest file declare service class as a service not as an activity so it should be like this
<service android:name=".AppService" >
</service>
Android SDK says that remote service runs in another process with the application. I thought it mean if the app stops/ is terminated..., then remote service still remains running. But it does not.
For example I have this remote service:
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.os.IBinder;
import android.util.Log;
public class WatchDogService extends Service {
private Timer timer = new Timer();
#Override
public void onCreate() {
Log.i(WatchDogService.class.getName(), "WatchDog start");
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Log.i(WatchDogService.class.getName(), "WatchDog boo boo!!! ^^");
}
}, 0, 5000);
}
#Override
public void onDestroy() {
Log.i(WatchDogService.class.getName(), "WatchDog stop");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(WatchDogService.class.getName(), "WatchDog has just been called...");
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
}
AndroidManifest.xml:
<service
android:name="WatchDogService"
android:process=":remote" >
<intent-filter>
<action android:name="WatchDogService" />
</intent-filter>
</service>
In another activity I call it as:
startService(new Intent("WatchDogService"));
The service starts ok. But if I go to system apps manager, then stop the app, the service is terminated too.
I want to keep the service running even if the app is terminated. How can I do that?
I want to keep the service running even if the app is terminated. How can I do that?
You don't. If the user terminates your app, your app is terminated, period. The user is in control of their Android device, not you.
Please respect the user's wishes, and try not to build apps that the user will want to force-stop, task-kill, or otherwise get rid of.
Instead of a service you may create a separate application and invoke it or
Instead of a service you may create a separate background application using AIDL described in this link:
http://developer.android.com/guide/components/aidl.html
Note that the AIDL should register a notification with an intent to start the original app when it is done and ask the user if he wishes to act on it.
I expected that "service" means service, not "application". I mean, I want something like "Service manager". But I forgot that the Applications settings in Android is for end-users, not coder.
So far, I got my answer.