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 ツ
Related
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 have created a simple service just periodically Toasting. But when service is stopped once it creates again by own and again continuously starting.
Following is my MainActivity code.
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(this, TestService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int i;
i=15;
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
i* 1000, pintent);
Button startBtn = (Button) findViewById(R.id.startBtn);
startBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startService(new Intent(getBaseContext(), TestService.class));
}
});
Button stopBtn = (Button) findViewById(R.id.stopBtn);
stopBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopService(new Intent(getBaseContext(), TestService.class));
}
});
}
Following is my service class
Testservice
public class TestService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Created", 1).show();
Log.i("TestService", "SERVICE START");
super.onCreate();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Destroy", 1).show();
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
return super.onStartCommand(intent, flags, startId);
}
}
That's all my code when button clicked to stop service it once stopped but again created but it's own
what's I am doing wrong??
Thanks in advance..
Try to use START_STICKY :
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Running ", 1).show();
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
If its still not working, try returning START_REDELIVER_INTENT instead of START_STICKY.
Check this link for more information :
START_STICKY and START_NOT_STICKY
Try
MainActivity.this
instead of getBaseContext()
I have fixed my problem as My AlarmManager was periodically sending intent request to my service so I stopped service and also stopped my AlarmManger by alarm.cancel(pintent);
Thanks to all of you..
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" />
I have a brodcastReciver , an activity and a service , in the activity i send an intent to service to set an alarm , and alarm is sending broadcast to brodcastReciver to show toast.
but i cant cancel alarm from activiy. here is my code :
public class MainActivity extends Activity {
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button) findViewById(R.id.button1);
stop = (Button) findViewById(R.id.button2);
start.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
stop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stop();
}
});
}
void stop() {
Intent i = new Intent(this, Reci.class);
i.putExtra("c", "cancel");
startService(i);
Toast.makeText(this, "stop clicked!", Toast.LENGTH_SHORT).show();
}
void start() {
Intent i = new Intent(this, Serv.class);
i.putExtra("d", "do");
startService(i);
Toast.makeText(this, "start clicked!", Toast.LENGTH_SHORT).show();
}
}
service :
public class Serv extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.getStringExtra("d").equalsIgnoreCase("do")) {
Toast.makeText(this, "onStart", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Reci.class)
.setAction("ir.test.code.Reci.noti");
PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
G.AM.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 5000, 5000, pi);
} else if (intent.getStringExtra("c").equalsIgnoreCase("cancel")) {
Toast.makeText(this, "onCancel", Toast.LENGTH_SHORT).show();
Intent i = new Intent(this, Reci.class)
.setAction("ir.test.code.Reci.noti");
PendingIntent pi = PendingIntent.getBroadcast(this, 1234, i, 0);
G.AM.cancel(pi);
}
return super.onStartCommand(intent, flags, startId);
}
}
broadcastReciver
public class Reci extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase("ir.test.code.Reci.noti")) {
Toast.makeText(context, "ir.test.code.Reci.noti",
Toast.LENGTH_SHORT).show();
}
}
}
and Application class :
public class G extends Application{
public static AlarmManager AM;
#Override
public void onCreate() {
super.onCreate();
AM = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
}
what should i do?
you are not starting service because of diffent class name you provided ...change void stop() method
Intent i = new Intent(this, Reci.class);
to
Intent i = new Intent(this, Serv.class);
in stop() method of mainactivity
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;
}
}