Will Service concept work even if App crash in Android? - android

I am working on an application for collecting crash reports in application, so that I have created class which extends Application for handling uncaught exception and created service class for communicate with server.
I made a simple divide by zero exception in a button click and it produce exception but my service class does not called. I am sure have registered the service class in manifest file.
my question is Will Service concept work even if application is crashed (force close) in Android?
code:
public class MyApp extends Application {
public void onCreate() {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
#Override
public void uncaughtException(Thread thread, Throwable e) {
handleUncaughtException(thread, e);
}
});
}
public void handleUncaughtException(Thread thread, Throwable e) {
e.printStackTrace();
Intent i = new Intent(MyApp.this, ServiceClass.class);
startService(i);
}
}
Service class:
public class ServiceClass extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("onStartCommand", "onStartCommand called");
// server communication code.
return Service.START_STICKY;
}
}
Manifest xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ex.errorhandle"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="com.ex.errorhandle.MyApp"
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<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.ex.errorhandle.ServiceClass" />
</application>
</manifest>

Related

How to make an application start on factory reset/first startup?

I am looking to have some basic forms run on my android device after it is reset or on the first boot like most smartphones ask you to connect to Wi-Fi, register the device etc. I haven't worked with native android development previously so what are my options and what areas should I look into?
Try this
BootCompleteReceiver.java
public class BootCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, MsgPushService.class);
context.startService(service);
}
}
MyService.java
public class MyService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return Service.START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroy", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MainActivity
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startService(new Intent(getBaseContext(), MyService.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newbootservice"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<service android:name=".MyService"/>
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

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>

Twilio Device defined in sticky Service is not starting activity if app closed

I need to be able to receive incoming Twilio calls regardless of whether the app is currently running or not.
Once the user has started the app and logged into our server, I start the service shown below.
The Service is started sticky, and at no point is stopService or stopSelf etc ever called, so the service should still be running after the App is closed.
When the App is running, IncomingCallActivity starts fine in response to a Twilio call.
If the App is in the background, IncomingCallActivity still starts fine in response to a Twilio call.
If however the App is closed, IncomingCallActivity no longer starts in response to a Twilio call.
Why isn't IncomingCallActivity started if the App has been closed??
public class CallService extends Service implements Twilio.InitListener, DeviceListener, ConnectionListener {
private Device mDevice;
private Connection mConnection;
#Override
public void onCreate() {
super.onCreate();
registerBroadcastReceiver();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Initialize the Twilio SDK if required
if (!Twilio.isInitialized()) {
Twilio.initialize(getApplicationContext(), this);
} else {
getCapabilityToken("CallService", getUser());
}
...
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onDestroy() {
// Unregister broadcast receiver
final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
localBroadcastManager.unregisterReceiver(mBroadcastReceiver);
super.onDestroy();
}
#Override
public void onInitialized() {
getCapabilityToken("CallService", getUser());
}
#Override
public void onError(Exception e) {
}
private void getCapabilityToken(String string, User user) {
// Request the capability token from the server.
...
}
protected void setCapabilityToken() {
// Create device using the capability token
mDevice = Twilio.createDevice(getUser().capabilityToken, this);
// Set pending intent for Twilio device
Intent intent = new Intent(this, IncomingCallActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mDevice.setIncomingIntent(pendingIntent);
// Broadcast that CallService is ready, to any registered receivers
Intent broadcastIntent = new Intent(App.ACTION__TWILIO_SERVICE_READY);
LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
}
public void connect() {
mConnection = mDevice.connect(null /* parameters */, null /* ConnectionListener */);
if (mConnection == null) {
...
} else {
...
}
}
private void answerCall(Device device, Connection connection) {
if (mConnection != null) {
mConnection.disconnect();
}
mConnection = connection;
mConnection.accept();
}
/**
* BroadcastReceiver
*/
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
switch (action) {
case App.ACTION__CAPABILITY_TOKEN_OBTAINED:
setCapabilityToken();
break;
case App.ACTION__CONNECT:
connect();
break;
}
}
};
#Override
public void onStartListening(Device device) {
}
#Override
public void onStopListening(Device device) {
}
#Override
public void onStopListening(Device device, int i, String s) {
}
#Override
public boolean receivePresenceEvents(Device device) {
return false;
}
#Override
public void onPresenceChanged(Device device, PresenceEvent presenceEvent) {
}
#Override
public void onConnecting(Connection connection) {
}
#Override
public void onConnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection) {
}
#Override
public void onDisconnected(Connection connection, int i, String s) {
}
}
Edit:
To clarify how I've declared my services etc, here is my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="au.com.encall.encall"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".IncomingCallActivity"
android:screenOrientation="portrait"/>
<service android:name=".services.CallService"/>
<service android:name=".services.DownloadService"/>
<service
android:name="com.twilio.client.TwilioClientService"
android:exported="false"
android:stopWithTask="false" />
<meta-data
... />
...
</application>
</manifest>
if you are using twilio demo than You need to service in Androidmenifest
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="true"/>
its working for me.
twilio provide their own service. so you need to just declare it on menifest.so does't need to create new service.
jusr remove this service and put it on android menifest.it will automatically start after app close.
Its Work for me no need extra service
<service android:name="com.twilio.client.TwilioClientService" android:exported="false" android:stopWithTask="false"/>
But How can we Handle if token is Expired ? At that time IncomingCallActivity no longer starts

android: Does not runs on the boot up.... and how to write the same to disable bluetooth

was trying to implement an service that disables bluetooth and wifi when ever user tries to enable bluetooth and Wifi as they are few ways of getting infected.
i have disable use of application use of app locker.
this is what i tried with the tutorials available but so far i have failed to run it on the bootup
Service class
public class MyService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
BroadcastReceiver mReceiver = new StatusReceiver();
registerReceiver(mReceiver, filter);
return super.onStartCommand(intent, flags, startId);
}
}
Reciver
public class StatusReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
wifiManager.setWifiEnabled(false);
}
}
}
Activity
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("HI","I am on activity");
startService(new Intent(this,MyService.class));
finish();
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.active"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".TestActivity"
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=".MyService" >
</service>
<receiver android:name=".StatusReceiver" >
</receiver>
</application>
</manifest>

BroadcastReceiver not receiving

I have read the instructions and examples in SO questions, but still unable to implement a simple BroadcastReceiver, it simply does not receive anything, can someone kindly provide some advice on the following code?
tnx
My activity:
public class Receiver1Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(MyService.MY_ACTION);
registerReceiver(new MyReceiver(), filter);
Intent intent = new Intent();
startService(intent);
}
}
My receiver:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.i("MyReceiver", "onreceive");
}
}
My service, which sends the broadcast:
public class MyService extends Service {
public static final String MY_ACTION = "com.receiver1.myaction";
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent intent2 = new Intent(MY_ACTION);
sendBroadcast(intent2);
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.receiver1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="10" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".Receiver1Activity"
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=".MyService"></service>
</application>
</manifest>
Are you sure that your service is even getting started? It looks like your just creating a blank intent and calling startService().
Your broadcastReceiver appears to be correct.
You need to register your receiver in your AndroidManifest.xml. Until you do that, the Android OS won't be able to find your BroadcastReceiver.

Categories

Resources