用服务来运行的背景和创建通知 [英] Using Service to run background and create notification

查看:95
本文介绍了用服务来运行的背景和创建通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在想我的应用程序启动服务单击该按钮,服务应该在后台运行,显示通知在每天的特定时间。我有以下的code做到这一点。但其显示的错误,我不明白。是新的Andr​​oid和这是一个使用服务我的第一个应用程序。任何帮助将是AP preciated。先谢谢了。

AndroidManifest.xml中

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

    <用途-SDK
        安卓的minSdkVersion =8
        机器人:targetSdkVersion =18/>

    <应用
        机器人:allowBackup =真
        机器人:图标=@可绘制/ ic_launcher
        机器人:标签=@字符串/ APP_NAME
        机器人:主题=@风格/ AppTheme>
        <活动
            机器人:名称=com.example.newtrial.CreateNotificationActiviy
            机器人:标签=@字符串/ APP_NAME>
            <意向滤光器>
                <作用机器人:名称=android.intent.action.MAIN/>

                <类机器人:名称=android.intent.category.LAUNCHER/>
            &所述; /意图滤光器>
        < /活性GT;
        <活动
            机器人:名称=com.example.newtrial.ResultActivity
            机器人:标签=@字符串/ title_activity_result>

        < /活性GT;

        <服务机器人:启用=真正的机器人:名称= />中UpdaterServiceManager。

    < /用途>

< /舱单>
 

CreateNotificationActiviy.java

 包com.example.newtrial;

进口android.os.Bundle;
进口android.app.Activity;
进口android.app.Notification;
进口android.app.NotificationManager;
进口android.app.PendingIntent;
进口android.content.Intent;
进口android.view.Menu;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;

公共类CreateNotificationActiviy延伸活动{

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.create_notification_activiy);

        按钮B =(按钮)findViewById(R.id.button1);
        b.setOnClickListener(新OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根
                startService(新意图(CreateNotificationActiviy.this,UpdaterServiceManager.class));
            }

        });

    }

    公共无效createNotification(查看视图){
        //如果这是引发prepare意图
        //通知被选中。
        意向意图=新的意图(这一点,ResultActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(此,0,意图,0);

        //构建通知
        //操作都只是假的
        通知NotI位=新Notification.Builder(本)
            .setContentTitle(通知标题)
            .setContentText(点击这里阅读)。setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            。建立();
        NotificationManager notificationManager =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        //隐藏其选中后通知
        noti.flags | = Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0,NotI位);

      }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.create_notification_activiy,菜单);
        返回true;
    }

}
 

UpdaterServiceManager.java

 包com.example.newtrial;

进口的java.util.Calendar;
进口java.util.Timer中;
进口java.util.TimerTask中;

进口android.app.AlertDialog;
进口android.app.Notification;
进口android.app.NotificationManager;
进口android.app.PendingIntent;
进口android.app.Service;
进口android.content.Context;
进口android.content.Intent;
进口android.os.IBinder;
进口android.util.Log;
进口android.view.View;

公共类UpdaterServiceManager延伸服务{

    私人最终诠释更新周期= 60 * 1000;
    私人定时器定时=新的Timer();
    私有静态最终诠释NOTIFICATION_EX = 1;
    私人NotificationManager notificationManager;
    CreateNotificationActiviy没有;

    公共UpdaterServiceManager(){
        没有=新CreateNotificationActiviy();
    }

    @覆盖
    公众的IBinder onBind(意向意图){
        // TODO自动生成方法存根
        返回null;
    }

    @覆盖
    公共无效的onCreate(){
        // code第一次创建服务时执行
        super.onCreate();
        Log.i(为MyService,服务启动。);
        showNotification();
    }

    公共无效showNotification()
    {
        最后的日历CLD = Calendar.getInstance();

        INT时间= cld.get(Calendar.HOUR_OF_DAY);
        如果(时间> 12)
        {
                  not.createNotification(空);

        }
        其他
        {
            AlertDialog.Builder警报=新AlertDialog.Builder(本);
            alert.setMessage(尚未);
            alert.setTitle(错误);
            alert.setPositiveButton(OK,NULL);
            。alert.create()显示();
        }
    }

    @覆盖
    公共无效的onDestroy(){
        如果(定时器!= NULL){
            timer.cancel();
        }
    }

    @覆盖
    公众诠释onStartCommand(意向意图,INT标志,INT startid)
    {
        返回START_STICKY;
    }

    私人无效stopService(){
        如果(!定时器= NULL)timer.cancel();
    }

}
 

