Java 我的服务在安卓上不起作用,为什么?
这里是代码:Java 我的服务在安卓上不起作用,为什么?,java,android,Java,Android,这里是代码: public class MyServeice extends Service { private Timer pushTimer; private final int NOTEF_ID = 1234; NotificationManager manager; @Override public IBinder onBind(Intent arg0) { return null; } @Overr
public class MyServeice extends Service
{
private Timer pushTimer;
private final int NOTEF_ID = 1234;
NotificationManager manager;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public void onCreate()
{
Log.i("MyActivity", "1");
//pushTimer = new Timer();
manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onDestroy()
{
Log.i("MyActivity", "2");
//pushTimer.cancel();
}
@Override
public void onStart(Intent intent, int startid)
{
Log.i("MyActivity", "3");
//pushTimer.schedule(new TimerTask()
//{
// @Override
// public void run()
// {
Notification not = new Notification(R.drawable.ic_launcher, "Custom notification", System.currentTimeMillis());
PendingIntent notIntent = PendingIntent.getActivity(this , 0, new Intent(this, MainActivity.class), 0);
not.setLatestEventInfo(this, "Title", "Text", notIntent);
manager.notify(NOTEF_ID, not);
manager.cancel(NOTEF_ID);
// }
//}, 0L, 60L * 1000);
}
}
我试着从我的MainActivity类开始(之前我认为问题出在timer中,但现在我对它进行了注释)。
起始代码如下:
public class MyServeice extends Service
{
private Timer pushTimer;
private final int NOTEF_ID = 1234;
NotificationManager manager;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public void onCreate()
{
Log.i("MyActivity", "1");
//pushTimer = new Timer();
manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
@Override
public void onDestroy()
{
Log.i("MyActivity", "2");
//pushTimer.cancel();
}
@Override
public void onStart(Intent intent, int startid)
{
Log.i("MyActivity", "3");
//pushTimer.schedule(new TimerTask()
//{
// @Override
// public void run()
// {
Notification not = new Notification(R.drawable.ic_launcher, "Custom notification", System.currentTimeMillis());
PendingIntent notIntent = PendingIntent.getActivity(this , 0, new Intent(this, MainActivity.class), 0);
not.setLatestEventInfo(this, "Title", "Text", notIntent);
manager.notify(NOTEF_ID, not);
manager.cancel(NOTEF_ID);
// }
//}, 0L, 60L * 1000);
}
}
startService(新意图(this,MyServeice.class))代码>
并没有显示服务类的日志,所以我决定服务根本并没有启动。应用程序未崩溃并正常启动。你能检查一下我的代码吗?你在MyServeice课上犯了一个错误
你用
@Override
public void onStart(Intent intent, int startid)
&在服务生命周期中,没有启动(..)方法
尝试此方法而不是上面的方法
@Override
public int onStartCommand(Intent intent, int flags, int startId)
编辑:
&第二,您必须在清单文件中声明服务,如:
<manifest ... >
...
<application ... >
<service android:name=".MyServeice" />
...
</application>
</manifest>
...
使用此方法:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {}
下面是关于服务的好教程:问题已结束。将有关我的服务类的信息添加到清单中解决了我的问题。您的服务是否已在清单中注册?请同时发布您的清单。发布您正在打开服务的活动的代码。您可以使用MyServeice。此
引用TimerTask
中的外部类。