Reputation: 9926
I trying to write simple basic application that will start my service when the phone is start.
i add all the permission i need.
I install the application on my android ( android 6.01 ). And when i reboot my phone - i can't see that the service is up or did any action.
The code:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAG" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.NoActionBar">
<service android:name=".MyService" android:enabled="true" android:exported="true"/>
<receiver android:name=".MainBroadcastReceiver" android:enabled="true" android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
public class MainBroadcastReceiver extends BroadcastReceiver {
public MainBroadcastReceiver(){
}
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyService.class));
}
}
public class MyService extends Service {
private File _file;
private Timer _timer;
private FileOutputStream _fileOutputStream;
public MyService() throws IOException {
_file = new File("/sdcard/" + "myServiceText.txt");
_file.createNewFile();
_fileOutputStream = openFileOutput(_file.getName(), Context.MODE_APPEND);
_fileOutputStream.write("Ctor called".getBytes());
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
_timer = new Timer("timer");
_timer.schedule(new TimerTask()
{
@Override
public void run()
{
try {
_fileOutputStream.write("onCreate Called".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 5000);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
_fileOutputStream.write("onStartCommand".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
return START_STICKY;
}
Upvotes: 1
Views: 180
Reputation: 6392
Your code is fine, the reason your service is not running it's because your app is in Stopped State.
1. Stopped state is a security procedure that allows your app to "wake itself up" only after user first manually launches it from the home screen.(Unless you are a system)
By doing so android prevents malicious apps to be installed and run in your phone background without you knowing.
2. How to debug a background process?
When working with background processes there are two great tools you need in your belt -
First is the adb broadcast command -
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
Second is attach remote debugger
(Android Studio):
Run | Attach debugger to android process (last option in the menu) | choose your app's process.
Upvotes: 1