This is my Service Class
public class ContactSync extends IntentService {
private static final String TAG = "com.ric.connectme.Services.ContactSync";
public ContactSync() {
super(TAG);
}
public ContactSync(String name) {
super(name);
}
#Override
protected void onHandleIntent(#Nullable Intent intent) {
if (intent != null) {
Toast t = Toast.makeText(getBaseContext(), message, Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER, 0, 0);
t.show();
GoForUplodeContect(intent);
}
}
private void GoForUplodeContect(Intent intent){
RsXtraUserNumbersBackupUploder.Uplode(getBaseContext(),intent);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
This Is What I Inserted In AndroidManifest
<service android:name=".Services.ContactSync">
</service>
And This is how I am calling this service
Intent intent = new Intent(context,ContactSync.class);
intent.putExtra(RsXtraIntetBundelKeys.USER_ID,userId);
context.startService(intent);
I Tried everything and system starting the service very well but the onHandleIntent is not executing.
Can any one help me on this ?
Related
I have an activity. It will be receive two variable from an service. In the service, I will send two variable to the activity by
// Send first variable
sendBroadcast(new Intent("first_one"));
// Send second variable
sendBroadcast(new Intent("second_one"));
Now, In the activity, I used bellow code to receive the data. There are
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(firstRec, new IntentFilter("first_one"));
registerReceiver(secondRec, new IntentFilter("second_one"));
}
#Override
protected void onPause() {
super.onPause();
if (firstRec != null) {
unregisterReceiver(firstRec);
firstRec = null;
}
if (secondRec != null) {
unregisterReceiver(secondRec);
secondRec = null;
}
}
private BroadcastReceiver firstRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK first");
}
};
private BroadcastReceiver secondRec = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG","OK second");
}
};
However, I cannot print the log "OK second" when I called sendBroadcast(new Intent("second_one")); in the service. What is happen? How can I fix it? Thank you
UPDATE: my activity is an accept calling activity get from #notz
How can incoming calls be answered programmatically in Android 5.0 (Lollipop)?. Then I create an service as following
public class myService extends Service{
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent answerCalintent = new Intent(getApplicationContext(), AcceptCallActivity.class);
answerCalintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
answerCalintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(answerCalintent);
//Send the second command after 10 second and make the calling in background
new CountDownTimer(10000, 100) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
sendBroadcast(new Intent("second_one"));
}
}.start();
return START_STICKY;
}
}
You should unregister your reŃeiver in a method opposite to that in which you register it:
If you registered receiver in onCreate() - then you should unregister it in onDestroy().
But as i know, for most cases, the best practice is to register receiver in onResume() and unregister it in onPause().
I made an service that triggers every 10 sec. How to connect service to activity when it triggers. Example i refresh my local DB, when appears an update Activity send an Toast.
AlarmService.class
#SuppressLint("SimpleDateFormat")
public class AlarmService extends Service {
Handler mHandler;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
}
public void f() {
Toast t = Toast.makeText(this, "Service is still running",
Toast.LENGTH_SHORT);
t.show();
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
Toast t = Toast.makeText(this, "Service started", Toast.LENGTH_SHORT);
t.show();
// TODO Auto-generated method stub
super.onStart(intent, startId);
mHandler = new Handler();
Runnable r = new Runnable() {
#Override
public void run() {
f();
mHandler.postDelayed(this,10000);
}
};
mHandler.postDelayed(r, 10000);
}
}
MainActivity.class
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent serviceIntent = new Intent(this,AlarmService.class);
startService(serviceIntent);
}
}
Use broadcast receiver like this
public static class MyExtBroadcastReceiver extends BroadcastReceiver {
public MyExtBroadcastReceiver() {
super();
}
#Override
public void onReceive(Context context, Intent intent) {
//Call your activity here
}
Make a method for setting the alarm
public void setAlarm(){
f(); // call your method f() here
AlarmManager am=(AlarmManager)getSystemService(ALARM_SERVICE);
Intent alarmintent1 = new Intent(this, MyExtBroadcastReceiver.class);
PendingIntent sender1=PendingIntent.getBroadcast(this, 100, alarmintent1, PendingIntent.FLAG_UPDATE_CURRENT | Intent.FILL_IN_DATA);
try {
am.cancel(sender1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar cal=Calendar.getInstance();
cal.add(Calendar.Seconds,10);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*10*60, sender1);
Call this method from OnCreate()
#Override
public void onCreate() {
setAlarm();
}
}
You can use LocalBroadcastManager, Messenger, ResultReceiver to send data from service to Activity.
Here is an example that uses ResultReceiver to send updated data from Service to Activity.
I'm using following code to stop my service
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
And this is my service that works indefinitely
public class UsageRecorderService extends IntentService {
public UsageRecorderService() {
super("UsageRecorder");
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
Why does not stop my service?
This code would work
public class UsageRecorderService extends IntentService {
private boolean mStop = false;
public UsageRecorderService() {
super("UsageRecorder");
}
public final Object sLock = new Object();
public void onDestroy() {
synchronized (sLock) {
mStop = true;
}
}
#Override
protected void onHandleIntent(Intent intent) {
while (true) {
synchronized (sLock) {
if (mStop) break;
}
UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
}
You can use stopService
Intent intent = new Intent(MainActivity.this, UsageRecorderService.class);
stopService(intent);
Also I recommend to read Services guide to understand what is going there.
Activity:
sendBroadcast(new Intent(ACTION_STOP));
IntentService
public class UsageRecorderService extends IntentService {
private static final String TAG = "UsageRecorderService";
String ACTION_STOP = "com.xxx.UsageRecorderService.ACTION_STOP";
boolean stop;
public UsageRecorderService() {
super("UsageRecorder");
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
if (ACTION_STOP.equals(intent.getAction())) {
stop = true;
}
}
};
#Override public void onCreate() {
super.onCreate();
IntentFilter intentFilter = new IntentFilter(ACTION_STOP);
registerReceiver(receiver, intentFilter);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG,"onHandleIntent");
while (true && !stop) {
Log.i(TAG,"----running----");
//UsageRecorder.recordUsages(this, false);
SystemClock.sleep(10000);
}
}
#Override public void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
An IntentService is designed to stop itself only when all the requests present in the work queue have been handled.Android stops the service after all start requests have been handled.
I have a service and an activity. in service I broadcast messages received from network and in the activity show these messages. this works fine. but all messages will lost when the activity is in the background.
How can I get last messages(if exists) from server, in activity onResume(or onCreate)?
EDIT :
in service:
public class server extends Service implements Runnable
{
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public void onStart(Intent intent, int startID)
{
//initializing socket and begining listen
new Thread(this).start();
}
public void run()
{
String readed;
while (true)
{
if(reader == null) continue;
try
{
if ((readed = reader.readLine()) != null)
{
Intent intent = new Intent(SEND_DATA_INTENT);
intent.putExtra("type", "message");
intent.putExtra("content", readed.substring(1));
sendBroadcast(intent);
Thread.sleep(100);
}
}
catch (Exception ee) { }
}
}
}
and in activity:
public class menhaj extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
#Override
protected void onResume()
{
if (dataUpdateReceiver == null) dataUpdateReceiver = new DataReciver();
IntentFilter intentFilter = new IntentFilter(server.SEND_DATA_INTENT);
registerReceiver(dataUpdateReceiver, intentFilter);
super.onResume();
};
#Override
protected void onPause()
{
if (dataUpdateReceiver != null) unregisterReceiver(dataUpdateReceiver);
super.onPause();
};
private class DataReciver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
if (intent.getAction().equals(server.SEND_DATA_INTENT))
{
Bundle bdl = intent.getExtras();
String type = bdl.getString("type");
if (type.equals("message"))
{
String message = bdl.getString("content");
db.addMessage(message);
showMessage(message);
}
}
}
}
}
If that activity is in the background, the user probably doesn't want to see messages from it. Show notifications from your services instead. Generally, an activity should de-register itself onPause() and register again onResume() when it comes back to the foreground.
I would declare BroadcastReceivers , those can receive messages and bring back to from your avtivity / app
Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys