Hai i have a application using background service.its running clearly.If my mobile is switch off,my service is ound service off.when my application is started then only my background service is strated .i want to restart the service again when mobile switch off?
is it possible?
Anybody explain with code
update
public class loginForm extends Activity
{
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView (R.layout.login);
receiver = new ConnectionReceiver();
registerReceiver(receiver,new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
}
private class ConnectionReceiver extends BroadcastReceiver{
private Timer mTimer;
private TimerTask mTimerTask;
#Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra (ConnectivityManager.EXTRA_NETWORK_INFO);
if(null != info)
{
String state = getNetworkStateString(info.getState());
if(state.equals("Connected")){
mTimer = new Timer();
mTimerTask = new TimerTask() {
#Override
public void run() {
loginForm.this.runOnUiThread(new Runnable() {
#Override
public void run() {
//Toast.makeText(getBaseContext(), "Disenabled provider " + provider,
///Toast.LENGTH_SHORT).show();
try{
insertAllGpsInformation();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(), "Your Net Connected or Not Login to Net"+"", Toast.LENGTH_LONG).show();
Log.e("Upload Picture Error:",e.getMessage());
}
}
});
}
};
mTimer.scheduleAtFixedRate(mTimerTask,180000,180000);
}
}
}
}
}
Register for the ACTION_BOOT_COMPLETED (see here for details). Start your service on boot.
You should register a BroadcastReceiver and look for the BOOT_COMPLETED Intent.
Here is link with some details: http://androidgps.blogspot.com/2008/09/starting-android-service-at-boot-time.html
Did I understand your question correctly?
create Broadcast Receiver that with the Intent of BOOT COMPLETED Action.
please refer following links for more help :
http://blog.gregfiumara.com/?p=82
http://marakana.com/forums/android/examples/60.html
You can use
public class BootReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
Log.i("BootReceiver :: Start Booting..");
Intent i = new Intent(context, StartService.class); // Start your service class
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
and use the broadcastreciever in androidmanifest.xml as
<receiver android:name=".receiver.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Related
I have surfed the web and I haven't found a solution to my problem.
In my android app I have to catch and send a notification to the server everytime the user turn off the GPS. At this time I have writed this code
In the Android manifiest:
<receiver android:name="proguide.prosegur.scr.BL.receivers.GPSStatusBroadcastReceiver">
<intent-filter>
<action android:name="android.location.PROVIDERS_CHANGED" />
</intent-filter>
</receiver>
In the GPSStatusBroadcastReceiver class:
public class GPSStatusBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
if (arg1.getAction().matches("android.location.PROVIDERS_CHANGED")) {
// here I have to send the notification
}
}
The problem is that everytime the user put down the GPS, I get this function called twice with identical Context and Intent arguments (I can only send 1 notification at a time).
Important note: it has to work under API level 8.
So, why this happen twice? What can I do (doing it right, not messing up the code) to send only 1 notification at a time? Thanks, sorry for my English.
Try this:
public class GpsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
final String action = intent.getAction();
if (action.equals(LocationManager.PROVIDERS_CHANGED_ACTION)) {
// GPS is switched off.
if (!context.getSystemService(Context.LOCATION_SERVICE).isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// Do something.
}
}
}
}
}
Also, instead of hardcoding "android.location.PROVIDERS_CHANGED", you should use the variable LocationManager.PROVIDERS_CHANGED_ACTION provided by Android.
Instead of setting your GPS receiver in your AndroidManifest.xml file, register your GPS receiver via a Service as follow:
public class GpsService extends Service {
private BroadcastReceiver mGpsReceiver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
registerReceiver();
return Service.START_NOT_STICKY;
}
private void registerReceiver() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
this.mGpsReceiver = new GpsReceiver();
this.registerReceiver(this.mGpsReceiver, mIntentFilter);
}
}
}
You can avoid this problem using sharedpreference and with an thread
but it is not a proper way to overcome this problem
my method as follows
#Override
public void onReceive(Context context, Intent intent) {
boolean flage=MainActivity.getpreference();
if(!flage){
MainActivity.putPreferens(true);
Log.e("gpssss","gpssss");
Thread thread = new Thread() {
#Override
public void run() {
try {
sleep(2000);
MainActivity.putPreferens(false);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}}
}
to the main class am create a sharedpreference and store boolean value false
the broad cast will work once.
I want my app to be aware anytime the user changes the locale. So in my Application class, I create a receiver to listen to the system intent ACTION_LOCALE_CHANGED:
public final class MyApp extends Application {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override public void onReceive(Context context, Intent intent) {
String locale = Locale.getDefault().getCountry();
Toast.makeText(context, "LOCALE CHANGED to " + locale, Toast.LENGTH_LONG).show();
}
};
#Override public void onCreate() {
IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, filter);
}
}
When I press home and go to the settings app to change my locale, the Toast is not shown. Setting the breakpoint inside onReceive shows it never gets hit.
Why do you want the BroadcastReceiver in Application class. My suggestion is to have a separate class for BroadcastRecevier.
public class LocaleChangedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction (). compareTo (Intent.ACTION_LOCALE_CHANGED) == 0)
{
Log.v("LocaleChangedRecevier", "received ACTION_LOCALE_CHANGED");
}
}
}
and register your Brodcast receiver in Manifest file.
<receiver
android:name=".LocaleChangedReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.LOCALE_CHANGED" />
</intent-filter>
</receiver>
Intent.ACTION_LOCALE_CHANGED is not a local broadcast, so it won't work when you register it with LocalBroadcastManager. LocalBroadcastManager is used for the broadcast used inside your app.
public class MyApp extends Application {
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String locale = Locale.getDefault().getCountry();
Toast.makeText(context, "LOCALE CHANGED to " + locale,
Toast.LENGTH_LONG).show();
}
};
#Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter(Intent.ACTION_LOCALE_CHANGED);
registerReceiver(myReceiver, filter);
}
}
Hi I developed one small android application in which I am using one activity one intent service and one broadcast receiver.
So my code looks like :
public class Main_Activity extends Activity {
private ResultReceiver resultReciver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_);
Log.i("***************************88", "inside activity on create");
IntentFilter filter = new IntentFilter("com.nilkash.broadcast.receiver");
resultReciver = new ResultReceiver();
registerReceiver(resultReciver, filter);
//LocalBroadcastManager.getInstance(this).registerReceiver(resultReciver, filter);
Intent intent = new Intent(this, ExampleService.class);
startService(intent);
}
public class ResultReceiver extends BroadcastReceiver{
public ResultReceiver()
{
}
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
Log.i("**********************", "inside broadcast receiver: ");
}
}
}
And intent service
public class ExampleService extends IntentService{
public ExampleService(String value)
{
super(value);
}
public ExampleService()
{
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i("********************************", "inside intetn reciver: ");
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.nilkash.broadcast.receiver");
//broadcastIntent.putExtra("value", "nilkash");
sendBroadcast(intent);
//LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
}
In manifest file I define service.
So my problem is that I start service from activity and its working fine. From service on intent receive I sent one broadcast receiver but it not listening inside my broadcast receiver.
Am i doing some thing wrong? Need Help. Thank you.
There is an error: sendBroadcast(intent);. Should be another intent object (broadcastIntent).
I am trying to set up a service that checks when a new update of an activity is installed in a device. I have already done so within an application activity, declaring the Broadcastreceiver in the manifest and it works perfectly.
However, when I try to run that receiver within a Service and dynamically declare it, my onReceive never gets called. This is my Service code:
public class UpdateService extends Service {
private static String mPackage = "com.my.package";
private static String mActivityName = "myActivity";
private BroadcastReceiver mUpdateReceiver;
#Override
public void onCreate() {
super.onCreate();
mUpdateReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("mTag","In the BroadcastReceiver onReceive()");
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_PACKAGE_REPLACED)) {
// Log that a new update is has been found
Log.d("mTag","New version of the app has been installed.");
Log.d("mTag", "Intent data: " + intent.getDataString());
Log.d("mTag","My package: " + mPackage);
}
}
};
Log.d("mTag","In the service onCreate() method.");
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
registerReceiver(mUpdateReceiver,filter);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("mTag","UpdateService started");
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mUpdateReceiver);
Log.d("mTag","Service destroyed");
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
The Log in the Service onCreate() gets called, which tells me that the service is up and running. However, after installing and replacing some apps through the adb, none of the logs in the BroadcastReceiver the method onReceive() get called.
This is my MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, UpdateService.class));
}
}
Do you guys have any ideas why the onReceive() does not get called?
Thank you.
I based my code in these two references:
BroadcastReceiver within a Service
How to know Android app upgraded?
you should add the data schema to your IntentFilter.
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
filter.addDataScheme("package");
registerReceiver(mUpdateReceiver,filter);
If you are trying to listen to the ACTION_PACKAGE_REPLACED broadcast, this cannot be done from service. Most probably, the replacement will happen when your application is closed. That`s why you will not listen to it.
You should register from the Manifest to let your OS know that you want to listen to this Intent then Create a class that extentsBroadcastReceiver` as the following:
Manifest:
<receiver android:name="PackageChangeReceiver" >
<intent-filter>
<action android:name="android.intent.action.PACKAGE_REPLACED" />
<data android:scheme="package" />
</intent-filter>
</receiver>
Receiver:
public class PackageChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_PACKAGE_REPLACED) && intent.getDataString().contains(context.getPackageName())) {
Log.d("Tag", "Package has been replaced");
Log.d("Tag", "Intent data: " + intent.getDataString());
Log.d("Tag", "Action: " + intent.getAction());
}
}
}
I have checked if intent.getDataString().contains(context.getPackageName()) to make sure that the replacement of the package is mine not any other application.
i want to make my app to be run in background and listens for
contact,sms deletion events.
for that i created a service in my app but i dnt how to start without activity
my code is like this
public class DeleteService extends Service {
ContentResolver cr;
MyContentObserver observer=new MyContentObserver();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return mBinder;
}
#Override
public void onCreate() {
cpath=ContactsContract.Contacts.CONTENT_URI;
// some action
}
#Override
public void onDestroy() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Launch a background thread to do processing.
super.onStartCommand(intent, flags, startId);
cpath=ContactsContract.Contacts.CONTENT_URI;
cr=getContentResolver();
cur=cr.query(cpath, null, null, null, null);
this.getApplicationContext().getContentResolver().registerContentObserver(cpath, true, observer);
return Service.START_STICKY;
}
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
nfm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int NOTIFICATION_ID = 1;
Intent intent1 = new Intent();
PendingIntent pi = PendingIntent.getActivity(DeleteService.this, 1, intent1, 0);
nf=new Notification(R.drawable.ic_launcher,"Contact Database changed",System.currentTimeMillis());
nf.setLatestEventInfo(getApplicationContext(), "Delete Event", "contact name", pi);
nf.flags = nf.flags |
Notification.FLAG_ONGOING_EVENT;
}
#Override
public boolean deliverSelfNotifications()
{
super.deliverSelfNotifications();
return true;
}
}
public class LocalBinder extends Binder {
DeleteService getService() {
return DeleteService.this;
}
}
}
register ACTION_SCREEN_ON or ACTION_USER_PRESENT broadcast recivers for your Appliction in Service and start Service when screen is on or user is present. you can register ACTION_SCREEN_OFF broadcast reciver for stoping Service when phone screen is off to avoid battery drain by your app.as:
In manifest.xml:
<receiver android:name="com.my.AppStart">
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
BroadcastReceiver :
public class AppStart extends BroadcastReceiver {
public static final String present = "android.intent.action.USER_PRESENT";
public static final String screenon = "android.intent.action.SCREEN_ON";
public static final String screenoff = "android.intent.action.SCREEN_OFF";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(present) || intent.getAction().equals(screenon) )
{
Intent i=new Intent(context,DeleteService.class);
context.startService(i);
}
if (intent.getAction().equals(screenoff))
{
//STOP YOUR SERVICE HERE
}
}
}
A service can only by started by an Activity, or a BroadCast receiver, or a service which is already started. It can't be stand-alone(It can't start by itself). So, you would need one of the two components to start it. you can make an activity which starts the service which is the preferred way. But if you don't want to provide a user interface, implement a broadcast receiver which fires up when the phone is switched on and the boot up is completed, Inside that br, start your service. This will also help you run the service as soon as a phone starts.
for example in your manifest:
<receiver android:name="com.my.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
and in the br:
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context,DeleteService.class);
context.startService(i);
}
}
In your activity .. put this code in oncreate
Intent svc=new Intent(youractivity.this,DeleteService.class);
startService(svc);