分钟变化时不调用 TIME_TICK

Far*_*Ali 5 java android

我面临的问题是,当时间更改时,TIME_TICK 仅在应用程序运行时调用。但我希望即使应用程序正在运行或不使用广播接收器也能调用它。

主要活动

public class MainActivity extends Activity {
      @Override
      public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Toast.makeText(getApplicationContext(), "Checking", Toast.LENGTH_LONG).show();
      }
    } 
Run Code Online (Sandbox Code Playgroud)

我的广播接收器

public class MyBroadastReceiversextends BroadcastReceiver
{

    @Override
    public void onReceive(Context arg0, Intent arg1) {

        Toast.makeText(arg0, "Toast Receive", Toast.LENGTH_LONG).show();
    }
}
Run Code Online (Sandbox Code Playgroud)

菜单文件

    <receiver android:name="com.example.serviceschecking.MyBroadastReceivers" android:enabled="true" android:exported="true">  
       <intent-filter >
           <action android:name="android.intent.action.TIME_TICK"/>
       </intent-filter>
</receiver> 
Run Code Online (Sandbox Code Playgroud)

Opi*_*chs 5

如 API 中所述,您必须以编程方式注册此意图:

广播操作:当前时间已更改。每分钟发送一次。您无法通过清单中声明的​​组件接收此信息,只能通过使用 Context.registerReceiver() 显式注册它。

您必须在您的 mainActivity 中注册它:

      IntentFilter mTime = new IntentFilter(Intent.ACTION_TIME_TICK);
      registerReceiver(YourReceiver, mTime);
Run Code Online (Sandbox Code Playgroud)