如何在暂停时将通知时间更改为秒表应用程序

时间:2017-11-05 14:49:21

标签: java android android-gradle

当应用 onPause onStop 时,我希望将通知时间与秒表同步。

final NotificationCompat.Builder mBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
    .setOngoing(StartRun)
    .setContentText( Lap + " " + s + " " ) 
    .setAutoCancel(true)
    .setLargeIcon(BitmapFactory.decodeResour‌​ce(getResources(), R.drawable.a)) 
    .setSmallIcon(R.drawable.a); 

mBuilder.setContentIntent(pendingIntent);
mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
mNotifyMgr.notify(mNotificationId,mBuilder.build());

2 个答案:

答案 0 :(得分:0)

是您应用的秒表还是其他应用?

如果stopWatch属于您自己的应用,那么只需在服务上运行它,然后在那里进行通知业务。 虽然如果你的应用程序的生命周期是onDestroy,这不会起作用。 但是你不需要它在你的Activities onDestroy之后运行,因为大多数情况下,stopWatch本身都不会存在。

如果stopWatch属于另一个应用,或者它是您自己的应用,但是在与您的活动分离的backGround上运行,那么您需要确保您的服务的LifeCycle没有附加到启动它的活动。

如果属于另一个应用程序的stopWatch将一个BroadCastListener注册到Manifest中的服务。

答案 1 :(得分:0)

        public class MyService extends Service {
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        SharedPreferences preferences=getSharedPreferences("Timer",MODE_PRIVATE);
        SharedPreferences preferences1=getSharedPreferences("Lap",MODE_PRIVATE);
        seconds=preferences.getInt("time",0);
         hours=seconds/3600;
        String Lap=preferences1.getString("Lap","null");
         minutes=(seconds%3600)/60;
         sec=seconds%60;
        StartRun=true;
        final int mNotificationId = 001;
  /* Creates an explicit intent for an Activity in your app */
        Intent i = getPackageManager()
                .getLaunchIntentForPackage(getPackageName())
                .setPackage(null)
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED );

        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, i, 0);

        String s=("" + hours + ":" + String.format("%02d", minutes) + ":" + String.format("%02d", sec));

        final NotificationCompat.Builder mBuilder =
                (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                        .setOngoing(StartRun)
                        .setContentText( Lap + "  " + s + " " )
                        .setAutoCancel(true)
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.a))
                        .setSmallIcon(R.drawable.a);
                        mBuilder.setContentIntent(pendingIntent);

                    mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                    mNotifyMgr.notify(mNotificationId,mBuilder.build());

        return START_STICKY;
    }

    NotificationManager mNotifyMgr;
}