Android get information from service - android

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.

Related

unable to stop service using AlarmManger in android

public class myserveclass extends Service {
#Override
public IBinder onBind(Intent arg0) {
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() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
.
public class MainActivity extends ActionBarActivity {
CheckinternetConnection internet;
TextView textview;
int tempint = 100;
private static final long REPEAT_TIME = 1000 * 5;
private PendingIntent pendingIntent;
Button button1;
Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview = (TextView) findViewById(R.id.textview);
internet = new CheckinternetConnection();
schedueService();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(internet, filter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
unregisterReceiver(internet);
}
class CheckinternetConnection extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (Utils.isNetworkAvailable(MainActivity.this)) {
textview.setVisibility(View.GONE);
startService(new Intent(getBaseContext(), myserveclass.class));
} else {
textview.setVisibility(View.VISIBLE);
textview.setText("It Seems Internet Connection is off");
stopService(new Intent(getBaseContext(), myserveclass.class));
}
}
}
public void schedueService() {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
1000 * 10, pintent);
}
}
this is my code for start service and stop service am able to start service when app is connected with internet and stop when internet is off but after 10 second again service becomes start please check my issue where am doing wrong i have used alarm manger please check please suggest me where am doing wrong .
You need to CANCEL the alarm to stop the service
Intent intent = new Intent(MainActivity.this, myserveclass.class);
PendingIntent pintent = PendingIntent.getService(MainActivity.this, 0,
intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pintent);
Hope it helps ツ

Service not running at predefined time interval

I have defined REPEAT_TIME = 15 * 1000; but the message is displayed in 3 seconds or so.
My MainActivity:
public class MainActivity extends ListActivity {
private LocalWorldService s;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, LocalWorldService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onPause() {
super.onPause();
unbindService(mConnection);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
LocalWorldService.MyBinder b = (LocalWorldService.MyBinder) binder;
s = b.getService();
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT)
.show();
}
public void onServiceDisconnected(ComponentName className) {
s = null;
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT)
.show();
}
};
My Service:
public class LocalWorldService extends Service {
private final IBinder mBinder = new MyBinder();
private ArrayList<String> list = new ArrayList<String>();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
system.out.println("Message");
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
System.out.println("On destroy used");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public class MyBinder extends Binder{
LocalWorldService getService(){
return LocalWorldService.this;
}
}
public List<String> getWordList(){
return list;
}
Following are two class for BroadCastReceiver:
public class MyScheduleReceiver extends BroadcastReceiver{
private static final long REPEAT_TIME = 15 * 1000;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 15);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
}
And:
public class MyStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent service = new Intent(context, LocalWorldService.class);
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
Map<String, ?> x = pref.getAll();
boolean momoMagnetIsOn = (Boolean) x.get("key_momo_magnet");
if (momoMagnetIsOn){
context.startService(service);
}
else{
context.stopService(service);
}
}
Umm, did you notice that you actually tell it to be inexact? You should use setExact()
OK I got it myself. Because I am following this
I don't even know why to restart the system. But restarting the system changed the time interval.I previously had restarted phone with REPEAT_TIME = 3 * 1000 and thus message being displayed every 3 seconds. Any explanation would be welcomed. I am new to this topic. Thank you..

Adding a service and removing it under next condition

