Служба не запускается в Android из AlarmManager после закрытия приложения - PullRequest
0 голосов
/ 05 июля 2018

Может ли кто-нибудь исправить мой подход или предложить мне правильные способы сделать это. Я пытался использовать широковещательные приемники вместо служб, но этот подход не работает для него. То есть я использовал getBroadcast () вместо getService () но не сработало.

Это работает, когда приложение не закрывается из окна приложения, но как только оно закрыто, телефон не показывает уведомления и звонит, как это было в случае, когда приложение не было закрыто.

MainActivity.class

`public class MainActivity extends AppCompatActivity {

    TimePicker timePicker;
    Button button;
    AlarmManager alarmManager;
    PendingIntent alarmIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        timePicker = findViewById(R.id.timePicker);
        button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                if (Build.VERSION.SDK_INT >= 23) {
                    calendar.set(
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH),
                            timePicker.getHour(),
                            timePicker.getMinute(),
                            0
                    );
                } else {
                    calendar.set(
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH),
                            timePicker.getCurrentHour(),
                            timePicker.getCurrentMinute(),
                            0
                    );
                }
                Intent intent = new Intent(MainActivity.this,MyIntentService.class);
//This is the intent which will be fired
                alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmIntent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
                alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
                Log.e("TAG:","AlarmSet.");
// Log is showing the right statement i.e the alarm was set but it wasnt triggered when the app was closed from the application window
            }
       });

    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("TAG","OnPause.");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e("TAG","OnStop.");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("TAG","OnDestroy.");
    }
}`

IntentService.class

`public class MyIntentService extends IntentService {
 public MyIntentService() {
     super("MyIntentService");
 }

 @Override
 protected void onHandleIntent(@Nullable Intent intent) {
     Log.e("TAG", "Starting service for notification and song");
     Random random = new Random();
     final Notification notification = new  NotificationCompat.Builder(getApplicationContext(), "notify")
            .setContentTitle("New Notification")
            .setContentText("TIme for task.")
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setPriority(Notification.PRIORITY_MAX)
            .build();
     final NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
     notificationManager.notify(random.nextInt(), notification);
     MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
     mediaPlayer.start();

 }
}`

Файл манифеста

`

<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=".MyIntentService"
        android:enabled="true"
        android:exported="true" />
 </application>

</manifest>`
...