auto start android application when the power is connected [duplicate] - android

This question already has answers here:
How to detect power connected state?
(6 answers)
Closed 2 years ago.
I am developing a dash cam android application. What I am wondering is that is there any way to auto launch the application when the power is connected to the android device. I am thinking to make the app fully automated like when the car engine starts and the power connects to the device with the usb cable, the application automatically launch and start to operate. I read some posts about auto start when the device boots. but, is there any way to auto start when the power connects to the device? thank you.

first you have to make service app.
and using BroadcastReceiver for get state of power.
private final BroadcastReceiver mConnectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) {
Log.e("mConnectionReceiver", "AC Connected by onReceive");
// turn on your app via using Intent
} else if (Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction())) {
Log.e("mConnectionReceiver", "AC Disconnected by onReceive");
}
}
};
for make service app
public class test extends AppCompatActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main ); // run Background Service
Intent serviceintent = new Intent( test.this, MyService.class );
startService( serviceintent );
}
}
and serviceThread
public class ServiceThread extends Thread {
Handler handler;
boolean isRun = true;
public ServiceThread(Handler handler) {
this.handler = handler;
}
public void stopForever() {
synchronized (this) {
this.isRun = false;
}
}
public void run() {
while (isRun) {
handler.sendEmptyMessage( 0 );
try {
Thread.sleep( 1000 );
} catch (Exception e) {
}
}
}
}
and make Service
public class MyService extends Service {
ServiceThread thread;
private final BroadcastReceiver mConnectionReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_POWER_CONNECTED.equals(intent.getAction())) {
Log.e("mConnectionReceiver", "AC Connected by onReceive");
// turn on your app via using Intent
} else if (Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction())) {
Log.e("mConnectionReceiver", "AC Disconnected by onReceive");
}
}
};
#Override public IBinder onBind(Intent intent) {
return null;
}
#Override public int onStartCommand(Intent intent, int flags, int startId) {
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.stopForever(); return START_STICKY;
}
public void onDestroy() {
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.start();
}
public void start() {
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.start();
}
public void stop() {
myServiceHandler handler = new myServiceHandler();
thread = new ServiceThread( handler );
thread.stopForever();
}
public class myServiceHandler extends Handler {
#Override public void handleMessage(android.os.Message msg) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
registerReceiver(mConnectionReceiver, filter);
}
}
this is just example. so check this and fix what you want.

Related

background service not working after app is killed in android

