My 'JobIntentService' isn't working good in background - android

When I start JobIntentService, it works fine, but after entering phone-sleep it suspends after some time. When I unlock my phone, it starts working again.
I want to have a long task working in background, it have to not suspend or stop.
Here's my JobInteneService:
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, ExampleJob.class, 1, work);
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate() called");
super.onCreate();
}
#Override
protected void onHandleWork(#NonNull Intent intent)
{
cancelRingtone = Uri.parse("android.resource://com.example.myapplication/" + R.raw.cancel);
cancelAlarm = RingtoneManager.getRingtone(this, cancelRingtone);
while(running)
{
cancelAlarm.play();
try
{
Thread.sleep(60000);
}
catch (Exception e)
{
Log.i(TAG, "onHandleWork: "+e);
running=false;
}
}
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy() called");
super.onDestroy();
}
Here's MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.WAKE_LOCK
}, 1);
}
public void click(View view)
{
Intent mIntent = new Intent(this, ExampleJob.class);
ExampleJob.enqueueWork(this, mIntent);
}
Here's AndroidManifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<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=".ExampleJob"
android:permission="android.permission.BIND_JOB_SERVICE"/>
</application>
With this code my phone will play beep sound every minute. In phone-sleep mode I count up to 6 beeps in half an hour.
Did I implement JobIntentService properly?
If JobIntentService isn't made for that work, what else should I use?

Related

What is the best method to run applets in the background - Android

I am developing an application that sends location data to a database. As I need this task to be executed in the background, I used the Service type to send the data, but when the application goes to the background, the service stops executing after a few seconds. I researched the subject and found the JobScheduler class, but this class performs services in the background with a very long time interval (15min) and I needed the service to be performed at least every 2 min and to be canceled only by the user. Is there a way to do this? I thank anyone who can help.
https://developer.android.com/reference/android/app/job/JobScheduler
My service:
public class GPSservice extends Service {
private String TAG = "INICIAR SERVIÇO GPS";
private Context context;
private HandlerThread handlerThread;
private Handler handler;
private final int TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS = 60; //tempo de sessenta segundos
#Override
public void onCreate() {
handlerThread = new HandlerThread("HandlerThread");
}
#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(TAG, "onStartCommand");
//Previne que seja executado em subsequentes chamadas a onStartCommand
if(!handlerThread.isAlive()) {
Log.d("NotifyService","Notificações iniciadas");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
Runnable runnable = new Runnable() {
#Override
public void run() {
AtualizarLocalizacaoBanco();
handler.postDelayed(this, 1000 * TEMPO_ENTRE_NOTIFICAÇOES_SEGUNDOS);
}
};
handler.post(runnable);
}
return Service.START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("NotifyService","Notificações Finalizadas");
Intent broadcastIntent = new Intent(this, BroadCastReceiver.class);
sendBroadcast(broadcastIntent);
//handlerThread.quit();
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
}
public void AtualizarLocalizacaoBanco(){
context = this;
ModeloAtualizacao model = new ModeloAtualizacao();
SharedPreferences preferences = this.context.getSharedPreferences("user_preferences", MODE_PRIVATE);
model.setId(preferences.getString("usuario_id", ""));
model.setLati(preferences.getString("user_latitude", ""));
model.setLongi(preferences.getString("user_longitude", ""));
model.setEmpresa(preferences.getString("usuario_empresa", ""));
model.setEscola(preferences.getString("usuario_escola", ""));
Call<String> call = new RetrofitConfig().postAtualizacao().atualizarLocalizacao(model);
call.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
Log.d("Sucesso: ", "ok");
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.d("Erro atualizar", t.getMessage());
}
});
}
Manifest:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<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"
android:usesCleartextTraffic="true">
<activity android:name=".ActivityGPS"></activity>
<activity android:name=".Activity_Lista_Aluno" />
<activity
android:name=".ProfessorActivity"
android:label="#string/title_activity_professor" />
<service
android:name=".GPSservice"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false"/>
<activity
android:name=".MainActivity"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".Activity_Login">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

BroadcastReceiver not working as expected on Android

