Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

android - Always show service in notification bar

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:

enter image description here

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In order to have your notification always present, you'll want to set these two flags:

notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;

Note that while setting your Service to be in the foreground will also get you an ongoing event, that is a very inappropriate thing to do unless you truly do need your Service to run in the foreground. A music player is a good example of an app that should do that -- the user has an expectation that their music will play without interruption, even when doing many other things with the device.

Most Services, however, can afford to be temporarily stopped by the system when memory is low, and then restarted automatically when memory is available again. So the correct way to think about it is to separate the two ideas.

  1. If you want your notification to always be visible, use the two flags I mentioned.
  2. If you happen to also need your Service to run in the foreground, you can and should call Service.startForeground(), but don't think of this as a way to get an ongoing notification.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...