总是显示在通知栏服务 [英] Always show service in notification bar

查看:239
本文介绍了总是显示在通知栏服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的应用程序添加到通知栏,以便它总是显示,喜欢在谷歌Play商店应用程序的一些

我希望它是这样的屏幕截图:

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

这是我的服务类code:

 包com.demo;

导入了java.util.Random;

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

公共类ServiceExample延伸服务{

    @覆盖
    公众的IBinder onBind(意向意图){
        返回null;
    }

    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        Toast.makeText(本,服务创建,300).show();
    }

    @覆盖
    公共无效的onDestroy(){
        super.onDestroy();
        Toast.makeText(本,服务破坏,300).show();
    }

    @覆盖
    公共无效onLowMemory(){
        super.onLowMemory();
        Toast.makeText(本,服务LowMemory,300).show();
    }

    @覆盖
    公共无效ONSTART(意向意图,诠释startId){
        super.onStart(意向,startId);
        Toast.makeText(本,服务启动,300).show();
        通知通知=新的通知(R.drawable.ic_launcher,
                滚动在状态条上的文字,System.currentTimeMillis的());

        PendingIntent contentIntent = PendingIntent.getActivity(此,0,
                新的意图(这一点,ServiceDemoActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(这一点,
                通知标题,通知说明,contentIntent);

        startForeground(1,通知);
    }

    @覆盖
    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){

        Toast.makeText(这一点,在服务任务完成,300).show();
        / * ThreadDemo就TD =新ThreadDemo就();
        td.start(); * /
        通知通知=新的通知(R.drawable.ic_launcher,
                滚动在状态条上的文字,System.currentTimeMillis的());

        PendingIntent contentIntent = PendingIntent.getActivity(此,0,
                新的意图(这一点,ServiceDemoActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(这一点,
                通知标题,通知说明,contentIntent);

        startForeground(1,通知);

        返回super.onStartCommand(意向,标志,startId);
    }

    私有类ThreadDemo就继承Thread {
        @覆盖
        公共无效的run(){
            super.run();
            尝试{
            睡眠(70 * 1000);
            handler.sendEmptyMessage(0);
            }赶上(例外五){
                e.getMessage();
            }
        }
    }
   私人处理程序处理程序=新的处理程序(){
    @覆盖
    公共无效的handleMessage(信息MSG){
        super.handleMessage(MSG);
        showAppNotification();
    }
   };

   无效showAppNotification(){
       尝试{
        NotificationManager纳米=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //该PendingIntent来,如果用户选择此推出我们的活动
        // 通知。注意使用FLAG_CANCEL_CURRENT的,使得如果有
        //已经是一个积极的匹配挂起的意图,取消和更换
        与意图的新数组//它。
// PendingIntent contentIntent = PendingIntent.getActivities(此,0,
//我的服务已完成,PendingIntent.FLAG_CANCEL_CURRENT);

        //该股票的文字,使用了一种格式化字符串,所以我们的信息可进行本地化
        字符串tickerText =djdjsdjkd;

        //构造通知对象。
        注意notif =新的通知(R.drawable.ic_launcher,tickerText,
                System.currentTimeMillis的());

        //设置为显示在通知面板的意见信息。
// notif.setLatestEventInfo(这一点,从,消息,contentIntent);

        //我们将有此通知执行默认的声音,震动,并导致。
        //注意,如果你想要的任何这些行为,你应该始终有
        //一个preference用户将其关闭。
        notif.defaults = Notification.DEFAULT_ALL;

        //注意,我们使用R.layout.incoming_message_panel作为ID为
        //通知。它可以是任何你想要的整数,但我们使用
        //使用资源ID相关的字符串的约定
        //通知。这将永远是内唯一的编号您
        // 应用。
        nm.notify(0,notif);
       }赶上(例外五){
           e.getMessage();
       }
    }
}
 

和我宣布我的服务我的项目清单文件:

 < XML版本=1.0编码=UTF-8&GT?;
<舱单的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    包=com.demo
    安卓版code =1
    机器人:VERSIONNAME =1.0>

    <使用-SDK安卓的minSdkVersion =8/>
    <应用
        机器人:图标=@可绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME>
        <活动
            机器人:ServiceDemoActivityNAME =
            机器人:标签=@字符串/ APP_NAME>
            <意向滤光器>
                <作用机器人:名称=android.intent.action.MAIN/>
                <类机器人:名称=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
        <服务机器人:名称=。ServiceExample>< /服务>
    < /用途>

< /舱单>
 

下面是我的课的启动和停止服务:

 包com.demo;

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

公共类ServiceDemoActivity扩展活动实现OnClickListener {
    / **第一次创建活动时调用。 * /
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(本);
        findViewById(R.id.stop).setOnClickListener(本);
    }

    私人意图inetnt;
    @覆盖
    公共无效的onClick(视图v){
        开关(v.getId()){
        案例R.id.start:

            inetnt =新的意图(这一点,ServiceExample.class);
            startService(inetnt);
            打破;
        案例R.id.stop:

            inetnt =新的意图(这一点,ServiceExample.class);
            stopService(inetnt);
            打破;
        }
    }

    @覆盖
    保护无效onResume(){
        super.onResume();
    }

    @覆盖
    保护无效的onDestroy(){
        super.onDestroy();
//
    }
}
 

下面是我的布局code:

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =FILL_PARENT
    机器人:layout_height =FILL_PARENT
    机器人:方向=垂直>

    <按钮
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=StartService
        机器人:ID =@ + ID /开始/>

        <按钮
        机器人:layout_width =FILL_PARENT
        机器人:layout_height =WRAP_CONTENT
        机器人:文本=StopService
        机器人:ID =@ + ID /停止/>

< / LinearLayout中>
 

解决方案

如果你希望你的应用程序能够在任何时候,状态栏present,你必须写一个服务和呼叫 startForeground(ID,通知) ONSTART(...) onStartCommand(...)方法,并分别调用该服务的的onDestroy()方法 stopForeground()方法。

的id为整数,可以分配给该通知,并通知是通知对象(你可以阅读有关它的详细位置:<一href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html">http://developer.android.com/guide/topics/ui/notifiers/notifications.html).

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

 的通知的通知=新的通知(R.drawable.statusbar_icon,
        滚动在状态条上的文字,System.currentTimeMillis的());

PendingIntent contentIntent = PendingIntent.getActivity(此,0,
        新的意图(这一点,YourActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);

notification.setLatestEventInfo(这一点,
        通知标题,通知说明,contentIntent);

startForeground(1,通知);
 

您可以把这个code在该服务的 ONSTART(...) onStartCommand(...)的方法。

你也可以阅读更多的在这里的服务:<一href="http://developer.android.com/reference/android/app/Service.html">http://developer.android.com/reference/android/app/Service.html

I want to add my app to the notification bar so that it always shows, like some apps in the Google Play store.

I want it to be like this screen shot:

I want my notification to not be cleared, and for my app to be opened when the notification is clicked.

Here's My Service Class Code:

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();
       }
    }
}

And I declare my Service in my project manifest file:

<?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>

Here's my class for starting and stopping the Service:

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();
//      
    }
}

Here's my layout code:

<?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>

解决方案

If you want your application to be present on the status bar at all times, you have to write a service and call startForeground(id, notification) in the onStart(...) and onStartCommand(...) methods and respectively call the stopForeground() method in the onDestroy() method of the service.

The id is an integer you can assign to the notification and notification is a Notification object (you can read about it more here: http://developer.android.com/guide/topics/ui/notifiers/notifications.html).

This way as long as your service is running, the status bar notification will show.

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);

You can put this code in the service's onStart(...) and onStartCommand(...) methods.

Also you can read more on services here: http://developer.android.com/reference/android/app/Service.html

这篇关于总是显示在通知栏服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