startService starts MainActivity - android

I am using
startService(new Intent(getApplicationContext(), NotificationService.class));
from Activity or BroadcastReceiver (using Context context). In every situation, service starts, but with that starts MainActivity also. How to fix it?
Service code:
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Manifest:
...
<activity
android:name=".ViewProfileActivity"
android:label="#string/title_activity_view_profile"
android:windowSoftInputMode="adjustResize|stateHidden" >
</activity>
<service
android:name=".NotificationService"
android:process=":NotificationService" >
</service>
...
UPD. Broadcast receiver:
public class BootBroadcast extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, NotificationService.class));
}
}

MainActivity starts from onCreate of Application class.

just replace this code in your MainActivity like this:
startForegroundService(Intent(applicationContext, MyService::class.java));

Related

How to launch an app when the screen unlocks?

I have tried this code but it's not working. Does anybody have any different solution? I have tried many ways like the below one from Stack Overflow but none of them is working.
manifest.xml
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF"/>
<action android:name="android.intent.action.SCREEN_ON"/>
</intent-filter>
</receiver>
screenreceiver
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON))
{
Intent intent = new Intent();
intent.setClass(context, ScreenLockActivity.class);
startActivity(intent);
}
}
}
To listen to screen on/off, your app should run by time and register Broadcast receiver to OS programmatically.
ScreenOnOffService.java
public class ScreenOnOffService extends Service {
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate() {
super.onCreate();
Log.i("ScreenOnOffService", "onCreate: ");
IntentFilter intentFilter = new IntentFilter();
// intentFilter.addAction("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(ScreenOnReceiver.newInstance(), intentFilter);
}
public void onDestroy() {
super.onDestroy();
Log.i("ScreenOnOffService", "onDestroy: ");
unregisterReceiver(ScreenOnReceiver.newInstance());
// startService(new Intent(this,ScreenOnOffService.class));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
}
ScreenOnReceiver.java
public class ScreenOnReceiver extends BroadcastReceiver {
public static final String TAG = "ScreenOn";
public static volatile ScreenOnReceiver screenOn;
public static ScreenOnReceiver newInstance() {
if (screenOn == null) {
screenOn = new ScreenOnReceiver();
}
return screenOn;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.i("hieuN", "intent: " + intent.getAction());
// do work. start activity.
}
}
Start service in activity
Intent service = new Intent(this, ScreenOnOffService.class);
startService(service);

Run service after device was restarted

I want that one of my services runs even if user has restarted device. I've tried this code but didn't succeed. What should I do? Help me please.
Thank you!
MyService2.class:
public class MyService2 extends Service {
private MyReceiver mR = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mR = new MyReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
registerReceiver(mR, intentFilter);
}
}
MyReceiver.class
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
context.startService(new Intent(context, MyService.class));
context.startService(new Intent(context,MyService2.class));
}
}
}
You are Registering your BroadcastReciver in your Service , Which your trying to start using your BroadcastReciver which is not registered.
So try registering your broadcast Reciever in your manifest file like this
<receiver android:name="your broadcast class">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter
First no need to register your receiver in service. Add your broadcast receiver in Manifest.
Like :
<receiver android:name="your broadcast class">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
Remember to add permission also :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
When device is rebooted your receiver will automatically get executed by system as it is declared in manifest. In your receiver just start your service.
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
//add a log or toast to confirm the receive
context.startService(new Intent(context, MyService2.class));
}
}
}
AND
public class MyService2 extends Service {
private MyReceiver mR = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do what ever you wanted to do...
}
}

Service and bootup code not working

I am trying to create a service that will run on bootup, however when trying it in my emulator the log is not showing my message through log tag, so clearly something is wrong.
Here is my code.
service.java
public class service extends Service {
private static final String TAG = "myapp.mycomp";
public service() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Service started");
Runnable r = new Runnable() {
#Override
public void run() {
/** something to do **/
}
};
Thread service = new Thread(r);
service.start();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
Log.i(TAG, "Service stopped");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent myIntent = new Intent(context, service.class);
context.startService(myIntent);
}
}
XML manifest intent
<receiver android:name=".MyReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
XML manifest permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

run app in background without activity alerts user when Contact or sms is deleted

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

How can i activate a service from a broadcastReceiver?

I want to activate a service from my broadcastReceiver, this is my code but it didn't work:
public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
#Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&& pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent( context, Deletecontact.class);
context.startService(service);
}}}
and this is the service
public void onCreate()
{
//deletecontact();
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy()
{
super.onDestroy();
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
public class MyBinder extends Binder {
Deletecontact getService() {
return Deletecontact.this;
}
}
I just want to call the service when the action of the broadcast is set
#Emna when i see you code for start service you have used this code to start service.
context.startService(service);
In this code context this not assign like below
So before you call startService
context=ctx;
Add above code after onReceive.
And Make sure that you have define Deletecontact.class this class as Service Tag in AndroidManifest.xml For Example Below :
<service android:enabled="true" android:name="xxx.yyy.zzz.Deletecontact"
></service>
Hope this will work .
try this,use ctx instead of context for starting service and preparing Intent:
public class PackageChangeReceiver extends BroadcastReceiver {
Context context;
Deletecontact delete= new Deletecontact();
#Override
public void onReceive(Context ctx, Intent intent) {
Uri uri = intent.getData();
String pkg = uri != null ? uri.getSchemeSpecificPart() : null;
if(intent.getAction().equals("android.intent.action.PACKAGE_REMOVED")&& pkg.equals("com.alarm"))
{Log.i("action","the package is removed");
Intent service = new Intent(ctx, Deletecontact.class);
ctx.startService(service);
}}}

Categories

Resources