我已经创建了用于检测otg电缆的应用程序。当我启动它时显示“otg not connected”并且它重复多次,当我插入otg电缆时它仍然重复“otg not connected”并且在一段时间后它显示“ otg连接“!!!!
当我启动应用程序时,它不应该显示任何内容,它应该仅在我插入或插入otg cable时显示。并且它不应该多次重复相同的消息!!!!
MainActivity.class
public class MainActivity extends AppCompatActivity
{
private Process suProcess;
private PendingIntent pendingIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getRoot();
startAlarm();
}
private void getRoot()
{
try
{
suProcess = Runtime.getRuntime().exec("su");
}
catch (IOException e)
{
}
}
private void startAlarm()
{
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
int interval = 1000;
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
}
AlarmReceiver.class
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context,Intent intent)
{
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
if(contents.length == 0)
{
Toast.makeText(context,"otg not connected",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context,"otg connected",Toast.LENGTH_SHORT).show();
}
}
}
答案 0 :(得分:0)
如果您不想在appstart上发出警报,请不要将其放在onCreate方法中。我会把这个方法放在一个Runnable中,这个方法会调用startalarm。在AlarmReceiver类中会添加一个静态int
private static int conn_length = 0;
并在onReceive方法中,如果要生成以下代码:
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
if(contents.length == conn_length){
return;
}
else{
conn_length = contents.length;
}
if(conn_length == 0)
{
Toast.makeText(context,"otg not connected",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(context,"otg connected",Toast.LENGTH_SHORT).show();
}
这样,如果连接状态发生变化,您只能获得一条消息。
编辑:
Runnable实现的示例。
在onCreate方法中添加此
Handler handler = new Handler();
handler.post(alarmUpdater);
在课堂的另一部分:
public Runnable alarmUpdater= new Runnable() {
@Override
public void run() {
startalarm();
}
};