I made a service that every 5 second he put on the screen a TAG (I think this is the name of this). When I make a boot it needs to put the TAG on the screen but he says that the app crashed. Why?
The code:
Android Manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name="com.YuvalFatal.MyBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:enabled="true" android:name="com.YuvalFatal.MyService"/>
BroadcastReceiver:
package com.YuvalFatal.ineedhelp;
import java.util.Timer;
import java.util.TimerTask;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastreceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context arg0, Intent arg1) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
Intent startServiceIntent = new Intent(arg0, MyService.class);
arg0.startService(startServiceIntent);
}
}, 0, 5000);
}
}
IntentService:
package com.YuvalFatal.ineedhelp;
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class MyService extends IntentService {
private static final String TAG = "com.YuvalFatal.ineedhelp";
public MyService(String name) {
super(name);
// TODO Auto-generated constructor stub
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.i(TAG, "Intent Service started");
}
}
I think (yep, I am magician and have great intuition :) your Service constructor should be default:
public class MyService extends IntentService {
...
public MyService() { // Default constructor! Without params!
super("MyService"); // Or another string
}
...
}
Other code looks normal
Related
My target was Restarting the Service when app is in background or even killed from home page by sweeping. App & Service is working nice while app is in foreground and background but while I killed the app by force(sweeping out from home page), the Service stopped working. That's okay but I implemented a Broadcast Receiver to restart the Service but it seems like its (Broadcast Receiver) not even called itself or the Service while app was killed forcefully / sweeping from home page.
My device is : Xiaomi Redmi Note 4
I included my codes here :
MainActivity.java
package com.turzo.servicetest;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private String TAG = "ServiceTest";
Intent mServiceIntent;
private SensorService mSensorService;
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
registerRec();
setContentView(R.layout.activity_main);
mSensorService = new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i (TAG, true+"");
return true;
}
}
Log.i (TAG, false+"");
return false;
}
#Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i(TAG, "onDestroy!");
super.onDestroy();
}
public void registerRec(){
SensorRestarterBroadcastReceiver myreceiver = new SensorRestarterBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver((BroadcastReceiver) myreceiver, intentFilter);
}
}
SensorService.java
package com.turzo.servicetest;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class SensorService extends Service {
public int counter=0;
private String TAG = "ServiceTest";
public SensorService(Context applicationContext) {
super();
Log.i(TAG , "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG , "ondestroy!");
Intent broadcastIntent = new Intent("com.turzo.servicetest.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
stoptimertask();
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i(TAG , "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
SensorRestarterBroadcastReceiver.java
package com.turzo.servicetest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, SensorService.class));
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.turzo.servicetest">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.turzo.servicetest.SensorService"
android:enabled="true" >
</service>
<receiver
android:name="com.turzo.servicetest.SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="com.turzo.servicetest.ActivityRecognition.RestartSensor"/>
</intent-filter>
</receiver>
</application>
</manifest>
You should restart Service in onTaskRemoved().
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartService = new Intent(getApplicationContext(),
this.getClass());
restartService.setPackage(getPackageName());
PendingIntent restartServicePI = PendingIntent.getService(
getApplicationContext(), 1, restartService,
PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePI);
}
NOTE:- Starting from android O . You can not call startService.
The startService() method now throws an IllegalStateException if an app targeting Android 8.0 tries to use that method in a situation when it isn't permitted to create background services.
This does not apply to foreground services, which are noticeable to the user. It can run in background with a notification on top. By default, these restrictions only apply to apps that target Android 8.0 (API level 26) or higher. However, users can enable most of these restrictions for any app from the Settings screen, even if the app targets an API level lower than 26. So in case if user enables the restrictions for below API 26 your Service will not work.
Read Background Execution Limits.
So Try to avoid using Service if you can . Make use of WorkManager if it fits the requirements.
I'm trying to create a service in my android project.but the service seems not starting at all.
package serviceexample.javatechig.com.serviceexample;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class HelloService extends Service {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
}
}
manifest.xml:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
and main activity:
package serviceexample.javatechig.com.serviceexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
findViewById(R.id.start_service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
startService(intent);
}
});
findViewById(R.id.stop_Service).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MyActivity.this, HelloService.class);
stopService(intent);
}
});
}
}
no errors but when I press the buttons the service won't get started.onCreate and onStartCommand events not raising.
The package your Service is in:
package serviceexample.javatechig.com.serviceexample;
The class name you use in the Manifest:
<service android:name="serviceexample.javatechig.HelloService" android:exported="false"/>
Those should be same in order for Service to work.
You are using the wrong package name in the AndroidManifest.xml
Replace:
serviceexample.javatechig.HelloService
with
serviceexample.javatechig.com.serviceexample.HelloService
Basically the path name should be same for service activities and all
I finaly found the problem. the service tag in manifest.xml wasn't a child of application tag.If I showed the whole manifest.xml you would find the problem in a minute :)
I have a BroadcastReceiver named StartService which start when the phone boots which in turn starts a service but when I am going to the service from this BroadcastReceiver I get exception:
android.content.ReceiverCallNotAllowedException: IntentReceiver components are not allowed to bind to services
my code is below:
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;
public class StartService extends BroadcastReceiver {
private RemoteServiceConnection conn = null;
private IMyRemoteService remoteService;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Intent startServiceIntent = new Intent(context, RemoteServiceClient.class);
context.startService(startServiceIntent);
conn = new RemoteServiceConnection();
Intent i = new Intent();
i.setClassName("com.collabera.labs.sai", "com.collabera.labs.sai.RemoteService");
context.bindService(i, conn, Context.BIND_AUTO_CREATE);
}
class RemoteServiceConnection implements ServiceConnection {
public void onServiceConnected(ComponentName className,
IBinder boundService ) {
remoteService = IMyRemoteService.Stub.asInterface((IBinder)boundService);
Log.d( getClass().getSimpleName(), "onServiceConnected()" );
}
public void onServiceDisconnected(ComponentName className) {
remoteService = null;
Log.d( getClass().getSimpleName(), "onServiceDisconnected" );
}
};
}
some of the step follow.
Step 1:
public class StartService extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, myServices.class);
context.startService(startServiceIntent);
}
}
Step 2:
// make all service related task
Step 3:
<service
android:name=".myServices"
android:enabled="true" />
<receiver android:name="com.yourpackage.StartService " >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
I am always used BroadcastReceiver and services this way.
May be helpful for you.If helpful then accept answer.
I just created a service as shown below :
package com.example.timepass;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class alarm extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Entered in service", Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "onStartCommand...", Toast.LENGTH_LONG).show();
return 1;
// Log.i("YourService", "Yes this works.");
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
Toast.makeText(this, "Changed", Toast.LENGTH_SHORT).show();
return null;
}
}
Now when I startservice from mainactivity by the following command:
Intent myIntent = new Intent("com.example.timepass.ALARM");
MainActivity.this.startService(myIntent);
By doing this there is no error, but no TOAST of Service class are dipslayed
My manifest is :
<service class=".alarm" android:name=".alarm" android:enabled="true">
<intent-filter>
<action android:value="com.example.timepass.ALARM"
android:name=".alarm" />
</intent-filter>
</service>
Please guide me!!!
Probably you don't have the service in your manifest, or it does not have an that matches your action. Examining LogCat should turn up some warnings that may help.
More likely, you should start the service via:
startService(new Intent(this, alarm.class));
I have an Activity class, in which I have a static flag, let's say
public static volatile flag = false;
Then in the class, I start a thread, which checks the flag and do different things.
I also have a broadcastreceiver, which sets the flag to true or false.
I though volatile will force the flag to the most recent value. But I can see my broadcastreceiver sets the static flag to true, but my thread is still getting it as false.
Am I missing something basic here? Any help would be appreciated!
Simplified Code (Updated) - So the flag is supposed to change to true after one minute. But it never did. But message from broadcast receiver shows it has been change to true
TestappActivity.java:
package com.test;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
public class TestappActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent0 = new Intent(this, TestService.class);
this.startService(intent0);
Intent intent = new Intent(this, TestReceiver.class);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent sender = PendingIntent.getBroadcast(this,
1, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar slot = Calendar.getInstance();
int min = slot.get(Calendar.MINUTE);
slot.set(Calendar.MINUTE, min+1);
am.set(AlarmManager.RTC_WAKEUP, slot.getTimeInMillis(), sender);
}
}
TestService.java:
package com.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class TestService extends Service {
private static final String TAG = "TestService";
public static volatile boolean flag = false;
private MyTopThread mTopThread;
public TestService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
protect();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
/**
* Run protection
*
*/
private void protect() {
mTopThread = new MyTopThread();
mTopThread.start();
}
private class MyTopThread extends Thread {
#Override
public void run() {
while (true) {
try {
Thread.sleep(150);
Log.d(TAG, "Flag is " + TestService.flag);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
TestReceiver.java:
package com.test;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class TestReceiver extends BroadcastReceiver {
final static private String TAG = "TestReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive is triggered ...");
TestService.flag = true;
Log.d(TAG, "flag is changed to " + TestService.flag);
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TestappActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".TestService" />
<receiver
android:name=".TestReceiver"
android:process=":remote" >
</receiver>
</application>
</manifest>
I think the problem is that you are running the receiver in its own process. From the docs for the android:process attribute of <receiver>:
If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the broadcast receiver runs in that process.
I think the receiver is modifying a process-local version of TestService.flag, not the one being used by TestService. Try removing the android:process attribute from the <receiver> tag in your manifest.
From this link
http://www.javamex.com/tutorials/synchronization_volatile.shtml
Essentially, volatile is used to indicate that a variable's value will
be modified by different threads.
I really hope your service thread is not this one (I don't see any other one):
private class MyTopThread extends Thread {
#Override
public void run() {
while (true) {
try {
Thread.sleep(150);
Log.d(TAG, "Flag is " + TestService.flag);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Because you have while(true) here, not while(!flag) as it should be.