Computer >> 컴퓨터 >  >> 프로그램 작성 >> Android

전화 재부팅 후에도 Android 상태 표시 줄 알림을 유지하는 방법은 무엇입니까?

<시간/>

이 예는 Android 상태 표시줄 알림이 휴대전화 재부팅 시 지속되도록 하는 방법을 보여줍니다.

1단계 − Android Studio에서 새 프로젝트를 생성하고 파일 ⇒ 새 프로젝트로 이동하여 필요한 모든 세부 정보를 입력하여 새 프로젝트를 생성합니다.

2단계 − res/layout/activity_main.xml에 다음 코드를 추가합니다.

<전>

3단계 − src/MainActivity에 다음 코드를 추가합니다.

패키지 app.tutorialspoint.com.notifyme;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;public class MainActivity extends AppCompatActivity { @Override protected void onCreate (Bundle storedInstanceState) { super .onCreate( 저장된 인스턴스 상태); setContentView(R.layout.activity_main); }}

4단계 − src/USBStateReceiver에 다음 코드를 추가합니다.

패키지 app.tutorialspoint.com.notifyme; android.annotation 가져오기. SuppressLint;import android.app.Notification;import android.app.NotificationChannel;import android.app.NotificationManager;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.support.v4 .app.NotificationCompat;import android.util.Log;public class USBStateReceiver extends BroadcastReceiver { public static final String NOTIFICATION_CHANNEL_ID ="10001"; 개인 최종 정적 문자열 default_notification_channel_id ="기본"; 부울 연결 =true; @SuppressLint( "UnsafeProtectedBroadcastReceiver") @Override public void onReceive(컨텍스트 컨텍스트, 의도 의도) { NotificationCompat.Builder 빌더 =new NotificationCompat.Builder(context, default_notification_channel_id); builder.setContentTitle( "USB - 알림" ); 문자열 작업 =의도.getAction(); 통나무. e ( "USB" , 작업); 어설션 작업 !=null; builder.setContentText( "연결됨" ); builder.setSmallIcon(R.drawable.ic_launcher_foreground); builder.setAutoCancel( true ); 빌더.setChannelId( NOTIFICATION_CHANNEL_ID ); 알림 알림 =builder.build(); NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (android.os.Build.VERSION. SDK_INT>=android.os.Build.VERSION_CODES. O ) { int 중요도 =NotificationManager. IMPORTANCE_HIGH; NotificationChannel notificationChannel =new NotificationChannel( NOTIFICATION_CHANNEL_ID , "NOTIFICATION_CHANNEL_NAME" , 중요도); 어설션 notificationManager !=null; NotificationManager.createNotificationChannel(notificationChannel); } 어설션 notificationManager !=null; if ( 연결됨 ) { notificationManager.notify( 1 , 알림); 연결된 =거짓; } else { 알림매니저.취소(1); 연결된 =사실; }}

5단계 − AndroidManifest.xml에 다음 코드 추가

<전> <수신기 android:name =".USBStateReceiver"> <응용 프로그램>

응용 프로그램을 실행해 보겠습니다. 실제 Android 모바일 장치를 컴퓨터에 연결했다고 가정합니다. Android 스튜디오에서 앱을 실행하려면 프로젝트의 활동 파일 중 하나를 열고 도구 모음에서 실행 아이콘을 클릭합니다. 모바일 장치를 옵션으로 선택한 다음 기본 화면을 표시할 모바일 장치를 확인하십시오 -

전화 재부팅 후에도 Android 상태 표시 줄 알림을 유지하는 방법은 무엇입니까?