I tried to use Service
as they said but it is not working yet. I do not know if I understand correctly, will the onStartCommand()
method run all the time? Because I've debugged and the application only goes into this method once, when onCreate()
is called and I need what's there to run all the time. Here is the code:
Servico.java
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();
}
}
RunService.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