I am trying to make a service in a separate process which should be restarted after manual stop in task manager. Return of START_STICKY in onStartCommand() doesn't work for me. Here is the code:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
Activity starts the service like this:
#Override
protected void onResume() {
doStartService();
super.onResume();
}
private void doStartService() {
Intent intent = new Intent(getApplicationContext(), MyService.class);
startService(intent);
doBindService();
}
private void doBindService() {
bindService(new Intent(this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);
mBound = true;
}
What can be wrong?
Related
I am passing the data from main activity to service.
I am getting these errors in Myservice.java
1. In override oncreate method - method does not override from superclass
2. The displayingText in run - cannot resolve symbol.
Mainactivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//load the layout file
}
String displayingText = "ABC";
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);//(new Intent(this, MyService.class));//use to start the services
mIntent.putExtra("PassToService",displayingText);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
MyService.java
public void onCreate() {
// cancel if service is already existed
if(mTimer!=null)//if mTimer is activated
mTimer.cancel();
else
mTimer=new Timer(); // recreate new timer
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(),0,INTERVAL);// schedule task
}
public int onStartCommand (Intent intent, int flags, int startId) {
String displayingText = intent.getStringExtra("PassToService");
Toast.makeText(getApplicationContext(), displayingText, Toast.LENGTH_SHORT);
return START_STICKY;
}
You have some problem in your code .
1.change the order of the code
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
// edited here
mIntent.putExtra("PassToService",displayingText);
startService(mIntent);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
My code
String displayingText = "abc";
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);//(new Intent(this, MyService.class));//use to start the services
mIntent.putExtra("PassToService",displayingText);
Toast.makeText(this, "Started", Toast.LENGTH_SHORT).show();
}
2.register in your manifest for your service
<service android:name=".your_package.MyService"/>
Registered as
<service
android:name=".MyService"
android:enabled="true" />
But the value return nothing.
for StartService(View v)....
you still haven't implemented any action or event in onCreate method.
if you still have can't resove problem, use "Mainactivity.this" in place of this in StartService method.
You can pass data to service like below :-
Intent intent = new Intent(MainActivity.this , GPSTracker.class);
intent.putExtra(YOURKEY , VALUE);
startService(intent);
and you can get your data on onStartCommand() method :-
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent != null){
intent.getStringExtra(YOURKEY)
}
return START_STICKY;
}
I had done as below. But the toast message return no character(no value)
public int onStartCommand (Intent intent, int flags, int startId) {
String displayingText = intent.getStringExtra("PassToService");
Toast.makeText(this, displayingText, Toast.LENGTH_SHORT).show();
return START_STICKY;
}
You need to use onStartCommand to get the data/values from the activity to service.,
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
after this you can override the oncreate method and display the stuffs.
But you need to remember that ALWAYS ONCREATE METHOD WILL BE EXECUTED WHEN WE USE startservice method in our activity
In Your Activity, just use the below code:
private void initializeService(String Index) {
Intent intent = new Intent(Detail_Test_run.this, Servicelay.class);
intent.putExtra("Index",Index);
startService(intent);
finish();
}
Then in your service use:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
index= intent.getStringExtra("Index");
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
addView(index);
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
For me it worked well, where I started calling all my functionalities from onStartCommand() instead of onCreate()
I think you should use sharedpreferances as data wont be available for service in background.
So in your startService() method:
public void StartService(View v) {
Intent mIntent = new Intent(this, MyService.class);
startService(mIntent);
SharedPreferences sp=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit();
editor.putString("data",displayingText).commit();
editor.apply();}
And in your service class's onStartCommand() add these lines
SharedPreferences prefs = getSharedPreferences("MyPrefs",MODE_PRIVATE);
String string = prefs.getString("data","");
Hope this helps :)
My app use a background music service.
I have a button to quit my app but I can't find anything to close my app and my service.
I bind my service to my activity.
I tried:
unbindService(serviceConnection);
myService().stopSelf();
stopService(new Intent(this, MediaPlayer.class));
and absolutely nothing works !!! The service continues.
How can I do to destroy my service and how can I do to close my app ??
Tx
EDIT:
I use this in the onCreate method
Intent intent = new Intent(this, serviceClass);
bindService(intent, serviceConnection, BIND_AUTO_CREATE);
And in the MediaPlayer class
public class LocalBinder extends Binder {
public MediaPlayer getService() {
return MediaPlayer.this;
}
}
public IBinder onBind(Intent intent) {
Log.i(TAG, "service bound");
init();
return mBinder;
}
And that...
But I dont know if I really need to start the service. Bind the service already starts it
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
Now I did this
#Override
public void onDestroy() {
player.stop();
super.onDestroy();
}
The onDestroy method works only if i unbind the service !
This doesnt work at all:
getService().stopSelf();
this.stopService(new Intent(this, MediaPlayer.class));
So, how can I stop the service and how can I close the app ?
This is what I do in my app. onDestroy() method from the activity will be called when you close your app.
private ServiceConnection musicServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
musicService.setCallbacks(MainActivity.this);
musicServiceBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(TAG, "MusicService service disconnected (unbinded)");
musicServiceBound = false;
}
};
#Override
protected void onStart() {
super.onStart();
Intent intent1 = new Intent(this, MusicService.class);
bindService(intent1, musicServiceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onDestroy() {
super.onDestroy()
if(musicServiceBound){
musicService.stopSelf();
unbindService(musicServiceConnection);
}
}
You wrote myService(), where you are creating another service using ().
For closing your app programmatically you can refer to this question.
i want to receive a broad cast when the screen is turned off in android. I have written the following code. This is the Receiver's code.
#Override
public void onReceive(Context context, Intent intent) {
helper = new FeedReaderDBHelper(context);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
System.out.println("Screen Off Receiver just received something");
if(helper.getValue(FeedReaderContract.FeedEntry.onlock).equals("YES"))
{
helper.lockAll();
wasScreenOn = false;
}
else if(helper.getValue(FeedReaderContract.FeedEntry.onLock3).equals("YES"))
{
System.out.println("Running 3 minutes thread");
Runner runner = new Runner(context);
Thread t = new Thread(runner);
t.setName("LockThreeThread");
t.start();
}
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
I am registering and unregistering the Receiver in a Service. The code is as follows.
Registring Receiver in onStartCommand method
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
isScreenOn = pm.isScreenOn();
RegisterReceiver();
//Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
//System.out.println("StartRemove");
helper = new FeedReaderDBHelper(this);
names = helper.getNames();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
startChecker();
}
});
t.start();
return START_STICKY;
}
And this is how i unregister in onDestroy of the Service method.
private void RegisterReceiver()
{
receiver = Factory.getScreeReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
registerReceiver(receiver, filter);
}
Please let me know what could be the problem. I have been digging into it for long time. Last two days were wasted on this. Nothing seems to work.
I think you're overly complicating this.
This is the activity you would need
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent startServiceIntent = new Intent(this, MyService.class);
startService(startServiceIntent);
}
This is the service
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("APP", "Service started");
ScreenOffReceiver receiver = new ScreenOffReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
return START_STICKY;
}
}
And this is the Broadcast Receiver
public class ScreenOffReceiver extends BroadcastReceiver {
public ScreenOffReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("APP", "EVENT occured");
}
}
I just tried out this code and the logging worked fine.
When you start this via a service, and start a new thread to do the job in the onStartCommand() method, be noted that the thread will start every time you invoke the onCreate() of the activity.
Hope this helps
i have problem with start service after running codes.
my service class:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
mApplication.setService(this);
}
now:
startService(intent); // service run sucess, but after millisecond delay
mApplication.setIsServiceRunning(true);
mApplication.getService().MyMethodAnyThing(); // <--- NullPointerExeption, because in my class mApplication.setService(this) do with delay and getService is null.
i need completed start service. example:
startService(intent);
mApplication.setIsServiceRunning(true);
// i need like listener
#Override
onServiceIsRunComplete() {
// here i'm sure that service is run
mApplication.getService().MyMethodAnyThing();
}
Maybe something like this,
protected ServiceConnection mServerConn = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder binder) {
Log.d(LOG_TAG, "onServiceConnected");
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.d(LOG_TAG, "onServiceDisconnected");
}
}
public void start() {
mContext.bindService(intent, mServerConn, Context.BIND_AUTO_CREATE);
mContext.startService(intent);
}
Also don't forget to unbindService() when stopping the service.
I hava a simple service with data - ArrayList < MyObject > , when I close the app - service is restarted, called onCreate method and data is losing. This is my onStartCommand method:
public int onStartCommand(Intent intent, int flags, int startId) {
.....
return START_STICKY;
}
Service start in Application class
Intent serviceIntent = new Intent(this, ChatNotificationService.class);
startService(serviceIntent);
I not called stopService method.
I need after closing the application, the service continued to work and the data saved in it.
How I can do it?
In activity:
#Override
protected void onCreate() {
super.onCreate();
bindService(serviceIntent, sConn, 0);
}
#Override
public void onDestroy(){
super.onDestroy();
chatNotificationService.closeConnections();
unbindService(sConn);
}