BroadcastReceiver启动通知服务,但该服务未更新

时间:2019-02-17 10:23:43

标签: java service broadcastreceiver

我创建一个计算步骤的应用程序。该应用程序显示使用该服务在通知中采取的步骤数。该服务在最小化应用程序和服务运行时启动,重复步骤数,效果很好。 我还创建了一个广播接收器,当应用程序完全关闭时,它将启动服务。 问题在于该服务已启动,但不会更新步骤中的数据。

如何在从Broadcastreceiver运行的服务中配置数据更新?

在MainActivity的此部分中,将启动服务并更新通知行中的数据。

       @Override
    public void step(long timeNs) {
        numSteps++;
        TvSteps.setText( TEXT_NUM_STEPS + numSteps );
        distView.setText( String.valueOf( df.format( (numSteps * step) ) ) + " m" );
        calView.setText( String.valueOf( df.format( 0.5 * calories * (numSteps * step / 1000) ) ) + " kcal" );
        mProgress.setProgress( mProgress.getProgress() + 1 );
        saveSprefs();
        startNotifyIntent();

    }

this is the method that start service
      protected void startNotifyIntent() {
        startService( new Intent( this, YourService.class ) );
    }

in OnStop method of my MainActivity I initialize BroadcastReceiver by using the method SetAlarmNotification 

      protected void SetAlarmNotification(){

            Calendar calendar=Calendar.getInstance();

            Intent intent=new Intent( getApplicationContext(), NotificationReceiver.class );
            PendingIntent pendingIntent=PendingIntent.getBroadcast( getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT );

            AlarmManager alarmManager=(AlarmManager) getSystemService( ALARM_SERVICE );
            alarmManager.setRepeating( AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()
                    , 60000, pendingIntent );
            SharedPreferences.Editor editor=sPrefs.edit();
            editor.putString( "SetAlarmReceiver", "alarmSet" );
            editor.apply();
        }

我的服务

  public class YourService extends Service {


    public final String PREFERENSES = "settings";
    SharedPreferences sPrefs;
    private static final int NOTIF_ID = 1;
    private static final String NOTIF_CHANNEL_ID = "Channel_Id";
    final String dateString = String.valueOf ( new SimpleDateFormat ( "ddMMyyyy" ).format ( Calendar.getInstance ().getTime () ) );
    DecimalFormat df = new DecimalFormat ( "0.0" );
    private static final String TEXT_NUM_STEPS = "";
    private int numSteps;
    double step;


    @Override
    public void onCreate() {
        super.onCreate ();
        sPrefs = getApplicationContext ().getSharedPreferences ( PREFERENSES, MODE_PRIVATE );

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        numSteps = Integer.parseInt ( Objects.requireNonNull ( sPrefs.getString ( dateString, null ) ) );
        step = ( ( ( sPrefs.getInt ( "setHeight", 0 ) / 4.0 ) + 37.0 ) / 100.0 );
        startForeground ();
        return Service.START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy ();
        Toast toast = Toast.makeText ( this, "Ooops,IM Closing", Toast.LENGTH_LONG );
        toast.show ();
    }


    private void startForeground() {
        Intent notificationIntent = new Intent ( this, MainActivity.class );
        PendingIntent pendingIntent = PendingIntent.getActivity ( this, 0,
                notificationIntent, 0 );
        startForeground ( NOTIF_ID, new NotificationCompat.Builder ( this,
                NOTIF_CHANNEL_ID )
                .setSmallIcon ( R.drawable.ic_launcher_background )
                .setPriority ( PRIORITY_HIGH )
                .setContentText ( String.valueOf ( df.format ( Integer.parseInt
                        ( sPrefs.getString ( dateString, null ) ) * step ) ) + " m" )
                .setOngoing ( true )
                .setOngoing ( true )
                .setOnlyAlertOnce ( true )
                .setContentTitle ( TEXT_NUM_STEPS + numSteps + " steps" )
                .setSmallIcon ( R.drawable.ic_launcher_background )
                .setContentIntent ( pendingIntent )
                .build () );

    }
}

我的BroadcastReceiver:

public class NotificationReceiver extends BroadcastReceiver {

    public final String PREFERENSES="settings";
    SharedPreferences sPrefs;
    @TargetApi(Build.VERSION_CODES.KITKAT)

    @Override
    public void onReceive(Context context, Intent intent) {
        sPrefs = context.getSharedPreferences ( PREFERENSES, MODE_PRIVATE );

        if (Objects.equals ( sPrefs.getString ( "SetAlarmReceiver", null ), "alarmSet" )) {

                    Intent i = new Intent(context.getApplicationContext(), YourService.class);

                    SharedPreferences.Editor editor = sPrefs.edit ();
                    editor.putString ( "SetAlarmReceiver", "alarmUse" );
                    editor.apply ();

                    context.getApplicationContext ().startService(i);

            }

        }
    }

我也在清单中注册了我的服务和广播接收者

     <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.guahoo.pedometer">

    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.SET_ALARM" />



    <application
        android:allowBackup="true"
        android:icon="@drawable/ikonka"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning"
        >
        <activity android:name=".Activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Activity.SettingsActivity" />



        <service android:name=".Services.YourService"
            android:exported="true"
            android:enabled="true"
            />
        <receiver android:name=".Reseivers.NotificationReceiver"/>
    </application>

</manifest>

我希望服务开始更新数据或至少了解问题所在。

0 个答案:

没有答案