android – 始终在通知栏中显示服务

android – 始终在通知栏中显示服务,第1张

概述我想将我的应用添加到通知栏,以便它始终显示,如Google Play商店中的某些应用. 我想要这样的屏幕截图: 我希望我的通知不被清除,并且当我的应用程序在通知单击时被打开. 这是我的服务类代码: package com.demo;import java.util.Random;import android.app.Notification;import android.app.Noti 我想将我的应用添加到通知栏,以便它始终显示,如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,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,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,//             "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();       }    }}

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

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

这是我开始和停止服务的课程:

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

这是我的布局代码:

<?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>
解决方法 如果您希望应用程序始终处于状态栏中,则必须在onStart(…)和onStartCommand(…)方法中编写一个服务并调用startForeground(ID,notification),并分别调用在服务的onDestroy()方法中使用stopForeground()方法.

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

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

Notification notification = new Notification(R.drawable.statusbar_icon,System.currentTimeMillis());PendingIntent contentIntent = PendingIntent.getActivity(this,YourActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);notification.setLatestEventInfo(this,contentIntent);startForeground(1,notification);

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

此外,您可以在这里阅读更多服务:http://developer.android.com/reference/android/app/Service.html

总结

以上是内存溢出为你收集整理的android – 始终在通知栏中显示服务全部内容,希望文章能够帮你解决android – 始终在通知栏中显示服务所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1131840.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存