I want to run my android application always in background like whatsapp,truecaller i have used all things but when device is reboot the application is stop running in background for that i have used broadcast receiver to listen boot. here is my code.
My Service
public class Myservice extends Service {
File file;
private static String fileName = null;
private MediaRecorder recorder = null;
boolean mStartRecording = true;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
Intent intent = new Intent("RestartService");
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public int onStartCommand(final Intent intent, int flags, int startId) {
onTaskRemoved(intent);
file = new File(Environment.getExternalStorageDirectory(), "pranay");
if (!file.exists()) {
boolean mkdir = file.mkdirs();
if (!mkdir) {
Toast.makeText(this, "Fialed", Toast.LENGTH_SHORT).show();
}
}
fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/pranay/" + UUID.randomUUID().toString() + "sample.mp3";
Log.i("msg", "running");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
String channel = "pranay";
NotificationChannel notificationChannel = new NotificationChannel("id", channel, NotificationManager.IMPORTANCE_NONE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.createNotificationChannel(notificationChannel);
Notification notification = new NotificationCompat.Builder(this, "id")
.setContentTitle("sa")
.setContentText("ssa")
.setSmallIcon(R.drawable.ic_launcher_background)
.setContentIntent(pendingIntent)
.build();
startForeground(1, notification);
recorder = new MediaRecorder();
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile(fileName);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
TelephonyManager manager1 = (TelephonyManager) getApplicationContext().getSystemService(getApplicationContext().TELEPHONY_SERVICE);
manager1.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String phoneNumber) {
super.onCallStateChanged(state, phoneNumber);
if (TelephonyManager.EXTRA_STATE_IDLE.equals(intent.getStringExtra(TelephonyManager.EXTRA_STATE))) {
cleanup();
} else if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
try {
recorder.prepare();
} catch (IOException e) {
Log.e("msg", "prepare() failed");
}
recorder.start();
mStartRecording = true;
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
return super.onStartCommand(intent,flags,startId);
}
private void startForeground(Notification notification, String id) {
startForeground(notification, id);
}
private void cleanup(){
if(recorder!=null)
{
try {
recorder.stop();
}catch (Exception e){
Log.e("msg",String.valueOf(e.getMessage()));
}finally {
recorder.release();
recorder=null;
}
stopSelf();
mStartRecording = false;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
restartServiceIntent.setPackage(getPackageName());
startService(restartServiceIntent);
super.onTaskRemoved(rootIntent);
}
}
Broad cast receiver
public class Receiver extends BroadcastReceiver {
static final String ACTION = "android.intent.action.BOOT_COMPLETED";
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(context,"Booted",Toast.LENGTH_SHORT).show();
Intent serviceIntent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(serviceIntent);
}
}
Manifest
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<receiver android:name=".Receiver"
android:enabled="true"
android:exported="true"
>
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
<action android:name="RestartService"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<category android:name="android.intent.category.DEFAULT"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>
<service android:name=".Myservice"/>
I am using android 10 and pie is it working on this versions?
You can use JobService android.intent.action.BOOT_COMPLETED this method is not worked on latest version of Android.
JobService
public MyJobService extends JobService {
private Handler myHandler = new Handler(new Handler.Callback() {
#Override
public boolean handler(Message msg) {
Log.e("TAG", "Does it run after reboot? ");
return true;
}
});
#Override
public boolean onStartJob(JobParameters params) {
myHandler.sendMessage(Message.obtain(myHandler, 1, params));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
myHandler.removeMessages(1);
}
}
MainActivity
MainActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle saveInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
ComponentName serviceComponent = new ComponentName(this,MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
builder.setMinimumLatency(1 * 1000);
builder.setOverrideDeadline(5 * 1000);
builder.setPersisted(true);
JobScheduler jobScheduler = (JobScheduler) getSystemService(this.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="you.package.name">
<application
..............
>
<service
android:name=".your.package.MyJobService"
android:permission="android.permission.BIND_JOB_SERVICE" />
</mainfest>
Related
I made an Android app that should play a sound when event is received, it works when app is in focus, but when the app is closed/collapsed sound doesnt play, only standard notification.
How to start a sound/music that is placed inside the app when app with the foreground service?
Main activity:
public class MainActivity extends AppCompatActivity {
private Intent alarmServiceIntent;
private ServiceConnection sConn;
private boolean bound;
private boolean alarm = false;
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
private void Init() {
alarmServiceIntent = new Intent(this, AlarmService.class);
sConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder binder) {
bound = true;
}
public void onServiceDisconnected(ComponentName name) {
bound = false;
}
};
ContextCompat.startForegroundService(this, alarmServiceIntent);
}
private void playAlarm() {
bindService(alarmServiceIntent, sConn, BIND_AUTO_CREATE);
}
public void stopAlarm(View v) {
if (sConn != null ) {
unbindService(sConn);
}
if(alarmServiceIntent != null) {
stopService(alarmServiceIntent);
}
}
//here is the method to receive event and call playAlarm
}
Alarm service:
public class AlarmService extends Service{
private final String CHANNEL_ID = "ID";
private final String CHANNEL_NAME = "NAME";
private IBinder mBinder = new MyBinder();
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
play();
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
onStop();
return super.onUnbind(intent);
}
#Override
public void onCreate() {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_MUTABLE);
}
else
{
pendingIntent = PendingIntent.getActivity
(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
}
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("TITLE")
.setSmallIcon(R.mipmap.icon)
.setContentIntent(pendingIntent)
.build();
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel( CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
new NotificationCompat.Builder(this, CHANNEL_ID);
}
startForeground(619, notification);
return START_REDELIVER_INTENT;
}
public void play() {
if(player == null) {
player = MediaPlayer.create(this,R.raw.alarm);
player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
}
Log.v("ALARM", "play: 12345");
player.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
);
player.setVolume(2,2);
AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC), 0);
player.setLooping(true);
player.start();
}
class MyBinder extends Binder {
AlarmService getService(){
return AlarmService.this;
}
}
}
You should override onDestroy method and call stop there.
#Override
public void onDestroy() {
player.stop();
}
Notification come up in notification center with image (even app is closed | app is in background) and whenever I click notification, the activity open it but no intent data.
I always get null whenever I try to get intent extra. No matter I try hard to pass data through Bundle or directly passing in intent.setExtra, I always get null.
I have a Firebase handler class
public class MyFirebaseInstanceService extends FirebaseMessagingService {
#Override
public void onNewToken(String s) {
super.onNewToken(s);
}
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
//super.onMessageReceived(remoteMessage);
String msg = remoteMessage.getNotification().getBody();
String title = remoteMessage.getNotification().getTitle();
String channel = remoteMessage.getNotification().getChannelId();
Holder holder = new Holder();
holder.setTitle(title);
holder.setMsg(msg);
holder.setChannel(channel);
if (remoteMessage.getData().size() > 0) {
Map<String, String> params = remoteMessage.getData();
holder.setId(params.get("id"));
holder.setImgUrl(params.get("imgurl"));
holder.setType(params.get("type"));
} else {
int r = new Random().nextInt();
holder.setId(r + "");
holder.setType("bigtext");
}
sendMyNotification(holder, remoteMessage);
}
private void sendMyNotification(Holder holder, RemoteMessage remoteMessage) {
String clickAction = remoteMessage.getNotification().getClickAction();
Intent intent = new Intent(this, NotificationReadActivity.class);
if (clickAction != null) {
if (!clickAction.isEmpty() && clickAction.length() > 5)
intent = new Intent(clickAction);
}
intent.putExtra("obj", holder);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(holder.getId() + "");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, holder.getChannel());
notificationBuilder.setSmallIcon(R.mipmap.ic_launcher);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
notificationBuilder.setChannelId(holder.getChannel());
if (holder.getType().equals("bigpic")) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle());
Bitmap bitmap = getBitmapfromUrl(holder.getImgUrl());
if (bitmap != null) {
notificationBuilder.setLargeIcon(bitmap);
}
} else {
notificationBuilder.setStyle(new NotificationCompat.BigTextStyle());
}
notificationBuilder.setContentTitle(holder.getTitle());
notificationBuilder.setContentText(holder.getMsg());
PendingIntent pendingIntent = PendingIntent.getActivity(this, holder.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(holder.getChannel(), "Default", NotificationManager.IMPORTANCE_DEFAULT);
channel.enableLights(true);
channel.enableVibration(true);
channel.setLightColor(Color.RED);
channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(holder.getId(), notificationBuilder.build());
} catch (Exception ignored) {
}
}
private Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (Exception ignored) {
return null;
}
}
}
then I have a one activity
public class NotificationReadActivity extends AppCompatActivity {
TextView title, desc;
AppCompatImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_read);
title = findViewById(R.id.title);
desc = findViewById(R.id.desc);
img = findViewById(R.id.img);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
Bundle bundle = intent.getExtras();
if (intent.hasExtra("obj")) {
Holder holder = (Holder) intent.getSerializableExtra("obj");
if (holder.getType().equals("bigpic")) {
Glide.with(this).load(holder.getImgUrl()).into(img);
} else
img.setVisibility(View.GONE);
title.setText(holder.getTitle());
desc.setText(holder.getMsg());
} else if (bundle.containsKey("obj")) {
Holder holder = (Holder) bundle.getSerializable("obj");
if (holder.getType().equals("bigpic")) {
Glide.with(this).load(holder.getImgUrl()).into(img);
} else
img.setVisibility(View.GONE);
title.setText(holder.getTitle());
desc.setText(holder.getMsg());
} else {
title.setText("Null");
//finish();
}
}
}
in manifest I have also set properly
<activity
android:name=".NotificationReadActivity"
android:excludeFromRecents="true"
android:label="#string/notification_center"
android:launchMode="singleTop">
<intent-filter>
<action android:name="com.full_package.NotificationReadActivity.TARGET_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".Fcm.MyFirebaseInstanceService"
android:exported="true"
android:permission="com.google.android.c2dm.permission.SEND">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>
I have come up with the only solution is a passing string or int or any type of data other than an object in the intent will work. intent.putExtra can not handle or pass an object.
Intent intent = new Intent(this, NotificationReadActivity.class);
intent.putExtra("key1", "some string"); //this is correct
intent.putExtra("key2", 123); //this is correct
intent.putExtra("key3", any type of data); //this is correct
intent.putExtra("object", some_object); //this is in-correct
I need to show the battery level automatically in the widget, I've tried so many solutions to resolve this issue but unfortunately the widget does not update.
Here is my code:
Manifest.xml
<receiver
android:name=".BatteryWidget"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
<action android:name="com.leenah.battery.action.UPDATE" />
<action android:name="Intent.ACTION_BATTERY_CHANGED" />
</intent-filter>
<meta-data
android:name="android.appwidget.provider"
android:resource="#xml/widget_info" />
</receiver>
<service android:name=".ScreenMonitorService"></service> </manifest>
BatteryWidget.java
public class BatteryWidget extends AppWidgetProvider {
private static
final String ACTION_BATTERY_UPDATE = "com.leenah.battery.action.UPDATE";
private int batteryLevel = 0;
public static void turnAlarmOnOff(Context context, boolean turnOn) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(ACTION_BATTERY_UPDATE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
if (turnOn) { // Add extra 1 sec because sometimes ACTION_BATTERY_CHANGED is called after the first alarm alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + 1000, 300 * 1000, pendingIntent); LogFile.log("Alarm set"); } else { alarmManager.cancel(pendingIntent); LogFile.log("Alarm disabled"); } }
#Override public void onEnabled (Context context){
super.onEnabled(context);
LogFile.log("onEnabled()");
turnAlarmOnOff(context, true); // context.startService(new Intent(context, ScreenMonitorService.class)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(new Intent(context, ScreenMonitorService.class)); } else { context.startService(new Intent(context, ScreenMonitorService.class)); }
//
}
#Override public void onUpdate (Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds){
super.onUpdate(context, appWidgetManager, appWidgetIds);
LogFile.log("onUpdate()");
// Sometimes when the phone is booting, onUpdate method gets called before onEnabled() int currentLevel = calculateBatteryLevel(context); if (batteryChanged(currentLevel)) { batteryLevel = currentLevel; LogFile.log("Battery changed"); }
updateViews(context);
}
private boolean batteryChanged ( int currentLevelLeft){
return (batteryLevel != currentLevelLeft);
}
#Override public void onReceive (Context context, Intent intent){
super.onReceive(context, intent);
LogFile.log("onReceive() " + intent.getAction());
if (intent.getAction().equals(ACTION_BATTERY_UPDATE)) {
int currentLevel = calculateBatteryLevel(context);
if (batteryChanged(currentLevel)) {
LogFile.log("Battery changed");
batteryLevel = currentLevel;
updateViews(context);
}
} ///
}
#Override public void onDisabled (Context context){
super.onDisabled(context);
LogFile.log("onDisabled()");
turnAlarmOnOff(context, false);
context.stopService(new Intent(context, ScreenMonitorService.class));
}
private int calculateBatteryLevel (Context context){
LogFile.log("calculateBatteryLevel()");
Intent batteryIntent = context.getApplicationContext().registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);
return level * 100 / scale;
}
private void updateViews (Context context){
LogFile.log("updateViews()");
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_layout);
views.setTextViewText(R.id.batteryText, batteryLevel + " %");
ComponentName componentName = new ComponentName(context, BatteryWidget.class);
AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(componentName, views);
////////////////
int[] appWidgetIds = appWidgetManager.getAppWidgetIds(componentName);
appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.batteryText);
}
}
ScreenMonitorService.java
public class ScreenMonitorService extends Service {
private static BroadcastReceiver screenOffReceiver;
private static BroadcastReceiver screenOnReceiver;
private static BroadcastReceiver userPresentReceiver;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
registerScreenOffReceiver();
registerScreenOnReceiver();
registerUserPresentReceiver();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(screenOffReceiver);
unregisterReceiver(screenOnReceiver);
unregisterReceiver(userPresentReceiver);
}
private void registerScreenOffReceiver() {
screenOffReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LogFile.log(intent.getAction());
BatteryWidget.turnAlarmOnOff(context, false);
}
};
registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
private void registerScreenOnReceiver() {
screenOnReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LogFile.log(intent.getAction());
KeyguardManager keyguardManager = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
if (!keyguardManager.inKeyguardRestrictedInputMode())
BatteryWidget.turnAlarmOnOff(context, true);
}
};
registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
private void registerUserPresentReceiver() {
userPresentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
LogFile.log(intent.getAction());
BatteryWidget.turnAlarmOnOff(context, true);
}
};
registerReceiver(userPresentReceiver, new IntentFilter(Intent.ACTION_USER_PRESENT));
}
}
so the widget is showing correctly only at the first time and does not updating anymore.
Please help me to fix this problem I will be waiting for your answers.
Have a great day
I need to create a service that allow my application to work also when I close it, I’ve tried with STICKY_SERVICE but it doesn’t work... if anyone can decribe me how I can do this please answer this question.
It works with android 7.1 and it doesn’t with other versions
Here is my code...
public class SensorService extends Service {
public int counter=0;
public SensorService(Context applicationContext) {
super();
Log.i("HERE", "here I am!");
}
public SensorService() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
startTimer();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "ondestroy!");
stoptimertask();
Intent broadcastIntent = new Intent("RestartSensor");
sendBroadcast(broadcastIntent);
}
private Timer timer;
private TimerTask timerTask;
long oldTime=0;
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer, to wake up every 1 second
timer.schedule(timerTask, 1000, 1000); //
}
/**
* it sets the timer to print the counter every x seconds
*/
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
Log.i("in timer", "in timer ++++ "+ (counter++));
}
};
}
/**
* not needed
*/
public void stoptimertask() {
//stop the timer, if it's not already null
if (timer != null) {
timer.cancel();
timer = null;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my service Restarter...
public class SensorRestarterBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i(SensorRestarterBroadcastReceiver.class.getSimpleName(), "Service Stops");
context.startService(new Intent(context, SensorService.class));
}
}
And the mainClass
public class MainActivity extends AppCompatActivity {
Intent mServiceIntent;
private SensorService mSensorService;
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ctx = this;
setContentView(R.layout.activity_main);
mSensorService = new SensorService(getCtx());
mServiceIntent = new Intent(getCtx(), mSensorService.getClass());
if (!isMyServiceRunning(mSensorService.getClass())) {
startService(mServiceIntent);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("isMyServiceRunning?", true+"");
return true;
}
}
Log.i ("isMyServiceRunning?", false+"");
return false;
}
#Override
protected void onDestroy() {
stopService(mServiceIntent);
Log.i("MAINACT", "onDestroy!");
super.onDestroy();
}
}
This restartthe service correctly but after 3/4 seconds it die.
I've added this to my manifest
<service
android:name=".SensorService"
android:enabled="true" >
</service>
<receiver
android:name=".SensorRestarterBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:label="RestartServiceWhenStopped">
<intent-filter>
<action android:name="RestartSensor"/>
</intent-filter>
</receiver>
Add the following code to your sensor service and edit as per your need. You need to bind the sticky service to a notification to keep the service alive and start in the foreground.
#Override
public void onCreate() {
super.onCreate();
Intent notifIntent = new Intent(this, SensorService.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, notifIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.smslogo_100x100)
.setColor(ContextCompat.getColor(this, R.color.colorAccent))
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText("Running")
.setContentIntent(pi)
.build();
startForeground(101010, notification);
}
This will rectify the issue you are facing and the service will run forever.
This code isn't working for me it should make notification every 2 sec the app runs with no errors and then after 2 sec keeps giving me messages you're app has stopped working.
I added these codes:
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<service android:name="NotificationService" android:exported="false"/>
<receiver android:name="BootReceiver">
<intent-filter>
<action android:name="com.company.app"/>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
MainActivity.java
startActivity(new Intent(this,NotificationService.class));
NotificationService.java
public class NotificationService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer=new Timer();
mTimer.schedule(timerTask,2000,2*1000);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
}catch (Exception e){
e.printStackTrace();
}
return super.onStartCommand(intent, flags, startId);
}
private Timer mTimer;
TimerTask timerTask=new TimerTask() {
#Override
public void run() {
Log.e("log","Running");
notifiy();
}
};
#Override
public void onDestroy() {
try {
mTimer.cancel();
timerTask.cancel();
}catch (Exception e){
e.printStackTrace();
}
Intent intent=new Intent("com.company.app");
intent.putExtra("your value","torestore");
sendBroadcast(intent);
}
public void notifiy(){
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("RSSPullService");
Intent mIntent=new Intent(Intent.ACTION_VIEW, Uri.parse(""));
PendingIntent pendingIntent=PendingIntent.getActivity(getBaseContext(),0,mIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
Context context=getApplicationContext();
Notification.Builder builder=new Notification.Builder(context)
.setContentTitle("T")
.setContentText("M")
.setContentIntent(pendingIntent)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
;//.setSmallIcon();
Notification notification=builder.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1,notification);
}
}
BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Service stops","ohhhhhhh");
context.startService(new Intent(context,NotificationService.class));
}
}