ResultActivity.java

 包com.example.newtrial;

进口android.os.Bundle;
进口android.app.Activity;
进口android.view.Menu;
进口android.widget.TextView;

公共类ResultActivity延伸活动{

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_result);
        TextView的电视=(TextView中)findViewById(R.id.textView1);
        tv.setText(通知后点击);
    }

    @覆盖
    公共布尔onCreateOptionsMenu(功能菜单){
        //充气菜单;这增加了项目操作栏,如果它是present。
        。getMenuInflater()膨胀(R.menu.result,菜单);
        返回true;
    }

}
 

logcat的

  12月12日至十日:14:04.286:I /处理(872):发送信号。 PID:872 SIG:9
一十二月12日至10日:14:11.774:I /则将MyService(893):服务启动。
一十二月12日至10日:14:12.094:D / AndroidRuntime(893):关闭虚拟机
一十二月12日至10日:14:12.094:W / dalvikvm(893):主题ID = 1:螺纹退出与未捕获的异常(组= 0x414c4700)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):致命异常:主要
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):java.lang.RuntimeException的:无法创建服务com.example.newtrial.UpdaterServiceManager:android.view.WindowManager $ BadTokenException:无法添加窗口 - 标记空是不为应用程序
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.ActivityThread.handleCreateService(ActivityThread.java:2587)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.ActivityThread.access $ 1600(ActivityThread.java:141)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1338)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.os.Handler.dispatchMessage(Handler.java:99)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.os.Looper.loop(Looper.java:137)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.ActivityThread.main(ActivityThread.java:5103)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在java.lang.reflect.Method.invokeNative(本机方法)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在java.lang.reflect.Method.invoke(Method.java:525)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在dalvik.system.NativeStart.main(本机方法)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):android.view.WindowManager $ BadTokenException:产生的原因无法添加窗口 - 令牌null不是一个应用程序
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.view.ViewRootImpl.setView(ViewRootImpl.java:563)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:269)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.Dialog.show(Dialog.java:281)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在com.example.newtrial.UpdaterServiceManager.showNotification(UpdaterServiceManager.java:65)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在com.example.newtrial.UpdaterServiceManager.onCreate(UpdaterServiceManager.java:41)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):在android.app.ActivityThread.handleCreateService(ActivityThread.java:2577)
一十二月12日至10日:14:12.124:E / AndroidRuntime(893):10 ...更多
 

解决方案

你的错误是在UpdaterServiceManager中的onCreate和showNotification方法。

正在试图展示的通知使用活动上下文服务。而每个服务都有自己的内容,只使用了。你并不需要传递服务的活动的背景下。我不明白为什么你需要一个特定的活动的背景下,显示通知。

把你的 createNotification方法UpdateServiceManager.class 。和删除CreateNotificationActivity 不是从服务。

  

您无法通过上下文不是一个活动显示一个应用程序窗口/对话框。尝试通过有效的活动参考

In want my app to start Service when the button is clicked and the Service should run in background to show a notification at a particular time of day. I have the following code to do this. But its shows errors which I don't understand. Am new to android and this is my first app using Service. Any help would be appreciated. Thanks in advance.

AndroidManifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.newtrial.CreateNotificationActiviy"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.newtrial.ResultActivity"
            android:label="@string/title_activity_result" >

        </activity>

        <service android:enabled="true" android:name=".UpdaterServiceManager" />

    </application>

</manifest>

CreateNotificationActiviy.java

package com.example.newtrial;

import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CreateNotificationActiviy extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_notification_activiy);

        Button b=(Button)findViewById(R.id.button1);
        b.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub      
                startService(new Intent(CreateNotificationActiviy.this, UpdaterServiceManager.class));
            }

        });

    }

    public void createNotification(View view) {
        // Prepare intent which is triggered if the
        // notification is selected
        Intent intent = new Intent(this, ResultActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // Build notification
        // Actions are just fake
        Notification noti = new Notification.Builder(this)
            .setContentTitle("Notification Title")
            .setContentText("Click here to read").setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .build();
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        // hide the notification after its selected
        noti.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(0, noti);

      } 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.create_notification_activiy, menu);
        return true;
    }

}

