Passing data to service in oncreate() - android

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 :)

Related

How to send data back from Activity to AccessibilityService?

I have a class that extends AccessibilityService and when there is a certain event starts an activity.
The problem is that when the activity ends, it should send data back to 'AccessibilityService'. Does anyone have an idea on how to do that?
Example:
public class MyAccessibilityService extends AccessibilityService {
#Override
public void onAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType()==AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED){
Intent intent=new Intent(getApplicationContext(),DialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// String resul=set result When Activity is closed
}
}
Thanks in advance!
AccesibilityService is an inherited class from Service class. So we can refer that question to this:
How to have Android Service communicate with Activity
The easiest way for your question:
1) Call startService() in your Activity's onDestroy() method:
#Override
protected void onDestroy() {
super.onDestroy();
Intent intent = new Intent(getApplicationContext(), MyAccessibilityService.class);
intent.putExtra("data","yourData");
startService(intent);
}
2) Override your MyAccessibilityService's onStartCommand() method:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
String data="";
if(intent.getExtras().containsKey("data"))
data = intent.getStringExtra("data");
return START_STICKY;
}
1)Call startActivity(intent) from your accessibility service on any event.
String msg = "your message";
Intent intent = new Intent(serviceContext, activityClassName.class);
intent.putExtra("message",msg);
startActivity(intent);
2)Now in your activities onCreate(Bundle bundle) method you can get intent.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String msg = intent.getStringExtra("message");
Log.e(LOG_TAG,"Message From Service - "+msg); //Message From Service - your message
}
Using Intent you can pass data from Service to Activity.

How to stop service from logout button?

Hello I am building an app where I am using service for locations. That service have to work all the time, so I set that when service goes to onDestroy, then intent is sent to BroadcastReceiver who starts service again, and on that way, my service always works. But I want to stop service when user click on button logout. How to prevent that,when service goes to onDestroy, don't send intent to broadcast(but only when user clicks on logout)?
This is my logout from MainActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_log_out) {
if (isNetworkConnected()) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "Logout!");
Log.d("MAIN_ACTIVITY " , "Internet access ");
}
else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
}
}
These are methods onStartCommand, onCreate and onDestroy in location service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand" , "LocationService");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
isEnded = false;
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
Bugsnag.init(this, BUGSNAG_API_KEY);
buildGoogleApiClient();
Log.d("onCreateService", "onCreateService");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "onDestroy!");
timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.user_location), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("onDestroyService", timeWhenServiceDestroyed);
editor.apply();
stopLocationUpdates();
Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
And this is my BroadCastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LocationServiceRestartBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, LocationService.class));
}
How to prevent that when user clicks on logout button, my service don't create again? Thanks in advance.
You could use static boolean variable shouldRestart that is false only when logout button is clicked, otherwise true.
Add to your activity :
public static boolean shouldRestart=true;
Add to your "logout button click event" this line:
shouldRestart=false;
And add this lines in onDestroy method of service :
if (MainActivity.shouldRestart){
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
MainActivity.shouldRestart=true;

Get intent in Service return NullPointerException

I create Service and call it from MainActivity.class with put string extra to intent but when I call getStringExtra in onStartCommand, it returns NullPointerException
Here is my code:
MainService.class :
public class MainService extends Service {
private WindowManager wm;
private WindowManager.LayoutParams params;
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
if (mView != null) {
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.removeView(mView);
}
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
final String quote = intent.getStringExtra("quote");
Log.d("datastring",quote);
return super.onStartCommand(intent, flags, startId);
}
}
In MainActivity.class I called :
Intent i=new Intent(MainActivity.this, MainService.class);
i.putExtra("quote", "dataquote");
stopService(i);
How I can get string from MainActivity in MainService?
If you want to provide more data to your Service you need to use something like:
Intent intent = new Intent(MainActivity.this, MainService.class);
intent.putExtra("quote", "dataquote");
startService(intent);
This will start the service and you should be able to get the data intent in the onStartCommand(). If the Service is already running, onStartCommand() will still be called with the new intent. This is because Service components are inherently singleton, so only one instance of a particular service run at a time.
In your case, you are providing the data via stopService(intent). Not only its not possible to get this intent, your Service will also stop after this statement so, you cannot really do much with the data even if you could have read it.
If you still need to stop your Service and pass data at the same time, you should check this post.

Automatic service restart after killing in application manager

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?

Service and Chronometer Synchronization

I need to be able to start chronometer, then close activity, after that through notifications, back to that activity, and see the right time in chronometer.
What I've Done
A part of my Activity:
public void doClick(View target)
{
switch(target.getId())
{
case R.id.buttonStart:
{
Mchronometer.setBase(SystemClock.elapsedRealtime());
Mchronometer.start();
Intent intent = new Intent(RecentActivity.this, ChronometerService.class);
intent.putExtra("task_name",task_name);
intent.putExtra("task_id",task_id);
intent.putExtra("ellapsedTime",Mchronometer.getBase());
Log.d("base",""+Mchronometer.getBase());
startService(intent);
break;
}
case R.id.buttonStop:
{
stopService(new Intent(RecentActivity.this, ChronometerService.class));
Mchronometer.stop();
Mchronometer.setBase(SystemClock.elapsedRealtime());
break;
}
case R.id.button3:
{
break;
}
}
}
A part of my Service:
public class ChronometerService extends Service {
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");
private NotificationManager notificationMgr;
private int task_id;
private long ellapsedTime;
#Override
public void onCreate() {
super.onCreate();
notificationMgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
String task_name =intent.getExtras().getString("task_name");
task_id =intent.getExtras().getInt("task_id");
ellapsedTime = intent.getExtras().getLong("ellapsedTime");
Log.d("servicebase",""+ellapsedTime);
displayNotificationMessage(task_name);
new Thread(myThreads, new ServiceWorker(),"ChronometerService").start();
return START_STICKY;
}
private class ServiceWorker implements Runnable {
public void run() {
}
}
#Override
public void onDestroy()
{
myThreads.interrupt();
notificationMgr.cancelAll();
super.onDestroy();
}
public IBinder onBind(Intent intent) {
return null;
}
public void displayNotificationMessage(String message){
Notification notification = new Notification(R.drawable.emo_im_winking,message,System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR;
Intent intent = new Intent(this, RecentActivity.class);
intent.putExtra("task_id", task_id);
intent.putExtra("ellapsedTime",ellapsedTime);
Log.d("servicebase1",""+Long.toString(ellapsedTime));
PendingIntent contentintent = PendingIntent.getActivity(this,0,intent,0);
notification.setLatestEventInfo(this,"ChronometerService",message,contentintent);
notificationMgr.notify(0, notification);
}
}
I tried to send a message from activity to a service, which contains elapsed information.
If I started it first on my device (after system load) it's works right, but when I launch it again. The activity receives wrong message. It receives the time of the first service launched on the device.
As you can see I also send one more variable, and activity reads it correctly.
I've found a solution to my question.
It's simple.
It's needed to use flag(PendingIntent.FLAG_UPDATE_CURRENT)
PendingIntent contentintent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
And it's work fine.

Categories

Resources