I am trying to load an URL (API) after every 15 seconds in a service. Everything is working fine but when the app is killed URL is not called. I dont need any UI in my app. I just want it to work in background when the app is killed. I have been finding a solution for two days but nothing worked. Please help!
Here is my service code :
public class MyService extends Service {
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000;
String data ;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
handler.postDelayed( runnable = new Runnable() {
public void run() {
data = (String) intent.getExtras().get("data");
Toast.makeText(MyService.this, ""+data, Toast.LENGTH_SHORT).show();
loadURL(data);
handler.postDelayed(runnable, delay);
}
}, delay);
return START_STICKY ;
}
#Override
public void onDestroy() {
handler.postDelayed( runnable = new Runnable() {
public void run() {
Toast.makeText(MyService.this, ""+data, Toast.LENGTH_SHORT).show();
loadURL(data);
handler.postDelayed(runnable, delay);
}
}, delay);
}
public void loadURL(String data){
try{
RequestFuture<JSONObject> requestFuture=RequestFuture.newFuture();
final String mURL = "http://192.168.1.12/att.php?emp_id=" + data + "&status=&submit=Insert";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST,
mURL,new JSONObject(),requestFuture,requestFuture);
MySingleton.getInstance(this).addToRequestQueue(request);
Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
try {
JSONObject object= requestFuture.get(10, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e){
Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
Here is my MainActivity.java where I am getting an intent as a userID :
public class MainActivity extends AppCompatActivity {
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
data = getIntent().getStringExtra("ID");
Intent intent = new Intent(MainActivity.this, MyService.class);
intent.putExtra("data", data);
startService(intent);
}
}
You will have to turn that background service into a foreground service, because of the limitations called Background Execution Limits that started from android Oreo.
Please check out this link for more better understanding:
https://developer.android.com/about/versions/oreo/background

A Handler with a 15 second delay only works accurately when the device is on charge

I'm creating an application where I want a Handler to send an http request every 15 second. The problem is, that while my device (huawei watch 2) is on chare, the Handler works as supposed to, but when I take the watch off the charger, the 15 second is changes between 15 and 40 seconds. Is there a problem with my implementation? I'm not passing any Runnable to the Handler, since there is only a little work to do. I have a SensorHelper class, which just gets the heart rate value. In the request I'm sending a custom message object as JSON.
MainActivity:
public class MainActivity extends WearableActivity {
private static ConnectionService mService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.BODY_SENSORS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BODY_SENSORS},
1);
}
Intent intent = new Intent(this, ConnectionService.class);
this.startService(intent);
this.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
setContentView(R.layout.activity_main);
// Enables Always-on
setAmbientEnabled();
}
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
ConnectionService.LocalBinder binder = (ConnectionService.LocalBinder) service;
mService = binder.getServiceInstance();
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
}
};
public static void sendMessage(String message) {
mService.sendMessage(message);
}
}
ConnectionService in order to avoid my application to go into DOZE mode:
public class ConnectionService extends Service {
private final IBinder mBinder = new LocalBinder();
private static SensorHelper sensorHelper;
private static OkHttpClient client = new OkHttpClient();
public static final MediaType JSON
= MediaType.parse("application/json; charset=utf-8");
public class LocalBinder extends Binder {
public ConnectionService getServiceInstance() {
return ConnectionService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
#Override
public void onCreate() {
if (sensorHelper == null) {
sensorHelper = new SensorHelper(this);
}
super.onCreate();
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("ASD")
.setContentText("ASD")
.setContentIntent(pendingIntent).build();
startForeground(1337, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
public void sendMessage(String message) {
Message msg = new Message("HR", message);
RequestBody requestBody = RequestBody.create(JSON, msg.toJson());
Request request = new Request.Builder()
.url("http://104.248.32.100/")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
}
});
}
}
SensorHelper in order to get the heart rate value, and post it:
public class SensorHelper implements SensorEventListener {
private String sensorValue = "normal";
private static Handler handler = new Handler();
private int delay = 15000;
public SensorHelper(Context context) {
SensorManager sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);
Sensor heartRateSensor = sensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
sensorManager.registerListener(this, heartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
handler.postDelayed(new Runnable(){
public void run() {
sendMessage();
handler.postDelayed(this, delay);
}
}, delay);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
sensorValue = String.valueOf(event.values[0]);
}
}
#Override
public void onAccuracyChanged (Sensor sensor,int i){
}
private String getSensorValue() {
return sensorValue;
}
private void sendMessage() {
MainActivity.sendMessage(getSensorValue());
}
}
Is there any mistakes I'm making, while the Handler is not working correctly? Is passing a Runnable necessary to create a new Thread? As far as is read, the Handler is creating a new Thread
I had the same exact problem, with a lot of applications that run on the background while the device is not charging. The problem is Android's battery optimization.
The solution is pretty simple, you have to disable your app's battery optimization by going to Settings > Battery > Battery optimization (The path varies by manufacturer).
Some manufacturers also add extra measures to optimize battery by making timed tasks proc less often, so check out for extra settings that might affect this.
Hope this helps!

why restart the service

