当前位置: 代码迷 >> Android >> 为何下面的代码不能实现定时提醒
  详细解决方案

为何下面的代码不能实现定时提醒

热度:96   发布时间:2016-04-28 02:17:48.0
为什么下面的代码不能实现定时提醒?
想用一个服务Service来实现每60秒向系统发送一个文字提醒和振铃提醒,点button后启动Service,然后Service每60秒先发一个文字提醒消息,然后振铃提醒。
实际测试时,发现这样:
1、点击按钮后,有文字提醒,但随后一振铃,文字提醒就消失了,要怎么样才能有文字提醒消息和振铃提示同时?
2、为什么程序没有能够定时提醒?而只运行了点击按钮的第一次?

public class MainActivity extends Activity {
private NotificationManager notificationManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button b1=(Button)findViewById(R.id.button1);

        b1.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
         Intent intent=new Intent(MainActivity.this,OrderService.class);
         startService(intent);
         }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
  
    }
    
    @Override
    protected void onDestroy(){
     super.onDestroy();
     Intent intent=new Intent(MainActivity.this,OrderService.class);
     stopService(intent);
    }
}


public class OrderService extends Service{
private boolean threadDisable;
private NotificationManager notificationManager;

@Override
public IBinder onBind(Intent intent){
return null;
}

@Override
public void onCreate(){
super.onCreate();
notificationManager=(NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);

Toast toast=Toast.makeText(getApplicationContext(), "Hello, world",Toast.LENGTH_LONG);
toast.show();

new Thread(new Runnable(){
@Override
public void run(){
while(!threadDisable){
try{
         Notification notification1=new Notification();
         notification1.icon=R.drawable.ic_launcher;
         notification1.tickerText="您有新订单!";
         PendingIntent intent=PendingIntent.getActivity(OrderService.this,0, new Intent(OrderService.this,MainActivity.class), 0);
         notification1.setLatestEventInfo(OrderService.this, "通知", "您有新订单", intent);
notificationManager.notify(0,notification1);

Notification notification2=new Notification();
String ringName=RingtoneManager.getActualDefaultRingtoneUri(OrderService.this, RingtoneManager.TYPE_RINGTONE).toString();
notification2.sound=Uri.parse(ringName);
notificationManager.notify(0,notification2);

Thread.sleep(60000);
}catch(InterruptedException e){
}
}
}
}).start();
}

@Override
public void onDestroy(){
super.onDestroy();
this.threadDisable=true;
}
}

------解决思路----------------------
service不是这么用的,你的代码,一看就知道你对service理解很浅,再认真看看service的使用和如何binder吧。
等你认真了解了,再回头看这个代码你就知道了。
------解决思路----------------------
你这样写代码只能执行一次  oncreate在Service启动时初始化 所以只能看到一次的 认真看下Service的启动方法和Activity和Service的数据交互吧
------解决思路----------------------
去找几篇关于android service的文章看看吧,就能理解了,还有建议用timer 定时器做,不要用线程睡眠了...