I know this was asked already many times but I can't get this to work. I looked all around Android docs and other sources. I got this activity that has a broadcast receiver variable inside and starts a service as such in the constructor:
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(getApplicationContext(), "Received", Toast.LENGTH_SHORT).show();
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_compass);
Intent mIntent = new Intent(this, GPSTracker.class);
startService(mIntent);
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mReceiver, new IntentFilter());
}
#Override
protected void onStop() {
unregisterReceiver(mReceiver);
super.onStop();
}
I put the service down in the manifest and I am sure it works properly. Any help will be appreciated.
Broadcast receiver is supposed to receive 2 floats from the service periodically.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="jemboy.compass" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".GPSTracker"></service>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
<activity android:name=".CompassActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OtherActivity"></activity>
</application>
In the activity
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(UPDATE_PLAYER)) {
updateMediaPlayerToggle();
} else if (intent.getAction().equals(BUFFERING)) {
showMediaPlayerBuffering();
}
}
};
private void registerBroadcastReceiver() {
LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(this);
IntentFilter updateIntentFilter = new IntentFilter();
updateIntentFilter.addAction(UPDATE_PLAYER);
updateIntentFilter.addAction(BUFFERING);
broadcastManager.registerReceiver(broadcastReceiver, updateIntentFilter);
}
in the service.
private void sendUpdatePlayerIntent() {
Log.d(TAG, "updatePlayerIntent");
Intent updatePlayerIntent = new Intent(MainActivity.UPDATE_PLAYER);
LocalBroadcastManager.getInstance(this).sendBroadcast(updatePlayerIntent);
}
Example from a media player service.

how to bind HCE hostapduservice to main activity on android

hy..i have a task to make my kitkat-nexus to act as a tag. I have ACS 122U as reader. i have read the program example in this site http://blog.opendatalab.de/hack/2013/11/07/android-host-card-emulation-with-acr122/. then i tryed the code on my own eclipse.
main activity :
public class MainActivity extends Activity implements OnMessageReceived, ReaderCallback {
private NfcAdapter nfcAdapter;
private ListView listView;
private IsoDepAdapter isoDepAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView)findViewById(R.id.listView);
isoDepAdapter = new IsoDepAdapter(getLayoutInflater());
listView.setAdapter(isoDepAdapter);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
Log.i("end of onCreate-----","onCreate HCE");
}
#Override
public void onResume() {
super.onResume();
//nfcAdapter.enableReaderMode(this, this, NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK,
// null);
//nfcAdapter.disableReaderMode(this); //tambahan poipo
Log.i("onResume---", "onResume");
}
#Override
public void onPause() {
super.onPause();
nfcAdapter.disableReaderMode(this);
Log.i("onPause---", "onPause");
}
#Override
public void onTagDiscovered(Tag tag) {
IsoDep isoDep = IsoDep.get(tag);
IsoDepTransceiver transceiver = new IsoDepTransceiver(isoDep, this);
Thread thread = new Thread(transceiver);
Log.i("dibawah thread", "ontagdiscovered");
thread.start();
}
#Override
public void onMessage(final byte[] message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
isoDepAdapter.addMessage(new String(message));
Log.i("didlmrun---", "onMessage");
}
});
Log.i("diluarrun---", "onMessage");
}
#Override
public void onError(Exception exception) {
onMessage(exception.getMessage().getBytes());
}
}
hostapduservice :
...
...
...
#Override
public byte[] processCommandApdu(byte[] apdu, Bundle extras) {
if (selectAidApdu(apdu)) {
Log.i("HCEDEMO====", "Application selected====");
return getWelcomeMessage();
}
else {
Log.i("HCEDEMO======", "Received: =====" + new String(apdu));
return getNextMessage();
}
}
...
...
...
then in the manifest file :
<uses-sdk
android:minSdkVersion="19"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="FEATURE_NFC_HOST_CARD_EMULATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service
android:name=".MyHostApduService"
android:exported="true"
android:permission="android.permission.BIND_NFC_SERVICE" >
<intent-filter>
<action android:name="android.nfc.cardemulation.action.HOST_APDU_SERVICE" />
</intent-filter>
<meta-data
android:name="android.nfc.cardemulation.host_apdu_service"
android:resource="#xml/apduservice" />
</service>
<activity
android:name="de.grundid.hcedemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
ok,,when i ran the above source code,, i saw my acs122u blinking continously when i tapped my nexus near to it. but i didn't see the log.i(....) from hostapdu service. In the eclipse log cat, there were just some log.i from main activity. what should i do to bind that hostapdu service to main activity, so my nexus can act as a tag...???
thanks in advance... :-)

