-2

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?

Prototype
  • 486
  • 1
  • 4
  • 17
  • 1
    Do you have an `Activity` that you're launching after installation to bring your app out of the stopped state? Your Receiver won't work until then. Also, get rid of that `` from the ``, and the `RestartService` ``, as well. – Mike M. Sep 18 '20 at 09:12
  • Yes i have Mainactivity in my appliction – Prototype Sep 18 '20 at 09:17
  • Sir i have checked the `BOOT_COMPLETED` not listing – Prototype Sep 18 '20 at 09:18
  • I don't know what that means. How exactly are you determining that it's the Receiver that has the issue? How do you know it's not the `Service` failing? – Mike M. Sep 18 '20 at 09:20
  • Sir i am using this code please check [link](https://codinginflow.com/tutorials/android/start-app-on-boot) – Prototype Sep 18 '20 at 09:21
  • That doesn't answer my questions. – Mike M. Sep 18 '20 at 09:22
  • But still the application is not opening – Prototype Sep 18 '20 at 09:22
  • Unless you can provide more debugging details, this is about all I can suggest to consider: https://stackoverflow.com/q/46445265. – Mike M. Sep 18 '20 at 09:24
  • I am showing notification when app is running in background – Prototype Sep 18 '20 at 09:26
  • Again, I don't know what that means, but that link is saying that the `Service` needs to be a foreground `Service`, started with `startForegroundService()` on recent versions, and calling `startForeground()` itself internally. Also, I don't see any `Notification` code anywhere, so I'm not sure how that fits in here. – Mike M. Sep 18 '20 at 09:28
  • ok i will update full code – Prototype Sep 18 '20 at 09:30
  • Ok, where's the `startForegroundService()` call? – Mike M. Sep 18 '20 at 09:37
  • I have also used `START_STICKEY` instead of this `return super.onStartCommand(intent,flags,startId);` – Prototype Sep 18 '20 at 09:42
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221681/discussion-between-prototype86-and-mike-m). – Prototype Sep 18 '20 at 09:44

1 Answers1

1

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>