i have a problem in my service, the service is runnig from MainActivity (i am doing test) and extends of service.
i want to use the service from foreground and background (when the app is closed) and i already have my first problem:
my service(have a counter that is displayed by LOG) is restarting when i close the app.
also i want to be able to use the service with the open app and close app, in other words to use both the Service Started and Link Service
public class MyService extends Service {
private Thread backgroundThread;
private boolean isRunning;
public MyService() {
Log.e("MyService","constructor");
}
#Override
public void onCreate() {
super.onCreate();
isRunning = false;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
Log.e("onStartCommand","Servicio Llamado");
if (!this.isRunning) {
Log.e("onStartCommand","hilo iniciandose");
this.backgroundThread = new Thread(myTask);
runTask();
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("onDestroy","servicio destuido");
}
private void runTask(){
this.isRunning = true;
this.backgroundThread.start();
}
private Runnable myTask = new Runnable() {
public void run() {
Log.e("myTask","hilo iniciado");
int i = 0;
do{
pauseService();
Log.e("myTask","hilo contador: "+i);
//Toast.makeText(getApplicationContext(),"CONTADOR = "+j, Toast.LENGTH_SHORT).show(); //no working :(
i++;
}while (i<10);
/*
//linea de detencion del servicio
//stopSelf();
isRunning=false;
backgroundThread.interrupt();
//backgroundThread = new Thread(myTask);
*/
Log.e("myTask","hilo cerrado");
}
};
private void pauseService(){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
In main Activity
Intent intent = new Intent(MainActivity.this,MyService.class);
intent.putExtra("iteraciones",10);
startService(intent);
why because the service restarts when I close the application and how can I avoid it?

Service stop working when turn on /of wifi many time

Service stop working when turn on /of Wi-Fi many time, when I start service do counter 1,2,3 etc or any thing then turn on /of Wi-Fi many time the service stops working ,I have BroadcastReceiver class doing start service, no exceptions , error appear , only I sent one message to phone to start service..
This is the code inside BroadcastReceiver:
if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")) {
Intent recorderIntent = new Intent(context, Start2.class);
context.startService(recorderIntent);
}
This My Start2 Service:
public class Start2 extends Service {
private static final String TAG = Start2.class.getSimpleName();
int mStartMode;
#Override
public void onDestroy() {
Log.d(TAG, "Stop Service onDestroy");
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... params) {
final Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
int i = 0 ;
#Override
public void run() {
try{
//do your code here
Log.d(TAG, "Start Service Repeat Time.. " + i);
i++;
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable to call it at regular interval
handler.postDelayed( this, 5000 );
}
}
};
handler.postDelayed(runnable, 1000 );
return null;
}
};
task.execute();
return mStartMode;
}
}

StopService from another Activity not working?

I know there are a lot of questions on this already but it doesn't seem to work, so basically I have a custom Service, the service works fine when the timer inside it expires, and calls the stopservice method. however when I try and stop the service from another activity it doesn't work?
code for custom service:
public class ConnectionService extends Service {
Intent service_intent;
Timer t;
int expiry_time = 0;
int timer_tick_starter = 0;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
t = new Timer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
service_intent = intent;
Log.d("onConnectionService", "onStartCommand");
expiry_time = Integer.parseInt(intent.getStringExtra("expiry"));
//convert the minutes to milliseconds
timer_tick_starter = (expiry_time * 60000);
Log.d("onConnectionService", "Expiry Time (in milliseconds) " + timer_tick_starter);
} catch (Exception e) {
Log.d("onConnectionService", e.getMessage().toString());
}
//timer will only start to run on the expiry_time which will then close the connection
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d("onConnectionService", "inside expiry time");
//close the connection
stopService(service_intent);
}
}, 30000);
return START_NOT_STICKY;
}
#Override
public boolean stopService(Intent name) {
Log.d("onConnectionService", "StopService called");
String message = name.getStringExtra("msg");
//broadcast sender
Intent intent = new Intent();
intent.putExtra("msg", message);
intent.setAction("fi.android.inetkeyapplication.CUSTOM_INTENT");
intent.putExtra("is_selected", UserConnectionState.getInstance().is_selected);
sendBroadcast(intent);
Log.d("onConnectionService", "Service has been killed");
return super.stopService(name);
}
#Override
public void onDestroy() {
Log.d("onConnectionService", "Destroy called");
}
}
here I start the service from onCreate:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Log.d("onConfigurationActivity", "Service starting ");
// Intent i = new Intent(ConfigurationActivity.this, ConnectionService.class);
Intent i = new Intent(context, ConnectionService.class);
i.putExtra("expiry", "1");
startService(i);
}
});
thread.start();
however later in my app when I try to kill it from the activity in which I start it, it doesn't work:
Button exit_button = (Button) findViewById(R.id.btnExit);
connect_button.setTypeface(roboto_light);
exit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do closing call
response_close = "";
//need to close service
//also kill the service
Log.d("onConfigurationActivity", "killing service");
Intent intent = new Intent(context, ConnectionService.class);
intent.putExtra("msg", "You have been disconnected");
stopService(intent);
}
});
I have tried my class - ConfigurationActivity.this (as context) and I have tried (this) at the moment I am using a custom context that I simply get inside onCreate. however nothing seems to work what am I missing?
thanx
ok so apparently stopping the service doesn't stop the timer. so I just called cancel() on timer

Categories

Resources