How to start service at boot on android 4.0.3

I wan't to start service at boot on android 4.0.3 but when i boot my device it not happen in my device and service not start.Help me please thank you
here is my manifest
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MainActivity"
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="com.android.testsharedpreference.MyService"></service>
<receiver android:name="com.android.testsharedpreference.BootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
</application>
my boardcast receiver
public class BootReceiver 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));
}
}
}
and my service
public class MyService extends Service
{
#Override
public IBinder onBind(Intent intent)
{
return null;
}
#Override
public void onCreate()
{
super.onCreate();
Toast.makeText(MyService.this, "onCreate Service ", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy()
{
super.onDestroy();
Toast.makeText(MyService.this, "onDestroy Service ", Toast.LENGTH_LONG).show();
}
}
you should add add android.permission.RECEIVE_BOOT_COMPLETED as it was not required before ICS so the app was working fine but starting from ICS is you don't have this permission your app wont receive the boot completed intent
Don't forget to override the method "onStartCommand" in your MyService:
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
String action = intent == null ? null : intent.getAction();
Log.d("onStartCommand", "action = " + action);
/* ... */
return START_NOT_STICKY; // for example ...
}

Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found

I've been studying from the book "Pro Android 2." I'm working through a Service example that consists of two classes: BackgroundService.java and MainActivity.java. The MainActivity claims (erroneously?) it starts the Service as indicated by output to logcat from the Log.d call below:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d(TAG, "starting service");
Button bindBtn = (Button)findViewById(R.id.bindBtn);
bindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent backgroundService = new Intent(MainActivity.this, com.marie.mainactivity.BackgroundService.class);
startService(backgroundService);
}
});
Button unbindBtn = (Button)findViewById(R.id.unbindBtn);
unbindBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
stopService(new Intent(MainActivity.this, BackgroundService.class));
}
});
}
}
What puzzles me is the UI provides two buttons: Bind and UnBind as shown above. But according to the documentation if onBind() as shown below returns null that indicates you don't want to allow binding. But as shown above the onClick() method of (the Bind button) bindBtn.setOnClickListener(new OnClickListener() calls startService(backgroundService) which gives this error:"Unable to start service Intent { cmp=com.marie.mainactivity/.BackgroundService }: not found"
public class BackgroundService extends Service {
private NotificationManager notificationMgr;
#Override
public void onCreate() {
super.onCreate();
notificationMgr = NotificationManager)getSystemService(NOTIFICATION_SERVICE);
displayNotificationMessage("starting Background Service");
Thread thr = new Thread(null, new ServiceWorker(), "BackgroundService");
thr.start();
}
class ServiceWorker implements Runnable
{
public void run() {
// do background processing here...
//stop the service when done...
//BackgroundService.this.stopSelf();
}
}
#Override
public void onDestroy()
{
displayNotificationMessage("stopping Background Service");
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void displayNotificationMessage(String message)
{
Notification notification = new Notification(R.drawable.note, message, System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
notification.setLatestEventInfo(this, "Background Service", message, contentIntent);
notificationMgr.notify(R.id.app_notification_id, notification);
}
}
I don't understand the point of this example. If onBind() returns null what's the point of having a Bind button (bindBtn)? I thought the point was to show how to start a BackgroundService. But it doesn't seem to work unless I'm missing something.
I should add I have added to my AndroidManifest.xml:
<service android:name=".BackgroundService"></service>
as follows:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<service android:name=".BackgroundService"></service>
</activity>
</application>
Remove the service from inside the activity. It is at the same level as the activity within the application. Eg:
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".MainActivity"
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=".BackgroundService"></service>
</application>

Categories

Resources