5
I tried to use the Service
as they said but it’s not working yet. I don’t know if I got it right, the method onStartCommand()
will run all the time? Because I debug and the application only enters this method once, when the onCreate()
is called and I need what’s there run all the time. Follow the code:
Java service.
public class Servico extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("oi", "onStartCommand");
boolean ok = true;
while(ok == true){
try {
Thread.sleep(30000);
} catch (InterruptedException e) {
e.printStackTrace();
}
gerarNotificacao();
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Executaservico.java
public class ExecutaServico extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, Servico.class);
context.startService(pushIntent);
}
}
}
Androidmanifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".ExecutaServico">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".Servico"/>
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Mainactivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(HomeActivity.this,Servico.class));
final Button continuar = (Button) findViewById(R.id.btn_continuar);
continuar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//varias coisas
}
});
}
}
I have no idea what I did wrong... Every 30 seconds the notification should appear
I did what you said, but it’s not working. It’s giving this error: "Activitythread: Performing stop of Activity that is not resumed"
– Éowyn
It worked, I just changed the call from Service to onPause(), because otherwise the application would not open... Thank you! I’m sorry I asked you another question, I needed this, and I didn’t know if you’d be back in time
– Éowyn
Ok, I’m glad it worked out, there is also the possibility to restart the service if the user forces the shutdown
– Vitor Henrique
how do I restart the service in the case of a force Closer? @Vitorhenrique
– Steve Rogers