UpdaterServiceManager.java

package com.example.newtrial;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.View;

public class UpdaterServiceManager extends Service {

    private final int UPDATE_INTERVAL = 60 * 1000;
    private Timer timer = new Timer();
    private static final int NOTIFICATION_EX = 1;
    private NotificationManager notificationManager;
    CreateNotificationActiviy not;

    public UpdaterServiceManager() {
        not=new CreateNotificationActiviy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // code to execute when the service is first created
        super.onCreate();
        Log.i("MyService", "Service Started.");
        showNotification();
    }

    public void showNotification()
    {
        final Calendar cld = Calendar.getInstance();

        int time = cld.get(Calendar.HOUR_OF_DAY);
        if(time>12)
        {
                  not.createNotification(null); 

        }
        else
        {
            AlertDialog.Builder alert=new AlertDialog.Builder(this);
            alert.setMessage("Not yet");
            alert.setTitle("Error");
            alert.setPositiveButton("OK", null);
            alert.create().show();
        }
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) 
    {
        return START_STICKY;
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }

}

ResultActivity.java

package com.example.newtrial;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class ResultActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        TextView tv=(TextView)findViewById(R.id.textView1);
        tv.setText("After notification is clicked" );
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.result, menu);
        return true;
    }

}

Logcat

12-10 12:14:04.286: I/Process(872): Sending signal. PID: 872 SIG: 9
12-10 12:14:11.774: I/MyService(893): Service Started.
12-10 12:14:12.094: D/AndroidRuntime(893): Shutting down VM
12-10 12:14:12.094: W/dalvikvm(893): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
12-10 12:14:12.124: E/AndroidRuntime(893): FATAL EXCEPTION: main
12-10 12:14:12.124: E/AndroidRuntime(893): java.lang.RuntimeException: Unable to create service com.example.newtrial.UpdaterServiceManager: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2587)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.ActivityThread.access$1600(ActivityThread.java:141)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1338)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.os.Looper.loop(Looper.java:137)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.ActivityThread.main(ActivityThread.java:5103)
12-10 12:14:12.124: E/AndroidRuntime(893):  at java.lang.reflect.Method.invokeNative(Native Method)
12-10 12:14:12.124: E/AndroidRuntime(893):  at java.lang.reflect.Method.invoke(Method.java:525)
12-10 12:14:12.124: E/AndroidRuntime(893):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-10 12:14:12.124: E/AndroidRuntime(893):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-10 12:14:12.124: E/AndroidRuntime(893):  at dalvik.system.NativeStart.main(Native Method)
12-10 12:14:12.124: E/AndroidRuntime(893): Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.view.ViewRootImpl.setView(ViewRootImpl.java:563)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:269)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.Dialog.show(Dialog.java:281)
12-10 12:14:12.124: E/AndroidRuntime(893):  at com.example.newtrial.UpdaterServiceManager.showNotification(UpdaterServiceManager.java:65)
12-10 12:14:12.124: E/AndroidRuntime(893):  at com.example.newtrial.UpdaterServiceManager.onCreate(UpdaterServiceManager.java:41)
12-10 12:14:12.124: E/AndroidRuntime(893):  at android.app.ActivityThread.handleCreateService(ActivityThread.java:2577)
12-10 12:14:12.124: E/AndroidRuntime(893):  ... 10 more

解决方案

Your error is in UpdaterServiceManager in onCreate and showNotification method.

You are trying to show notification from Service using Activity Context. Whereas Every Service has its own Context, just use the that. You don't need to pass a Service an Activity's Context.I don't see why you need a specific Activity's Context to show Notification.

Put your createNotification method in UpdateServiceManager.class. And remove CreateNotificationActivity not from Service.

You cannot display an application window/dialog through a Context that is not an Activity. Try passing a valid activity reference

这篇关于用服务来运行的背景和创建通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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