始终在通知栏中显示服务

Din*_*esh 11 notifications android android-service

我想将我的应用添加到通知栏,以便始终显示,就像Google Play商店中的某些应用一样.

我希望它像这个屏幕截图:

在此输入图像描述

我希望我的通知不被清除,并且在点击通知时打开我的应用程序.

这是我的服务类代码:

package com.demo;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ServiceExample extends Service {

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

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"Service Created",300).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Destroy",300).show();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Toast.makeText(this,"Service LowMemory",300).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"Service start",300).show();
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this,"task perform in service",300).show();
        /*ThreadDemo td=new ThreadDemo();
        td.start();*/
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);

        return super.onStartCommand(intent, flags, startId);
    }

    private class ThreadDemo extends Thread{
        @Override
        public void run() {
            super.run();
            try{
            sleep(70*1000); 
            handler.sendEmptyMessage(0);
            }catch(Exception e){
                e.getMessage();
            }
        }
    }
   private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        showAppNotification();
    }
   };

   void showAppNotification() {
       try{
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_CANCEL_CURRENT so that, if there
        // is already an active matching pending intent, cancel it and replace
        // it with the new array of Intents.
//      PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
//             "My service completed", PendingIntent.FLAG_CANCEL_CURRENT);

        // The ticker text, this uses a formatted string so our message could be localized
        String tickerText ="djdjsdjkd";

        // construct the Notification object.
        Notification notif = new Notification(R.drawable.ic_launcher, tickerText,
                System.currentTimeMillis());

        // Set the info for the views that show in the notification panel.
//      notif.setLatestEventInfo(this, from, message, contentIntent);

        // We'll have this notification do the default sound, vibration, and led.
        // Note that if you want any of these behaviors, you should always have
        // a preference for the user to turn them off.
        notif.defaults = Notification.DEFAULT_ALL;

        // Note that we use R.layout.incoming_message_panel as the ID for
        // the notification.  It could be any integer you want, but we use
        // the convention of using a resource id for a string related to
        // the notification.  It will always be a unique number within your
        // application.
        nm.notify(0, notif);
       }catch(Exception e){
           e.getMessage();
       }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在我的项目清单文件中声明我的服务:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceDemoActivity"
            android:label="@string/app_name"  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ServiceExample"></service>
    </application>

</manifest>
Run Code Online (Sandbox Code Playgroud)

这是我启动和停止服务的课程:

package com.demo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class ServiceDemoActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
    }

    private Intent inetnt;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:

            inetnt=new Intent(this,ServiceExample.class);
            startService(inetnt);
            break;
        case R.id.stop:

            inetnt=new Intent(this,ServiceExample.class);
            stopService(inetnt);
            break;
        }
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
//      
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StartService" 
        android:id="@+id/start"/>

        <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StopService"
        android:id="@+id/stop" />

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

Dar*_*tle 19

为了始终显示您的通知,您需要设置以下两个标志:

notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
Run Code Online (Sandbox Code Playgroud)

请注意,虽然将服务设置为前台也会使您获得正在进行的事件,这是非常不合适的事情,除非您确实需要服务在前台运行.音乐播放器就是一个应该做到这一点的应用程序的一个很好的例子 - 用户期望他们的音乐将不间断地播放,即使在使用该设备做许多其他事情时也是如此.

但是,大多数服务可以在内存不足时由系统暂时停止,然后在内存再次可用时自动重启.所以考虑它的正确方法是将这两个想法分开.

  1. 如果您希望始终显示通知,请使用我提到的两个标志.
  2. 如果您碰巧还需要服务在前台运行,您可以而且应该致电Service.startForeground(),但不要将此视为获取持续通知的方式.

  • 我不会被冒犯:) (3认同)
  • @HeroVsZero非常欢迎你.你可以考虑选择这个作为接受的答案,因为,这是正确的答案.正如我已经解释过的那样,尽管我喜欢paradx以保持代表的真实和深思熟虑的答案,但他的建议实际上是不好的建议.我认为将未来访问者引导到最正确的答案是决定选择哪个答案的最重要因素. (2认同)

Ada*_*nos 10

如果你希望你的应用程序出现在任何时候都在状态栏上,你必须写一个服务,并呼吁startForeground(id, notification)onStart(...)onStartCommand(...)方法,并分别调用stopForeground()方法的onDestroy()服务的方法.

id是一个可以分配给通知的整数,通知是一个Notification对象(您可以在这里阅读更多信息:http://developer.android.com/guide/topics/ui/notifiers/notifications.html).

这样,只要您的服务正在运行,状态栏通知就会显示.

Notification notification = new Notification(R.drawable.statusbar_icon,
        "Rolling text on statusbar", System.currentTimeMillis());

PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
        new Intent(this, YourActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

notification.setLatestEventInfo(this,
        "Notification title", "Notification description", contentIntent);

startForeground(1, notification);
Run Code Online (Sandbox Code Playgroud)

您可以将此代码放在服务onStart(...)onStartCommand(...)方法中.

您还可以在此处阅读有关服务的更多信息:http://developer.android.com/reference/android/app/Service.html