public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context,"您的手機已經開啓",Toast.LENGTH_LONG).show(); //手機開啓跳轉到主頁面 Intent intent1 = new Intent(context, MainActivity.class); intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(intent1); } } //主頁面
public class MainActivity extends AppCompatActivity { //全集變量 private Button stop; private MediaPlayer mediaPlayer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //找到控件 stop = (Button) findViewById(R.id.stop); mediaPlayer = MediaPlayer.create(this, R.raw.womendemingtian); //音樂播放 mediaPlayer.start(); //點擊停止播放音樂停止 stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mediaPlayer.stop(); } }); } } //主頁面佈局
<Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="停止播放" android:id="@+id/stop"/> //加權限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission> //在清單列表註冊
<receiver android:name=".MyReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver>