基于安卓,点击状态栏图标,查询笔记内容的代码
时间: 2023-12-13 20:04:00 浏览: 75
你可以尝试以下代码:
1. 在 AndroidManifest.xml 中添加权限:
```
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
2. 在 MainActivity.java 中添加以下代码:
```java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_NOTE = 1;
private static final String NOTE_MIME_TYPE = "text/plain";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 设置状态栏图标点击事件
NotificationManager notificationManager = getSystemService(NotificationManager.class);
NotificationChannel channel = new NotificationChannel("note", "Note", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
Notification notification = new NotificationCompat.Builder(this, "note")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("Search note")
.setContentText("Click to search note")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setContentIntent(getNoteSearchPendingIntent())
.build();
notificationManager.notify(1, notification);
}
private PendingIntent getNoteSearchPendingIntent() {
Intent intent = new Intent(Intent.ACTION_SEARCH);
intent.setType(NOTE_MIME_TYPE);
intent.putExtra(SearchManager.QUERY, "");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return PendingIntent.getActivity(this, REQUEST_CODE_NOTE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
```
3. 在 AndroidManifest.xml 中添加以下代码:
```xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
```
4. 在笔记应用中添加以下代码:
```java
public class NoteActivity extends AppCompatActivity {
private EditText mEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note);
mEditText = findViewById(R.id.edit_text);
// 将笔记内容保存到文件中
File file = new File(getExternalFilesDir(null), "note.txt");
try {
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(mEditText.getText().toString().getBytes());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
5. 在 AndroidManifest.xml 中添加以下代码:
```xml
<activity android:name=".NoteActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
```
现在你可以在状态栏中点击图标,然后输入笔记内容进行搜索了。
阅读全文