I need to start a service and end it under some condition. I previously used IntentService which I found to be incorrect for the purpose(if I am right). I have started using service with BroadcastReciever. But still can't get the desired result. I may elaborate or even paste my code if needed. But for now, I just need something like a flow chart or pseudocode.
The condition would be checked from Preference settings. If checked, I would like to run the service in background else stop the service. Please, can any one out here help me.
EDITED:
My MainActivity:
public class MainActivity extends ListActivity {
private LocalWorldService s;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
Intent intent = new Intent(this, LocalWorldService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onPause() {
super.onPause();
unbindService(mConnection);
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
LocalWorldService.MyBinder b = (LocalWorldService.MyBinder) binder;
s = b.getService();
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT)
.show();
}
public void onServiceDisconnected(ComponentName className) {
s = null;
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT)
.show();
}
};
My Service:
public class LocalWorldService extends Service {
private final IBinder mBinder = new MyBinder();
private ArrayList<String> list = new ArrayList<String>();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Magnet is on", Toast.LENGTH_LONG).show();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
public class MyBinder extends Binder{
LocalWorldService getService(){
return LocalWorldService.this;
}
}
public List<String> getWordList(){
return list;
}
Following are two class for BroadCastReceiver:
public class MyScheduleReceiver extends BroadcastReceiver{
private static final long REPEAT_TIME = 15 * 1000;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, MyStartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast( context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 15);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
}
And:
public class MyStartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent service = new Intent(context, LocalWorldService.class);
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(context);
Map<String, ?> x = pref.getAll();
boolean momoMagnetIsOn = (Boolean) x.get("key_momo_magnet");
if (momoMagnetIsOn){
context.startService(service);
}
else{
context.stopService(service);
}
}
CORRECTION:
I need to override onDestroy().
override onDestroy method in Service
When ever you want to start a service all you need is
startService(new Intent(this, MainService.class));
And to Stop a service anytime just call
stopService(new Intent(this, MainService.class));
Remember service needs to be declared in AndroidManifest.xml. As you said that your service is working. I'm sure you have done that. Still AndroidManifest.xml
<service android:enabled="true" android:name=".MainService" />

Android AlarmManager problems

I'm making and application in android using multiple alarms, and i want to do differents things for each alarm, my problem is that i don't know how to recover the id of the alarm or differentiate each alarm in alarm class.
This is my code:
//Activate the alarm
public void ActivateAlarm(int num) {
int seconds =Preferences.getTime(num);
myIntent[num] = new Intent(Settings.this,
Alarm.class);
pendingIntent[num] = PendingIntent.getService(Settings.this, num,
myIntent[num], 0);
alarmManager[num] = (AlarmManager) getSystemService(ALARM_SERVICE);
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager[num].setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
seconds * 1000, pendingIntent[num]);
Toast.makeText(Settings.this, "Alarm"(num+1)+"activated",Toast.LENGTH_LONG)
.show();
}
class Alarm
public class Alarm extends Service implements Runnable {
public int alarmID;
private static Thread thread;;
#Override
public void run() {
// TODO Auto-generated method stub
handler.sendEmptyMessage(1);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
// Toast.makeText(Alarm.this, Alarm.thread.getName(), Toast.LENGTH_LONG).show();
//ReadFile.readFile(Integer.parseInt(thread.getName()));
displayNotification();
}
};
private void displayNotification() {
//different notification for each alarm
}
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
//super.onStart(intent, startId);
thread = new Thread(this);
thread.start();
}
public void setIDAlarm(int pos){
this.alarmID=pos;
}
}
Thank you.
SInce it worked for you i'll post as answer for others:
You can use
intent.setAction("MyAction1")
and then filter your alarms with
intent.getAction().equals("MyAction1") { do something ...}

How to auto Trigger Alarm Manager on its own instead of onClick

Below is my code which is working very fine. I am calling service after 10 seconds on click of button using Alarm Manager. I want to automate this process say every 10 minutes it should trigger on its own and call service irrespective of device in SCREEN_OFF or SCREEN_ON. Currently i also suspect call is from "Activity" due to which if I close the application it would not trigger.
/*MainActivity.java*/
package com.example.alarmservice;
public class MainActivity extends Activity implements OnClickListener{
final static private long ONE_SECOND = 1000;
final static private long TEN_SECONDS = ONE_SECOND * 10;
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setup();
findViewById(R.id.the_button).setOnClickListener(this);
}
private void setup() {
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Rise and Shine!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.example.alarmservice"));
//pi = PendingIntent.getBroadcast( this, 0, new Intent("com.authorwjf.wakeywakey"),0);
//am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
Intent intent = new Intent(MainActivity.this, ServiceClass.class);
pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + TEN_SECONDS, pi);
}
#Override
protected void onDestroy() {
am.cancel(pi);
unregisterReceiver(br);
super.onDestroy();
}
}
Service Class
/*ServiceClass.java*/
package com.example.alarmservice;
public class ServiceClass extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d("Testing", "Service got created");
Toast.makeText(this, "ServiceClass.onCreate()", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Toast.makeText(this, "ServiceClass.onStart()", Toast.LENGTH_LONG).show();
Log.d("Testing", "Service got started");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}

Categories

Resources